Tag Archives: authentication

Access Token, Refresh Token

https://medium.com/@bantic/more-oauth-2-0-surprises-the-refresh-token-1831d71f4af6#.i6aemn6ol

https://auth0.com/learn/refresh-tokens/

Since access tokens are so powerful yet also so potentially insecure, their risk is mitigated by giving them short-lived expiration windows.

Hence an access token returned by Azure iOS client framework will last for 1 hour. Within that hour, you can access data from your Easy Table. After an hour, you will get an authentication error.

However, this introduces another difficulty for web programmers — how to continue to access data on behalf of your users when their access tokens expire? Enter refresh tokens.

Refresh Token

What is a Refresh Token?

A Refresh Token is a special kind of token that can be used to obtain a renewed access token. An access token allows accessing a protected resource (i.e https://abc-123.azurewebsites.net/TodoItems) at any time.

You can keep requesting new access tokens until the refresh token expires.

Refresh tokens must be stored securely by an application because they essentially allow a user to remain authenticated forever.

How Refresh Tokens work

An Access Token is required to access a protected resource. Thus, a client will use a Refresh Token to get that Access Token, which is issued by the Authentication Server.

Although Access Tokens can be renewed at any time using Refresh Tokens, they should be renewed when old ones have expired, or when getting access to a new resource for the first time. Refresh Tokens can also expire but are rather long-lived. They are usually subject to strict storage requirements to ensure they are not leaked. Nevertheless, they can be blacklisted by the authorization server.

A Refresh Token is used to obtain new Access Tokens (and access protected resources) until it is expires (which may take a long time).

Access Tokens must also be kept secret, but due to its shorter life, security considerations are less critical.

In the case of Azure Active Directory refresh tokens

When refresh tokens were first explained to me, I was told something along the lines that a refresh token is used to refresh an access token. The word “refresh” certainly implies that that is the case. When I thought about it this way I imagine the access token as a battery-operated toy with dead batteries. It is “stale”, and cannot be used. In order to “refresh” it you replace the batteries and now the freshened toy works again.

But that is not what a refresh token does. Access tokens do not become stale only to be refreshed later on and reused. Access tokens expire, never to be valid again. A refresh token is not tied to an access token. It is simply used to get a new, valid access token when you need it.

How do you know when your access token is not valid? By attempting to use it and having the OAuth provider reject it.

Azure AAD token notes

http://cgillum.tech/2016/03/07/app-service-token-store/

Please, correct me if I’m wrong:
– the first time end-user uses my xamarin app (google authentication), he gets a token that will expire in 1 hour, after that, he finishes use my app and closes it.
– Three hours later, he opens the app and tries to access data from an azure table (for example): in this case, now, his “old” token is expired so, using your code above, he gets a “new” refresh token and he is able to obtain his data from azure. Perfect.

And now, what happens? will this new refreshed token expire in one hour like the first one?
So, does he have to get a new one in 72-hours? And so on with the cycle?
If not, “a fresh re-auth by the end-user will be required to get a new, non-expired authentication token”?

cgillum says:
May 25, 2016 at 9:31 am
Your understanding is correct. Refreshed tokens will have the same lifetime as the original tokens (1 hour in the case of Google). The tokens can be refreshed at anytime before or within the 72-hour window without requiring a re-auth. This will be a regular cycle within your app.

When the Access Token expires, you can use the Refresh Token to get a new Access Token. This Access token, along with the 1st access token, all expire in 1 hour. You can continue to use refresh token to request access tokens. The standard request token expiration date is 14 days. After 14 days, you need to sign in again.

Authenticate web service urls part 2

ref – https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens

In part 1, we set up a simple project where we let a client create a user through a public URL /setup, then display all the users via /api/users.

Next, let’s make sure that we can authenticate a user and then protect those routes using Express route middleware and requiring a token.

Authenticating and Creating a Token

We then use Postman to query it like so

POST_authen_create_user

why – form-urlencoded vs form-data

To summarize, form-urlencoded has a low fixed cost, but high variable for special characters, so application/x-www-form-urlencoded is good for short messages like those found in most basic web forms. On the other hand, form-data has a high fixed costs due to the additional MIME headers prepended to each message chunk, but low variable cost for special characters, so multipart/form-data is good for long messages such images or large files.

Now, copy that whole token string somewhere to be used later.

Protecting URLS

Now let’s protect /api and /api/users by forcing clients to provide the token whenever they need to access these urls.

So for our var apiRoutes that we get from express.Routes(), we have that routing variable use a function to process requests.

We make it run a middleware function by using .use on it. We basically check the requests’ headers to see if the key x-access-token has a valid value. That value should be the token value we received earlier. If the token is valid, everything checks through via the next(), and we run to the apiRoutes.get(‘/users’, function(req, res) {}); function definitions which gets the user from the database and gives it back as a json response.

For example, if you were to hit http://localhost:8080/api/ or http://localhost:8080/api/ it will run this function definition first….see that x-access-token has not been defined in the headers and return you an error json message.

When the tokens are valid, you’ll see the valid json data returned. If you are to use POSTman, here’s what it should look like:

x-access-token_get_user

Authenticate web service urls part 1

ref – https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens

We’ll build a quick API using Node and Express and we’ll be using POSTman to test it.

Create an application directory, then in your mac terminal:

$ npm install express body-parser morgan mongoose jsonwebtoken –save

  • express is the popular Node framework
  • mongoose is how we interact with our MongoDB database
  • morgan will log requests to the console so we can see what is happening
  • body-parser will let us get parameters from our POST requests
  • jsonwebtoken is how we create and verify our JSON Web Tokens

The –save modifier will also save these packages to our package.json file.

After all the packages have been downloaded, you will see a node_modules folder. The packages are installed inside there.

User Model (/models/user.js)

In your project directory, create models folder. Then inside that models folder, you create user.js file.

The user model that we define will be used when creating and getting users. To create a Mongoose model, let’s create the file app/models/user.js

Now let’s create a configuration file to store configuration settings for our application.

config.js (/config.js)

Basically, the database is hosted on our local machine.

  • secret: used when we create and verify JSON Web Tokens
  • database: the URI with username and password to your MongoDB installation

Note: You should be running GULP for your working environment so that when you make changes, it will automatically help you save. In your gulpfile.js, make sure that gulp.task, script has the string “server.js”.

server.js

Set up all the package variables and db connections

Then we have our app use body parser for POST, morgan for throwing logs to console outputs, and set our config file’s object secret to web token’s super secret key.

public URL for home

Let’s create public URL for the home page and then start the server

Open up a browser and go to

http://localhost:8080/

You’d get the json response:

{“message”:”(GET http://localhost:8080/)”}

If you look at your mac terminal, you’ll also see morgan’s log outputs.

Finally, we put a url where the server creates and inserts a new user along with a password into the database.

Public URL to create a user

Open up a browser and put in

http://localhost:8080/setup

You will get the json data back:

{“success”:true}

This means that you have successfully inserted the user rtsao with pw compaq.

Showing Users through public URL

Put the following code above our routes:

What this means is that the variable apiRoutes always has url start with /api.

Whatever url we specify for a certain request, its always /api/url paired with GET or POST..etc.

Hence in apiRoutes.get(‘/users’…) function definition, it just means for (GET http://localhost:8080/api/users) we will return all the users from the database.

So now when we hit:

http://localhost:8080/api/users

we get:

[{“_id”:”55973f3702e8b0094967b544″,”name”:”rtsao”,”password”:”compaq”,”admin”:true,”__v”:0},{“_id”:”55977f4b06112d75860f9af6″,”name”:”rtsao6680″,”password”:”abcde12345″,”admin”:true,”__v”:0}]

Full Code

/config.js

/server.js

/models/user.js