Reputation: 2696
Hello i have a web api with individual user accounts that creates tokens and send them back to the client. I created an mvc client in a separate project that gets this token from the web api using the following function.
private async Task<Dictionary<string,string>> GetTokenAsync()
{
var client = new HttpClient();
var post = new Dictionary<string, string>
{
{"grant_type","password" },
{"username","[email protected]" },
{"password","Panagorn18!" }
};
var response = await client.PostAsync("http://localhost:55561/token", new FormUrlEncodedContent(post));
//response.StatusCode == HttpStatusCode.Unauthorized
var content = await response.Content.ReadAsStringAsync();
var json = JObject.Parse(content);
var tkn = json["access_token"].ToString();
var ex = json["expires_in"];
var exp = new DateTime();
exp.AddSeconds((long)ex);
var ms = exp.ToUniversalTime().Subtract(
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
var dic = new Dictionary<string, string>
{
{ "token", tkn },
{ "expires", ms.ToString() }
};
return dic;
}
Now my questions are:
1. Where i have to save this token?
2. How can i keep the user loged in for example 30 days?
3. How can i check if the token expired and logout the user in the mvc project?
4. What configuration i have to put at startup class at mvc project to use this tokens?
Upvotes: 1
Views: 133
Reputation: 4895
1. Where i have to save this token?
Server side: Session, Memory Cache, etc
Client side: cookie, localStorage, sessionStorage, etc
Others: maybe another cache server (Redis)
Database is also a good place to save
2. How can i keep the user logged in for example 30 days?
It's what token expiry date used for (check AccessTokenExpireTimeSpan
)
3. How can i check if the token expired and logout the user?
A good way is implement your own AuthenticationTokenProvider
, deserialize the token passed to server, check the expiry date and add the AccessTokenExpired to response header
Sample code:
// CustomAccessTokenProvider.cs
public class CustomAccessTokenProvider : AuthenticationTokenProvider
{
public override void Receive(AuthenticationTokenReceiveContext context)
{
context.DeserializeTicket(context.Token);
var expired = context.Ticket.Properties.ExpiresUtc < DateTime.UtcNow;
if(expired)
{
context.Response.Headers.Add("X-AccessTokenExpired", new string[] { "1" });
}
base.Receive(context);
}
}
// Startup.cs
public void Configuration(IAppBuilder app)
{
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
AccessTokenProvider = new CustomAccessTokenProvider()
});
}
Upvotes: 4