0

I am using MVC 5 Web Api 2 with individual user account authentication. I have set the access token expiration of 30 days.

       OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(30), // Expiration 30 Days 
            AllowInsecureHttp = true
        };

But my access token gets expires early (i think it expires after 9-10 hours). So i want to call jquery ajax for refresh token " /Token ". I refered RFC6749 From this artical i created ajax :-

var data = "refresh_token="+refresh_token;
data = data + "&grant_type=refresh_token"   
$.ajax({
    type: 'post',
    url: "/Token",
    data: data,
    Content-Type: application/x-www-form-urlencoded
    success: function (data) {
     saveAccessToken(data);
    }
});

I have created GrantRefreshToken in " ApplicationOAuthProvider.cs " also

 public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
    {
        return base.GrantRefreshToken(context);
    }

When call the ajax I am getting error of invalid grant_type. No Clue why? Please help. Thanks in advance

Community
  • 1
  • 1
Rushee
  • 766
  • 7
  • 18

1 Answers1

0

Solved the issue by refering the link Refresh Token. Added the class

 public class ApplicationRefreshTokenProvider : AuthenticationTokenProvider
 {
 public override void Create(AuthenticationTokenCreateContext context)
 {
    // Expiration time in seconds
    int expire = 100*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);
}

}

and added this in Startup.Auth.cs

RefreshTokenProvider = new ApplicationRefreshTokenProvider()

Ajax Call

 $.ajax({
            beforeSend: function (xhr) {
                   xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
            },
            type: 'post',
            url: "http://MyLink/Token",
            dataType: 'application/x-www-form-urlencoded',
            data: "grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA..",
            success: function (data) {
                saveAccessToken(data);                  
            }
        });
Community
  • 1
  • 1
Rushee
  • 766
  • 7
  • 18