11
votes

I've managed to get a simple example code that can create a bearer token and also request new ones by refresh token by reading other forums here on stackoverflow.

The startup class looks like this

public class Startup
{
    public static void Configuration(IAppBuilder app)
    {
        app.UseOAuthBearerAuthentication(
                      new OAuthBearerAuthenticationOptions());

        app.UseOAuthAuthorizationServer(
                      new OAuthAuthorizationServerOptions
                      {
                          TokenEndpointPath = new PathString("/Token"),
                          Provider = new OAuthAuthorizationServerProvider()
                          {
                              OnValidateClientAuthentication = async c =>
                              {
                                  c.Validated();
                              },
                              OnGrantResourceOwnerCredentials = async c =>
                              {
                                  if (c.UserName == "alice" && c.Password == "supersecret")
                                  {
                                      Claim claim1 = new Claim(ClaimTypes.Name, c.UserName);
                                      Claim[] claims = new Claim[] { claim1 };
                                      ClaimsIdentity claimsIdentity =
                                          new ClaimsIdentity(
                                             claims, OAuthDefaults.AuthenticationType);
                                      c.Validated(claimsIdentity);
                                  }
                              }
                          },
                          AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(40),
                          AllowInsecureHttp = true,
                          RefreshTokenProvider = new ApplicationRefreshTokenProvider()
                      });
    }
}

And i also have a class for refresh tokens that looks like this:

public class ApplicationRefreshTokenProvider : AuthenticationTokenProvider
{
    public override void Create(AuthenticationTokenCreateContext context)
    {
        // Expiration time in seconds
        int expire = 2 * 60;
        context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddSeconds(expire));
        context.SetToken(context.SerializeTicket());
    }

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

The way i understand it is that by providing a refresh token you should get a new access token. However what happends in this code is that when i provide a refresh token a new refresh token is created and returned aswell. I want it to create both a access and refresh token the first time when username/password is provided but it doesn't seem correct to create new refresh tokens everytime a request for a new access token is made by using refresh token?

If i for instance, given my code, have a 20 min timespan on the access token and two weeks on the refresh tokens, new access tokens could be created every 20 min which is good, however new refresh tokens would also be created every 20 min but last 2 weeks. Alot of refresh tokens would then be created but not used.

Question:

I just started reading/learning about this a few hours ago so i'm quite unsure but is this the correct behavior or am i supposed to cange my code in some way to only create and return a new access token when a refresh token is provided and not create and return a new refresh token also? Any help or input is highly appreciated, thanks!

1
A refresh token replaces your credential, so basically first time you use your credential to authenticate, then you use the refresh token every time you need to authenticate again. As the result of authentication you get back an auth token which contain identity and claims. Hope this clarifies the concept.Serge Semenov

1 Answers

2
votes

Since no one has answered yet i'm going to provide what i did and which is doing what i was looking for. Therefore I'm going to accept this answer for now.

public class Startup
{
public static void Configuration(IAppBuilder app)
{
    app.UseOAuthBearerAuthentication(
                  new OAuthBearerAuthenticationOptions());

    app.UseOAuthAuthorizationServer(
                  new OAuthAuthorizationServerOptions
                  {
                      TokenEndpointPath = new PathString("/Token"),
                      Provider = new OAuthAuthorizationServerProvider()
                      {
                          OnValidateClientAuthentication = async c =>
                          {
                              c.Validated();
                          },
                          OnGrantResourceOwnerCredentials = async c =>
                          {
                           //Add a string with the current date
                            string dateNow = DateTime.UtcNow.ToString();

                              if (c.UserName == "alice" && c.Password == "supersecret")
                              {
                                  Claim claim1 = new Claim(ClaimTypes.Name, c.UserName);
                                  Claim[] claims = new Claim[] { claim1 };
                                  ClaimsIdentity claimsIdentity =
                                      new ClaimsIdentity(
                                         claims, OAuthDefaults.AuthenticationType);

                                  //Add a claim with the creationdate of the token
                                  claimsIdentity.AddClaim(new Claim("creationDate", dateNow));

                                  c.Validated(claimsIdentity);
                              }
                          }
                      },
                      AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(40),
                      AllowInsecureHttp = true,
                      RefreshTokenProvider = new ApplicationRefreshTokenProvider()
                  });
}
}

And in the ApplicationRefreshTokenProvider i made theese changes

public class ApplicationRefreshTokenProvider : AuthenticationTokenProvider
{
    public override void Create(AuthenticationTokenCreateContext context)
    {
    //Get the claim which holds creation date
     DateTime creationDate = Convert.ToDateTime(clientid.Claims.Where(c => c.Type == "creationDate").Single().Value);
     //Create a variable holding current time minus 30 seconds(This is how long time you can create new refresh tokens by providing your original refresh token)
     DateTime now = DateTime.UtcNow.AddSeconds(-30);


    //If the time has passed more than 30 seconds from the time you got your original access and refresh token by providing credentials
    //you may not create and return new refresh tokens(Obviously the 30  seconds could be changed to something less or more aswell)
    if(now < ceationDate)
    {
    // Expiration time in seconds
    int expire = 2 * 60;
    context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddSeconds(expire));
    context.SetToken(context.SerializeTicket());
    }
}

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