Anirudha Deshmukh

Anirudha Deshmukh

  • NA
  • 40
  • 2.8k

Token based authorization for Web API in MVC 5 application

Jun 24 2019 12:54 AM
Hello Sir,
 
 We have a web application for School Management and we are using Web Api for android app communication. We are using "Microsoft.Owin.Security.OAuth" for Web Api token based authorization.
We are using OAuthAuthorizationProvider and overwrite ValidateClientAuthentication and GrantResourceOwnerCredentials functions. We are generating token successfully and send token response to android app.
We are storing token in android app database and requirement is same token is valid for next few days (at least 90 days). But issue is token is expiring on server after some minutes and android app is not authorizing and redirecting to Login page again.
How can we keep server side token for long time?

I have given my code below-
public class OAuthAuthorizationProvider:OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return base.ValidateClientAuthentication(context);
}

public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
string message = string.Empty;
try
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
string mobileNo = context.UserName;
string password = context.Password;
IUserFascade userFascade = new UserFascade();
UserModel userModel = userFascade.ValidateUserPassword(mobileNo, password);
identity.AddClaim(new Claim(ClaimTypes.Sid, userModel.UserId.ToString()));
identity.AddClaim(new Claim(ClaimTypes.Name, userModel.UserFullName));
identity.AddClaim(new Claim(ClaimTypes.Role, userModel.Role));
identity.AddClaim(new Claim(ClaimTypes.Gender, gender));
identity.AddClaim(new Claim("LastLoginTime", FormUtilities.DateFormatYYYYMMDDHHMMSS(userModel.LastLoginTime)));
context.Validated(identity);
}
catch (Exception ex)
{
}
return base.GrantResourceOwnerCredentials(context);
}
}

public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context)
{
context.Properties.AllowRefresh = true;
context.Properties.IsPersistent = true;
return base.TokenEndpointResponse(context);
}

Answers (1)