Imran Ahmad Mughal
Imran Ahmad Mughal

Reputation: 22

Web API in MVC project (Authentication)

I have ASP.NET MVC project and using Form Authentication (Cookie base) with ASP.NET Identity. I added WEB API controller into that project. Now What I want is for MVC project it should use Form Authentication using Cookie but for API it should use token base, How I can configure it.

Regards, Imran Ahmad

Upvotes: 1

Views: 468

Answers (1)

Vivek Singh
Vivek Singh

Reputation: 1113

Firstly install these NuGet packages,

1.Install-Package Microsoft.AspNet.WebApi.Owin

2.Install-Package Microsoft.Owin.Host.SystemWeb

3.Install-Package Microsoft.Owin.Security.OAuth

then, the project must be having a StartUp.cs file.
Add this code to your file

    OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/api/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(2),                
        Provider = new AuthorizationServerProvider()
    };

    // To Generate token
    app.UseOAuthAuthorizationServer(OAuthOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

Add this code to new AuthorizationServerProvider.cs file

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

     public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
     {
         var identity = new ClaimsIdentity(context.Options.AuthenticationType);
         context.Validated(identity);
     }
}

You can test the code using Postman API client by posting to your endpoint

yourwebsite/api/token 

along with grant_type, username and password in the
x-www-form-Urlencoded tab of the postman.

The response of which you will get an access_token, put this access token put it in your header while calling your Resource controller.

For further references refer http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/.

Upvotes: 2

Related Questions