fbpx

Token based authentication Asp.net mvc web api

Reading time: 5 minutes

Problem

How to authenticate users using token based authentication in Asp.net MVC web API, CORS Support. Solution of the error message “Authorization has been denied for this request”

Problem to get auth token asp.net mvc
Authorization has been denied for this request

Final output

You can able to get the auth token for specific user and then do authentication on authorized API requests with it in you Web API’s.

As I stated before mostly we use token based approach to implement authentication in order to access secured data.

With the evolution of front-end frameworks nowadays the preferred approach to authenticate users is to use signed token as this token sent to the server with each authenticated request.

This can Allow users to access authorized data by providing username and password and prevent anonymous users from viewing secured data.

So, the solution needs little patience 😉
Let’s get our hands dirty and start implementing it

Solution

1. Open ‘Package manager console’ in Visual studio and  Install the Owin package.

Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

2. Open startup.cs which you will find on the root directory of the project and add the below code at the bottom of Configuration’ method.

public void Configuration(IAppBuilder app)
{
    ...
    
    HttpConfiguration config = new HttpConfiguration();
    WebApiConfig.Register(config);
    app.UseWebApi(config);
}

3. Go to Controllers folder and inside AccountController Add a method with the name ‘FindUser

public async Task<ApplicationUser> FindUser(string userName, string password)
{
    return await UserManager.FindAsync(userName, password);            
}
Add FindUser method inside AccountController
Add FindUser method inside Accont controller

4. Now again Open ‘Package manager console’ and  Install the Owin OAuth package.

Install-Package Microsoft.Owin.Security.OAuth -Version 3.0.0

5. Implement the ‘AuthorizationServerProvider

Add new folder named ‘Providers’ then add new class named ‘AuthorizationServerProvider’ and inherit the class with ‘OAuthAuthorizationServerProvider’ and add override methods inside the class as mentioned below:

public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        using (AccountController _repo = new AccountController())
        {
            ApplicationUser user = await _repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);
    }
}
AuthorizetionServerProvider class
AuthorizationServerProvider class

6. Open startup.cs and call the new method named “ConfigureOAuth” as the first line inside the method “Configuration”, the implementation for this method as below:

public void ConfigureOAuth(IAppBuilder app)
{
    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = new AuthorizationServerProvider()
    };

    // Token Generation
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
ConfigureOAuth-method-implementation-and-call-inside-first-line-on-Configuration-method
Configure auth method insdie Startup class

7. This time install the package to allow CORS for ASP.NET Web API For Website.

Install-Package Microsoft.Owin.Cors

Now open class “Startup.cs” file add the below line of code to the method “Configuration” as the below:

// Generating the token when you try to call it from your browser.
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
Configure token generation

8. You are just a step behind 😉 take a long breath and after successfully configured Token based authentication lets test and get the auth token for a registered user.

Note: If you don’t have any user registered before. please register the user and then get the auth token. 

Open Postman which is the API testing tool and mention these parameters inside the endpoint with ‘yourwebsite/token’ end point call.

Test to get token
Get access token using postman

Notice that the content-type and payload type is “x-www-form-urlencoded” so the payload body will be on form (grant_type=password&username=”demo@gmail.com”&password=”123123”). If all is correct you’ll notice that we’ve received signed token on the response.

As well the “grant_type” Indicates the type of grant being presented in exchange for an access token, in our case it is password.

9. At last just try to access the authorized Web API by passing auth_token to the end point. 

Note: You will get this message when an end point needs authorization
Authorization has been denied for this request

Authorization has been denied for this request
Error message authorization has been denied for this request

10. To authorize the user to this endpoint you need to add Authorization header and pass access_token to it.

Authorization token format should be something like below:
token_type space access_token

Web api with Authroziation token
Access the authorized or secured data using auth token

Share your love with us 😉

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Leave a Reply