asp.net core 自动刷新token还有跨域的问题
2022/4/24 17:12:35
本文主要是介绍asp.net core 自动刷新token还有跨域的问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
在服务端刷新token,放到响应header里面,前端死活得不到值。最后发现因为用的是自定义newtoken,前端在跨域中读不到。
加入扩展头跨域,解决问题。
两个问题
1>服务器自动刷新token
public class FlushTokenMiddleware
{
private readonly RequestDelegate _next;
private readonly JWTHelperService jWTHelperService;
public FlushTokenMiddleware(RequestDelegate next,
JWTHelperService JWTHelperService)
{
_next = next;
jWTHelperService = JWTHelperService;
}
public async Task InvokeAsync(HttpContext context)
{
JwtSecurityToken token = null;
string authorization = context.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authorization)
&& authorization.StartsWith("Bearer "))
token = new JwtSecurityTokenHandler().
ReadJwtToken(authorization.Substring("Bearer ".Length));
//刷新Token
if (token != null
&& token.ValidTo > DateTime.UtcNow
&& token.ValidTo.AddMinutes(-100) <= DateTime.UtcNow)
{
Console.WriteLine(DateTime.UtcNow.ToString("F"));
var username = context.User.Claims.FirstOrDefault(q => q.Type == SysDefineConstValue.UserName);
var rolename = context.User.Claims.FirstOrDefault(q => q.Type == SysDefineConstValue.Role);
var roleid = context.User.Claims.FirstOrDefault(q => q.Type == SysDefineConstValue.RoleId);
var userid = context.User.Claims.FirstOrDefault(q => q.Type == SysDefineConstValue.UserId);
var deptid = context.User.Claims.FirstOrDefault(q => q.Type == SysDefineConstValue.ShopId);
var jwttoken = jWTHelperService.CreateOrFreshToken(null, username?.Value??"",
rolename?.Value??"", userid?.Value??"", deptid?.Value??"",
roleid?.Value??"");
context.Response.Headers.Add("newtoken",jwttoken);
}
await _next(context);
}
扩展
public static class FlushTokenMiddlewareExtend
{
public static IApplicationBuilder UseFlushToken(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<FlushTokenMiddleware>();
}
}
注册
app.UseAuthorization();
app.UseFlushToken();
2>跨域设置
services.AddCors(options =>
options.AddPolicy(MyAllowSpecificOrigins,
p => p.AllowCredentials()
.AllowAnyMethod()
.SetIsOriginAllowed(_ => true)
.AllowAnyHeader()
.WithExposedHeaders("newtoken")
.SetPreflightMaxAge(TimeSpan.FromSeconds(60)))
);//跨域
3>vue拦截获取
if (response.headers.newtoken) { setToken(response.headers.newtoken) }这篇关于asp.net core 自动刷新token还有跨域的问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-12-06使用Microsoft.Extensions.AI在.NET中生成嵌入向量
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#