Tonmoy chowdhury
Tonmoy chowdhury

Reputation: 41

How ASP Web API generate new token using refresh token during authorization of Http Request

I am using access token in my asp.net web api. I am using Angular4 as a client application. I got both access token and refresh token after login. i have a authorize attribute to check my Get/Post request is valid or not. i am sending refresh token with access token in every request. When my access token expires my authorize attribute prevent me to access get/post function. How do i authorize my get/post function using valid refresh token and generate new access token during validating the get/post method.

Upvotes: 0

Views: 2416

Answers (1)

user4864425
user4864425

Reputation:

Access token and refresh token are two different things.

The access token is used to access a resource. You send the access token to the resource, on every request.

The refresh token is used to obtain a new access token, without having to send credentials. The refresh token is send to the authorization endpoint. But only after the access token expires (an unauthorized response is returned).

Make sure that the refresh token doesn't expire before the access token expires. Because otherwise you'll have to send the credentials again.

Also note that the refesh token should be kept secret, as it could be used to retrieve tokens without having to send credentials. Always send it over a secured line.

-- update --

The server side of the refresh token

I assume you have an OAuthAuthorizationServerProvider to handle the login. Something like:

internal class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

In order to opt-in you can override GrantRefreshToken to accept refresh tokens:

public override async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
{
    // chance to change authentication ticket for refresh token requests
    var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
    var appUser = await userManager.FindByNameAsync(context.Ticket.Identity.Name);
    var oAuthIdentity = await appUser.GenerateUserIdentityAsync(userManager);
    var newTicket = new AuthenticationTicket(oAuthIdentity, context.Ticket.Properties);

    context.Validated(newTicket);
}

Add a provider to add a Refresh token to the ticket:

internal class ApplicationOAuthRefreshTokenProvider : AuthenticationTokenProvider
{
    public override void Create(AuthenticationTokenCreateContext context)
    {
        var form = context.Request.ReadFormAsync().Result;
        var grantType = form.GetValues("grant_type");

        // If I remember correctly we arrive here for all implemented grant types.
        // But we don't want to add a refresh token to the refresh token itself.

        if (grantType[0] != "refresh_token")
        {
            // 35 days.
            int expire = 35 * 24 * 60 * 60;
            context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddSeconds(expire));
            context.SetToken(context.SerializeTicket());
        }
        base.Create(context);
    }

    public override void Receive(AuthenticationTokenReceiveContext context)
    {
        context.DeserializeTicket(context.Token);
        base.Receive(context);
    }

}

And don't forget to register in the startup:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        // Other statements ...

        // Configure the application for OAuth based flow
        var oAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider("self"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
#if LIVE
            AllowInsecureHttp = false,
#else
            AllowInsecureHttp = true,
#endif
            RefreshTokenProvider = new ApplicationOAuthRefreshTokenProvider()
        };
        app.UseOAuthBearerTokens(oAuthOptions);
    }

Upvotes: 1

Related Questions