Monday, February 5, 2018

Token Based Authentication

Token based authentication is a security technique that authenticates the users who attempt to log in to a server, a network, or some other secure system, using a security token provided by the server.

A Token is a piece of data created by server and contains information to identify a particular user and token validity. Token based authentication is stateless and will not store any information about user on the server or in a session. The token will contains the user's information, as well as a special token code that user can pass to the server with every method that supports authentication instead of passing username and passwords directly.

After the token is validated by the service, it is used to establish security context for the client, so the service can make authorization decisions or audit activity for successive user requests.

How Token based authentication works:

  • User provides credentials, which will be verified by server that the information is correct
  • Once server finds the match, a signed token will be sent and stored in user's local storage
  • As part of completing the authorization action, the token is attache to user's request which then be decoded and verified by server
  • A match allows the user to proceed
  • The token will be destroyed when user logs out

Advantages of using Token based authentication:

  • Cross-domain (OR) CORS: Cookies + CORS don't play well across different domains. A token based approach allows you to make AJAX calls to any server, on any domain because you use an HTTP header to transmit the user information
  • Stateless: There is no need to keep a session store, the token is a self-contained entity that conveys all the user information. The rest of the state lives in cookies or local storage on the client side
  • CDN: You can serve all the assets of your app from a CDN and your server side is just the API
  • Decoupling: You are not tied to any particular authentication scheme. The token might be generated anywhere, hence your API can be called from anywhere with a single way of authenticating those calls
  • Mobile ready: When you start working on a native platform cookies are not ideal when consuming a token based approach simplifies this a lot
  • CSRF: Since you are not relying on cookies, you don't need to protect against cross site requests
  • Performance: We are not presenting any hard performance benchmarks here, but a network round trip is likely to take more time than calculating to validate a token and parsing its contents

How to implement Token based Authentication in Web API:

  • Add following using Nuget packages to the Web API project. Microsoft Owin is responsible for regenerating and verifying tokens
    • Microsoft.Owin.Host.SystemWeb
    • Microsoft.Owin.Security.OAuth
    • Microsoft.Owin.Cors
  • Create a new class under App_Start folder and then add following code:
    [assembly: OwinStartup(typeof(WebApisTokenAuth.App_Start.Startup))]
    namespace WebApisTokenAuth.App_Start
    {
    public class Startup
    {
    public void Configuration(IAppBuilder app)
    {
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    var myProvider = new AuthorizationServerProvider();
    OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
        Provider = myProvider,
        RefreshTokenProvider = new RefreshTokenProvider()
    };
    app.UseOAuthAuthorizationServer(options);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

    HttpConfiguration config = new HttpConfiguration();
    WebApiConfig.Register(config);
    }
    }
    }
    Below is the explanation:

    AuthorizationServerProvider: This class is inherited from OAuthorizationServerProvider and overrides methods of it. ValidateClientAuthentication, GrantResourceOwnerCredentials and GrantRefreshToken are some of the noted methods

    RefreshTokenProvider: This class is inherited from IAuthenticationTokenProvider interface and provides implementation for creating the refresh token and regenerate the new access token, if it expired. CreateAsyn() and ReceiveAsync() are the methods used to achieve this
  • Create API controller and Authorize key word at the top to enforce authorization
    • To provide an authentication/authorization, use 'Authorize' key at the top of the action method or the controller
    • Add it at the top of the controller, if it needs to be forced for the entire controller, if not, use it at the Action level

With this I am concluding the illustration. Feel free to share your feedback. Happy Programming !!!

No comments:

Post a Comment