Giter Club home page Giter Club logo

asp.net-web-api-oauth-2.0-token-based-authentication's Introduction

ASP.NET WEB API OAuth 2.0 Token Based Authentication

What is token:

Access token is piece of data which is created by server, and used to identify the certain user of given application, and it is used to access particular resource on the server.

Bearer Token Type:

The access token type provides the client with the information required to successfully utilize the access token to make a protected resource request (along with type-specific attributes). The client MUST NOT use an access token if it does not understand the token type. In this example we are using token of type "Bearer" A certain type of token, with the property that anyone can use the token, and it is commonly used. Bearer can be simply understood as "give access to the Bearer of this token." It is recommended to use Bearer token over https, with short expiration time.

Why token based authentication instead of cookie based:

Cookies:

  • Sent with every request
  • Usually supported in browsers
  • Difficult to use cross domain
  • Prone to CSRF

Token:

  • Can be used by hetrogneous clients (browsers, native mobile app etc.)
  • Work cross domain
  • Scalable (no overhead in using web farm when new server is added)
  • Offer more control
  • Loosly Coupled

Demo Application (Server Side/Back End):

  • Open VS 2017
  • File -> Project -> Web -> ASP.NET Web Application

project-tempalate-1

project-tempalate-2

Authorization Server Configuration:

  • App_Start-> startup.cs partial class has the configration code as following:
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new ApplicationOAuthProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    // Note: Remove the following line before you deploy to production:
    AllowInsecureHttp = true
}

// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);

The TokenEndpointPath property is the URL path to the authorization server endpoint. That's the URL that app uses to get the bearer tokens.

The Provider property specifies a provider that plugs into the OWIN middleware, and processes events raised by the middleware.

Here is the basic flow when the app wants to get a token:

  1. To get an access token, the app sends a request to ~/Token.
  2. The OAuth middleware calls GrantResourceOwnerCredentials on the provider.
  3. The provider calls the ApplicationUserManager to validate the credentials and create a claims identity.
  4. If that succeeds, the provider creates an authentication ticket, which is used to generate the token.

gettokenflow

The OAuth middleware doesn't know anything about the user accounts. The provider communicates between the middleware and ASP.NET Identity. For more information about implementing the authorization server.

Configuring Web API to use Bearer Tokens:

In the WebApiConfig.Register method, the following code sets up authentication for the Web API pipeline:

config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

The HostAuthenticationFilter class enables authentication using bearer tokens. The SuppressDefaultHostAuthentication method tells Web API to ignore any authentication that happens before the request reaches the Web API pipeline, either by IIS or by OWIN middleware. That way, we can restrict Web API to authenticate only using bearer tokens.

When the client requests a protected resource, here is what happens in the Web API pipeline:

  1. The HostAuthentication filter calls the OAuth middleware to validate the token.
  2. The middleware converts the token into a claims identity.
  3. At this point, the request is authenticated but not authorized.
  4. The authorization filter examines the claims identity. If the claims authorize the user for that resource, the request is authorized. By default, the [Authorize] attribute will authorize any request that is authenticated. However, you can authorize by role or by other claims. For more information, see Authentication and Authorization in Web API.
  5. If the previous steps are successful, the controller returns the protected resource. Otherwise, the client receives a 401 (Unauthorized) error.

authenticationflow

Testing the application:

testing-auth-flow

  1. Try to access protected resource using POSTMAN (google chrome extension) as anonymous user:

access-protected-resource-anonymous-user

  1. Register as a new user:

register-user

  1. Get Token:

get-token

  1. Try to access protected resource using POSTMAN (google chrome extension) as registered user:

get-protected-resource-reg-user

Main Source: https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api

asp.net-web-api-oauth-2.0-token-based-authentication's People

Contributors

aamir-poswal avatar

Watchers

 avatar  avatar

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.