Net Core教程

asp.net core 自动刷新token还有跨域的问题

本文主要是介绍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还有跨域的问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!