Identity 2.0 Web API generates a token for the client

I am developing an ASP.NET Web API application. I need to authenticate users with a username and password and return the line marker back in response. I need to have an attribute [Authorize].

I tried to explore how to do this using the BearerToken mechanism, but without any success. Please provide an example of working code.

+4
source share
2 answers

You need to configure the authorization server (in your case, your authorization server and resource server) to issue access tokens and use them. This can be done using the Owin middleware by defining and the endpoint to which you must send the user credentials (resource owner flow) using grant_type = password. In this way, AS will verify these credentials and provide you with an access token tied to the expiration date that you are configuring.

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 a class with a name SimpleAuthorizationServerProviderand check the credentials in the method GrantResourceOwnerCredentialsas 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 reading here , where you have a good understanding of the components you install and how this thread works.

+7

, , OAuth OWIN.

+2

All Articles