Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identity 2.0 Web API generate token for client

I am developing ASP.NET Web API application. I need to authenticate users by login and password and return string token back in response. I need to have attribute [Authorize] working.

I tried to investigate, how to do it using BearerToken mechanism, but without any success. Please provide working code example.

like image 348
Evgeniya Rudakovskaya Avatar asked Dec 25 '22 04:12

Evgeniya Rudakovskaya


1 Answers

You need to configure your Authorization server (in your case your authorization server and resource server) to issue access tokens and to consume them. This can be done using Owin middle-ware by defining and end point which you should sent user credentials (resource owner flow) to it with grant_type = password. So the AS will validate those credentials and provide you with access token tied to expire date you configure.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);
        //Rest of code is here;
    }

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

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        // Token Consumption
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

    }
}

Now you need to define class named SimpleAuthorizationServerProvider and validate the credentials in the method GrantResourceOwnerCredentials as the code below:

public class SimpleAuthorizationServerProvider : 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 (AuthRepository _repo = new AuthRepository())
        {
            IdentityUser 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);

    }
}

I highly recommend you to read my post here where you have good understanding for the components you are installing and how this flow works.

like image 188
Taiseer Joudeh Avatar answered Jan 06 '23 04:01

Taiseer Joudeh