How to use token authentication with WebApi .Net

1

I'm looking at some websites about token-based authentication using the OAuth library but a question has come up.

I have a webapi that already exposes services for both an App and a Site. We already have a login system with SQL database running. But now we would like every request in webapi to be validated via token. I installed and configured all necessary packages, edited the Startup class etc but I caught the following problem.

When the site or app logs in using my service, example link , and I validate the login to the bank, I would like to call create the token and save this token the rest of the day to call other actions and controllers. Example, the person has logged in and goes to the menu to register or change the data, when he calls the service again link I place a [Authorize] in the method only or do I still have to do something to compare if the token it created when logging in is still the same?

    
asked by anonymous 05.06.2018 / 15:32

2 answers

1

I have not been very clear about your question, but there is no need for a if to compare token, framework itself does this internally.

>

Example:

On your startup.cs , you'll probably have a method similar to this:

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);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

In this method the endpoint is defined and the time the token will last

You should also have a provider more or less so

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 (IUserRepository _repository = new UserRepository(new Data.DataContexts.OAuthServerDataContext()))
            {
                var user = _repository.Authenticate(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);
        }
}

To authenticate you need to make a request at this endpoint by passing the three information

  • grant_type
  • username
  • password

After this you will receive a token

Finally, in every action that is decorated with [Authorize], the token must be in the header of the request, with the Authorization

If the token is invalid, Forbbiden 403 returns.

Note: The token is composed of information and we can either add or capture such information, note that in block identity.AddClaim(new Claim("role", "user")); the user is added to the token

>     
06.06.2018 / 02:34
1

If the authentication is by token, it must be sent in all requests and validated. As much as the existence as the validity of the token, therefore it is a good practice that it has a time to expire.

You can use ASP.net OAuth2 to generate the token and validate it, see the following link in the Microsoft tutorial to do so. p>     

05.06.2018 / 19:34