How to use token authentication with Webapi . Net

Asked

Viewed 1,043 times

1

I’m looking at some sites about token-based authentication using the Oauth library but a question has arisen.

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

When the site or app logs in using my service, example http://meuservico/api/Login, and I validated the login in the bank, I would like to call the creation of the token and save this token the rest of the day for calling other actions and controllers. Example, the person logged in and goes to the registration menu or data change, when he calls the service again http://meuservico/api/Change data i put a [Authorize] in the method only or still need to do something to compare if the token he created when logging in is still the same?

2 answers

1


I was not very clear about your doubt, but there is no need for a if to compare the token, own framework does so internally.

Example:

In his startup.cs , you will 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());
}

This method defines the endpoint and the time that the token will last

You must also have one preview sort of like this

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 on this endpoint passing the three information

  • grant_type
  • username
  • password

After that you will receive as a reply token

At last, in all action which is decorated with the [Authorize] will require the token to be in the header request, with the attribute Authorization

If the token is invalid returns Forbbiden 403.

Obs: the token is composed of information and we can both add and capture such information, note that in the block identity.AddClaim(new Claim("role", "user")); is added the userin the token

  • that was my question. if in [Authorize] he already validated this token. thank you.

1

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

You can use ASP.net’s Oauth2 to generate the token and validate it, see the following microsoft tutorial for this. Authentication for web API

Browser other questions tagged

You are not signed in. Login or sign up in order to post.