Asp.net客户端

系统教程 行业动态 更新时间:2024-06-14 16:53:13
Asp.net客户端 - 服务器(Asp.net Client-Server)

您好我有一个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() }); }

更多推荐

本文发布于:2023-04-06 01:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/010efb22ff6a16ea6920d761ec1c9cab.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   Asp   net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!