您好我有一个web api,其中包含创建令牌的个人用户帐户并将其发送回客户端。 我在一个单独的项目中创建了一个mvc客户端,该项目使用以下函数从web api获取此令牌。
private async Task<Dictionary<string,string>> GetTokenAsync() { var client = new HttpClient(); var post = new Dictionary<string, string> { {"grant_type","password" }, {"username","admin@admin.com" }, {"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; }现在我的问题是: 1.我必须保存此令牌? 2.如何让用户保持30天? 3.如何检查令牌是否过期并在mvc项目中注销用户? 4.我必须在mvc项目的启动课中使用此令牌进行哪些配置?
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","admin@admin.com" }, {"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?
最满意答案
1. Where i have to save this token?服务器端:会话,内存缓存等
客户端:cookie,localStorage,sessionStorage等
其他:也许是另一个缓存服务器(Redis)
数据库也是一个值得保存的好地方
2. How can i keep the user logged in for example 30 days?AccessTokenExpireTimeSpan 牌到期日期用于(检查AccessTokenExpireTimeSpan )
3. How can i check if the token expired and logout the user?一个好方法是实现自己的AuthenticationTokenProvider , 反序列化传递给服务器的令牌 , 检查到期日期并将AccessTokenExpired添加到响应头
示例代码:
// 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() }); } 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() }); }更多推荐
发布评论