GithubHelp home page GithubHelp logo

node-rest-auth's Introduction

node-rest-auth

A Node.js RESTful Authentication Middleware for Express

Install

$ npm install rest-auth

Usage

var auth = require('rest-auth');

// Tell the auth module how to authenticate a user
auth.authenticateUser(function(username, password, callback) {
    User.findOne({ username: username }, function(err, user) {
        if (err) {
            return callback(err);
        }
        if (! user) {
            return callback(null, false, 'User does not exists');
        }
        if (hash(password) !== user.password) {
            return callback(null, false, 'Invalid password');
        }
        // The username and password should be given here
        callback(null, {
            username: username,
            password: user.password
        });
    });
});

// Then, in your app config...
app.configure(function() {
    app.set('view engine', 'hbs');
    app.set('views', consts.VIEW_PATH);
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    
    // rest-auth requires the cookie parser
    app.use(express.cookieParser());
    
    // Load the authentication middleware
    app.use(auth.authenticate({
        expires: '2 hours',
        authRoute: 'auth-token',
        authTokenHash: {
            algorithm: 'sha256',
            salt: 'saltiness'
        }
    });
    app.use(express.logger());
    app.use(app.router);
});

Requesting an auth token

This request:

POST /auth-token

Content-Type: application/json

{
  "username": "bob",
  "password": "somepassword"
}

Will result in something like this (assuming the credentials are correct):

{
    "authToken": "username:1341191721405:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
}

Or something like this in the event of an error:

{
    "error": {
        "message": "User does not exist"
    }
}

Making an Authenticated Request

Once the user has an auth token, they can send that token back to make an authenticated request. This can be done in the query string, the request body, or by using a cookie depending on how you intend your API to be used.

As a query string
GET /something/23?authToken=username:1341191721405:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae
As a request parameter
POST /something

Content-Type: application/json

{
    "param1": "foo",
    "param2": "bar",
    "authToken": "username:1341191721405:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
}

Configuration

There are a lot of ways to control how rest-auth functions. The first place to start is the configuration for the auth.authenticate() method.

expires

The amount of time that an authentication token remains valid before it must be renewed. This can be a number (milliseconds) or a string value with a unit (available unit formats by node-expires). Also, if using cookies, this will be used to determine the expiration for the cookie. Default: "2 hours"

authRoute

The route by which authentication tokens are requested. Default: "auth-token"

authParam

When using query strings or request bodies to send authentication tokens back to the server, this is the parameter to check in. Default: "authToken"

authCookie

When using cookies to send authentication tokens back to the server, this is the cookie name. Default: "authToken"

secureCookie

When using cookies, determines whether to set the secure flag. Default: false

autoRenewToken

Determines if authentication tokens be automatically updated with every request. If set to "cookie-only", auto-renew will only update tokens in cookies. If set to true, non-cookie refreshed tokens will be stored in res.authToken after the authenticate middleware runs and can be sent back to the client in a way of your choosing. Default: true

authTokenHash.algorithm

The hashing algorithm to use. Default: "sha256"

authTokenHash.salt

A string of salt data to use when hashing. If no salt is given, a random salt will be created when the application starts. Default: null

authTokenHash.iterations

How many times should hashing be iterated over. Higher values are more secure, but will add more latency to your server.

Auto-population

By adding another middleware function after auth.authenticate() you can make your user's data fill in the req.user property automatically on authenticated requests (probably much more comfortable for people used to sessions).

app.configure(function() {
    ...
   
    app.use(auth.authenticate({ ... }));
    app.use(auth.populateUser(function(username, callback) {
        User.findOne({ username: username }, function(err, user) {
            if (err) {
                return callback(err);
            }
            callback(null, {
                username: username,
                someValue: user.someValue,
                another: user.another
            });
        });
    });
   
    ...
});

app.get('/foo', function(req, res) {
    if (req.user) {
        console.log(req.user.someValue);
    }
    ...
});

Permissions

node-rest-auth's People

Contributors

kbjr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

node-rest-auth's Issues

npm not working!

Cannot find and install this package throught npm...!

npm search rest-auth
npm http GET https://registry.npmjs.org/-/all/since?stale=update_after&startkey=1354899473057
npm http 200 https://registry.npmjs.org/-/all/since?stale=update_after&startkey=1354899473057
No match found for "rest-auth"

and therefore

npm install rest-auth
npm WARN package.json [email protected] 'contributers' should probably be 'contributors'
npm http GET https://registry.npmjs.org/rest-auth
npm http 404 https://registry.npmjs.org/rest-auth
npm ERR! 404 'rest-auth' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404 
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.

npm ERR! System Linux 3.2.0-36-generic-pae
npm ERR! command "node" "/home/vito/local/bin/npm" "install" "rest-auth"
npm ERR! cwd /home/vito
npm ERR! node -v v0.8.15
npm ERR! npm -v 1.1.68
npm ERR! code E404
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /home/vito/npm-debug.log
npm ERR! not ok code 0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.