Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OAuth bearer token not working

I have a minimal setup of an auth-provider, which sets claims-identity

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

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        if (context.UserName != context.Password)
        {
            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);
    }
}

I am trying to access hello-world-api, which is giving unauthorized access error.

public class HelloWorldApiController : ApiController
{

    [HttpGet]
    [Route("api/hello")]
    //[AllowAnonymous]
    [Authorize]
    public HttpResponseMessage FetchAllEnum()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "Hello World!!!");
    }
}

But I am getting 401/unauthorized access for the above API. I do get the bearer token back to the web-api and I am also passing it to the server as Bearer ABCD****. I do see that the authorization header is set while debugging in Visual Studio.

If I debug the AuthorizeAttribute, I am getting user.Identity.IsAuthenticated as false, which is actually causing the issue. But given that I do see the Authorization header set and I have set claims details in OAuthProvider, why is it that the AuthorizeAttribute is not reading that information?

Note: This is a Web API project so there are no references to the MVC AuthorizeAttribute.

Here is the OWIN setup:

public static class WebApiConfig
{
    public static HttpConfiguration Register()
    {
        var config = new HttpConfiguration();
        config.MapHttpAttributeRoutes();
        //config.SuppressDefaultHostAuthentication(); //tried with/without this line
        config.Filters.Add(new AuthorizeAttribute());
        config.EnableCors(new EnableCorsAttribute("*", "*", "*", "*"));
        return config;
    }
}

public class OwinConfiguration
{
    // ReSharper disable once UnusedMember.Local
    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);
        app.UseCors(CorsOptions.AllowAll);
        app.UseWebApi(WebApiConfig.Register());
    }

    private void ConfigureOAuth(IAppBuilder app)
    {
        var options = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
            Provider = new SimpleAuthorizationProvider()
        };

        app.UseOAuthAuthorizationServer(options);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}
like image 463
harishr Avatar asked May 20 '15 09:05

harishr


People also ask

How do I authorize a Bearer Token?

Bearer token The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value. For added security, store it in a variable and reference the variable by name.

How does OAuth Bearer Token work?

Bearer Tokens are the predominant type of access token used with OAuth 2.0. A Bearer Token is an opaque string, not intended to have any meaning to clients using it. Some servers will issue tokens that are a short string of hexadecimal characters, while others may use structured tokens such as JSON Web Tokens.

Does Bearer Token have an expiry?

A valid bearer token (with active access_token or refresh_token properties) keeps the user's authentication alive without requiring him or her to re-enter their credentials frequently. The access_token can be used for as long as it's active, which is up to one hour after login or renewal.

Is Bearer Token and OAuth same?

Bearer tokens are for OAuth2 authentication. A bearer token is an encoded value that generally contains the user ID, authenticated token and a timetamp. It is most commonly used in REST APIs. If the API supports OAuth2 then it'll use a bearer token.


1 Answers

to make it work config.Filters.Add(new HostAuthenticationAttribute("bearer")); needed to add this line beofre authorize attribute...

public static HttpConfiguration Register()
{
    var config = new HttpConfiguration();
    config.MapHttpAttributeRoutes();

    config.Filters.Add(new HostAuthenticationAttribute("bearer")); //added this
    config.Filters.Add(new AuthorizeAttribute());
    config.EnableCors(new EnableCorsAttribute("*", "*", "*", "*"));
    return config;
}
like image 88
harishr Avatar answered Oct 01 '22 13:10

harishr