Ahasanul Banna
Ahasanul Banna

Reputation: 123

Token based authentication in ASP.NET Web API 2 not working

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
        app.UseCors(CorsOptions.AllowAll);
        var myProvider = new MyAuthorizationServerProvider();
        OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = myProvider
        };
        app.UseOAuthAuthorizationServer(options);
        app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions());
        HttpConfiguration config = new HttpConfiguration();
        WebApiConfig.Register(config);
    }
}

Token generate successfully but when I use this token to access Authorize controller that not work properly. Always response message show "Authorization has been denied for this request" Here postman send request for generate token

This is my MyAuthorizationServerProvider class

 public class MyAuthorizationServerProvider: OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        if(context.UserName== "admin" && context.Password == "admin")
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
            identity.AddClaim(new Claim("username", "admin"));
            identity.AddClaim(new Claim(ClaimTypes.Name, "Admin Ahasanul Banna"));
            context.Validated(identity);
        }
        else if (context.UserName=="user" && context.Password=="user")
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
            identity.AddClaim(new Claim("username", "user"));
            identity.AddClaim(new Claim(ClaimTypes.Name, "User Ahasanul Banna"));
            context.Validated(identity);
        }
        else
        {
            context.SetError("Invalid_grant", "Provided username & password is incorrect");
            return;
        }
    }
}

And my AuthorizeAttribute class

    public class AuthorizeAttribute :System.Web.Http.AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        if (!HttpContext.Current.User.Identity.IsAuthenticated)
        {
            base.HandleUnauthorizedRequest(actionContext);
        }
        else
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
        }

    }
}

When I access any Authorize action using this token server response "Authorization has been denied for this request." messageHere Postman send request

    [Authorize]
    [HttpGet]
    [Route("authenticate")]
    public IHttpActionResult GetForAuthenticate()
    {
        var identity = (ClaimsIdentity)User.Identity;
        return Ok("Hello" + identity.Name);
    }
    [Authorize(Roles ="admin")]
    [HttpGet]
    [Route("authorize")]
    public IHttpActionResult GetForAdmin()
    {
        var identity = (ClaimsIdentity)User.Identity;
        var roles = identity.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value);

        return Ok("Hello" + identity.Name +" Role: " +string.Join(",",roles.ToList()));
    }

How to solve this issue?

Upvotes: 1

Views: 3512

Answers (1)

Roman Marusyk
Roman Marusyk

Reputation: 24619

Check this code

public void Configuration(IAppBuilder app)
{
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
    app.UseCors(CorsOptions.AllowAll);
    var myProvider = new MyAuthorizationServerProvider();
    OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = myProvider
    };
    app.UseOAuthAuthorizationServer(options);
    app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions());
    HttpConfiguration config = new HttpConfiguration();
    WebApiConfig.Register(config);
}

here you use an authorization server with configured options (OK):

app.UseOAuthAuthorizationServer(options);

then override it without options (NOT OK)

app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions());

Just remove the second app.UseOAuthAuthorizationServer and try again.

Also you forgot to add

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

Upvotes: 2

Related Questions