学习ASP.NET Core的身份认证(基于JwtBearer的身份认证10)
基于Cookie传递token的主要思路是通过用户身份验证后,将生成的token保存到Response.Cookies返回客户端,后续客户端访问服务接口时会自动携带Cookie到服务端以便验证身份。之前一直搞不清楚的是服务端程序如何从Cookie读取token进行认证(一般都是将token放到header中以特定键值对形式自动验证身份),不过参考文献2中给出示例,主要是处理JwtBearerEvents.OnMessageReceived事件,该事件是接收到 protocol message时触发,此时可以从Cookie中取出token并将其赋予MessageReceivedContext.Token属性,以便支撑身份验证。主要代码如下所示:
[HttpPost]
public async Task<ApiResult> LoginPlus([FromBody] UserInfo info)
{
try
{
if (_dbClient.Queryable<AppUser>().Any(r => (r.Account == info.Name) && (r.Password == info.Password)))
{
AppUser curUser = _dbClient.Queryable<AppUser>().First(r => (r.Account == info.Name) && (r.Password == info.Password));
ApiResult result = new ApiResult();
result.UserName = curUser.Name;
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Secure = true,
Expires = DateTime.UtcNow.AddDays(7)
};
Response.Cookies.Append("auth_token", GetToken(info.Name), cookieOptions);
return result;
}
else
{
return new ApiResult("身份验证失败", 500, false);
}
}
catch (Exception ex)
{
return new ApiResult(ex.Message, 500, false);
}
}
builder.Services.AddAuthentication(options =>
{
...
}).AddJwtBearer(options =>
{
...
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Cookies["auth_token"];
if (!string.IsNullOrEmpty(accessToken))
{
//Bearer Token. This will give the application an opportunity to
//retrieve a token from an alternative location.
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
先在postman中进行验证,如下面两图所示,调用LoginPlus后,会在客户端Cookie中存储值为auth_token的token数据。
调用另一需授权的服务时,不需要设置header,也不需要其它操作,postman会自动携带Cookie调用服务,也能正常调用并返回数据。如果手工删除Cookie,再调用服务时则会报401错误。
参考文献:
[1]百度AI智能问答,搜索条件:asp.net core 通过Cookie传递token
[2]https://www.cnblogs.com/CreateMyself/p/15755657.html