GithubHelp home page GithubHelp logo

auth0-blog / nodejs-jwt-authentication-sample Goto Github PK

View Code? Open in Web Editor NEW
688.0 62.0 298.0 26 KB

A NodeJS API that supports username and password authentication with JWTs

License: MIT License

JavaScript 100.00%

nodejs-jwt-authentication-sample's Introduction

NodeJS JWT Authentication sample

This is a NodeJS API that supports username and password authentication with JWTs and has APIs that return Chuck Norris phrases. How awesome is that?

Available APIs

User APIs

POST /users

You can do a POST to /users to create a new user.

The body must have:

  • username: The username
  • password: The password
  • extra: Some extra information you want to save from the user (It's a string). This could be a color or anything at all.

It returns the following:

{
  "id_token": {jwt},
  "access_token": {jwt}
}

The id_token and access_token are signed with the secret located at the config.json file. The id_token will contain the username and the extra information sent, while the access_token will contain the audience, jti, issuer and scope.

POST /sessions/create

You can do a POST to /sessions/create to log a user in.

The body must have:

  • username: The username
  • password: The password

It returns the following:

{
  "id_token": {jwt},
  "access_token": {jwt}
}

The id_token and access_token are signed with the secret located at the config.json file. The id_token will contain the username and the extra information sent, while the access_token will contain the audience, jti, issuer and scope.

Quotes API

GET /api/random-quote

It returns a String with a Random quote from Chuck Norris. It doesn't require authentication.

GET /api/protected/random-quote

It returns a String with a Random quote from Chuck Norris. It requires authentication.

The JWT - access_token must be sent on the Authorization header as follows: Authorization: Bearer {jwt}

Running it

Just clone the repository, run npm install and then node server.js. That's it :).

If you want to run it on another port, just run PORT=3001 node server.js to run it on port 3001 for example

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

Author

Auth0

License

This project is licensed under the MIT license. See the LICENSE file for more info.

What is Auth0?

Auth0 helps you to:

  • Add authentication with multiple authentication sources, either social like Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, amont others, or enterprise identity systems like Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider.
  • Add authentication through more traditional username/password databases.
  • Add support for linking different user accounts with the same user.
  • Support for generating signed Json Web Tokens to call your APIs and flow the user identity securely.
  • Analytics of how, when and where users are logging in.
  • Pull data from other sources and add it to the user profile, through JavaScript rules.

Create a free account in Auth0

  1. Go to Auth0 and click Sign Up.
  2. Use Google, GitHub or Microsoft Account to login.

Use Postman

Postman provides a powerful GUI platform to make your API development faster & easier, from building API requests through testing, documentation and sharing

Here is a small collection to highlight the features of this sample API.

Run NodeJS JWT Authentication in Postman

nodejs-jwt-authentication-sample's People

Contributors

amingilani avatar babeard avatar chenkie avatar diegopoza avatar enaqx avatar fhemberger avatar juukie avatar kmaida avatar lukeocodes avatar mehreencs87 avatar mgonto avatar mseimys avatar patrickjs avatar unicodeveloper 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  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  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  avatar  avatar  avatar  avatar

Watchers

 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  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

nodejs-jwt-authentication-sample's Issues

How to exclude a route from jwt token verification

How to exclude a route from jwt token verification

router.use((req, res, next) => {
const r = req;
// check header or url parameters or post parameters for token
// const token = req.body.token || req.query.token || req.headers['x-access-token'];
const token = req.body.token || req.query.token || req.headers.authorization;
// decode token
if (token) {
    // verifies secret and checks exp
    jwt.verify(token, req.app.get('superSecret'), (err, decoded) => {
        if (err) {
            // res.json({ success: false, message: 'Failed to authenticate token.' });
            return res.status(401).send({
                success: false,
                message: 'Failed to authenticate token.'
            });
        } else {
            // if everything is good, save to request for use in other routes
            r.decoded = decoded;
            next();
            // console.log(decoded);
        }
        // return {};
    });
} else {
    // if there is no token
    // return an error
    return res.status(403).send({
        success: false,
        message: 'No token provided.'
    });
}
});

In this I want to exclude some router from token verification (ex: user registration route). How can I do that.
I have tried putting that route above jwt.verfication code but still it is not working

random-quote occasionally returns empty string as a quote

Currently, the API can occasionally return empty when fetching quotes. This is due to zero-indexing when selecting from the quotes array and the use of length to get the quote position. The way it's randomizing, it can currently try to return a quote at one position after the last quote.

A fix is forthcoming shortly.

jwt issuer invalid. expected: https://login.microsoftonline.com/******/v2.0

Hi,

When I tried to run nodejs-sso example, everything works fine until const {jwt} = auth.verifyJWT(req, {scp: 'access_as_user'}); throws the error jwt issuer invalid. expected: https://login.microsoftonline.com/*****/v2.0. When I checked the expected url and the issuer i placed in the code, they are exactly the same. However, when i decode jwt token i see that iss claim is different than this.

Why do i get a jwt token with a different iss claim ?

NOTE: The iss claim in the decoded token is "https://login.microsoftonline.com/a2b0309e-37c1-486d-bdbd-4d91b7d25cd5/v2.0".

How to access the 'extra' information on the client side?

Thank you for the great code!

I have a question - the returning token contains the username and the 'extra' field. However since they seem to be encrypted, how will my client decrypt that without including the secret on the client side?

Thank you!

UnauthorizedError: jwt audience invalid. expected: undefined

Sorry, probably a PICNIC but I've converted https://github.com/connor11528/vuejs-auth-frontend to VueJS2 and it's wired up to an instance of this server; LogIn/SignUp/LogOut are all working and the server's creating, memorizing & returning an id_token back fine as long as the server instance is up. However when I call the protected random-quote I get a 401 response and the server logs

UnauthorizedError: jwt audience invalid. expected: undefined

..in the console.

getQuote() {
	    let token = auth.getAuthHeader();
		console.log(token)
        this.$http.get('http://localhost:3001/api/protected/random-quote', { headers: {
		Authorization: token
		}})
		  .then((data) => {
            this.quote = data;
          })
          .catch((err) => console.log(err))
      }

If I remove the authorization header the server logs the following in the console:

UnauthorizedError: No Authorization header was found

I'm certain I'm passing in the Authorization header in the "Bearer {jwt}" format correctly. What else am I missing?

Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImsiLCJpZCI6MiwiaWF0IjoxNDkzOTQyMjQ5LCJleHAiOjE0OTM5NjAyNDl9.RVrM7JL7D0ClQ-zOJijdJxZnUQHXVZKFO8wBvN469C8
xhr.js?14ed:177 GET http://localhost:3001/api/protected/random-quote 401 (Unauthorized)
dispatchXhrRequest @ xhr.js?14ed:177
xhrAdapter @ xhr.js?14ed:12
dispatchRequest @ dispatchRequest.js?91bc:52
xhr.js?14ed:177 XHR finished loading: GET "http://localhost:3001/api/protected/random-quote".
dispatchXhrRequest @ xhr.js?14ed:177
xhrAdapter @ xhr.js?14ed:12
dispatchRequest @ dispatchRequest.js?91bc:52
SecretQuote.vue?325d:31 Error: Request failed with status code 401
    at createError (eval at <anonymous> (app.js:782), <anonymous>:15:15)
    at settle (eval at <anonymous> (app.js:890), <anonymous>:18:12)
    at XMLHttpRequest.handleLoad (eval at <anonymous> (app.js:761), <anonymous>:77:7)

The app fails with "Cannot GET /

image

My aim is to really talk to you about working together on a really cool tutorial for Aurelia users (I am aware of your blog, your article on Rob Eisenberg's blog, your use of Paul van Bladel's aurelia plugin and I am pretty good friend with Eugenio and Matthias.

So, it feels silly to trip on the most simple first step. I am using node v5.5.1

Can you tell me what am I missing, please?

package.json contains references to 'in-memory-todo'

Minor issue.

Seems like the packages.json is based on the one from the 'in-memory-todo' project. All URL's, name, description etc still refer to that project.

package.json should be edited to contain correct information.

UnauthorizedError: jwt issuer invalid. expected: undefined

I followed instructions, and even tried changes shown in issue #30 because I was initially receiving the invalid audience error. Now I'm getting the invalid issuer error when I authenticate and try to hit a protected API. I'm using this example for my app: https://auth0.com/blog/adding-authentication-to-react-native-using-jwt/

Sign up and Login seem to work (aside from errors when I try to sign up the same user twice and try to login twice).

Any ideas?

I think the only difference is that my react-native app that uses this API as an end point fetches with my local IP instead of localhost.

Thanks!

Can't start server

Hi not sure if I did understood the instructions but after cloning the repo, running npm install and then node server.js I get the following error:

events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE :::3001
    at Object.exports._errnoException (util.js:870:11)
    at exports._exceptionWithHostPort (util.js:893:20)
    at Server._listen2 (net.js:1234:14)
    at listen (net.js:1270:10)
    at Server.listen (net.js:1366:5)
    at Object.<anonymous> (/Users/omar/Development/nodejs-jwt-authentication-sample/server.js:40:24)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)

Any help will be appreciated.

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.