[英]How to authorize requests with x-auth-token in its header using asp.net core api?
I generated token included user info and her roles using asp.net core web api and get it at client, then put it in x-auth-token in request header. 我使用asp.net核心网络api生成了包含用户信息及其角色的令牌,并将其从客户端获取,然后将其放在请求标头中的x-auth-token中。 How cal I authorize user (with her roles) in asp.net api controllers and actions?
我如何在asp.net api控制器和操作中授权用户(及其角色)? My setting in startup.cs is like below but I can not catch request in my action!
我在startup.cs中的设置如下所示,但我无法在操作中捕获请求!
var securityKey = Environment.GetEnvironmentVariable("SECURITY_KEY");
var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "shoniz.com",
ValidAudience = "readers",
IssuerSigningKey = symmetricSecurityKey
};
});
The code in your example is an settings of authentication (JWT scheme). 您的示例中的代码是身份验证设置(JWT方案)。 First, you have to add middleware, which will authenticate user.
首先,您必须添加中间件,该中间件将对用户进行身份验证。 This part of code should be present in
Startup.cs
( Configure()
method). 这部分代码应该出现在
Startup.cs
( Configure()
方法)。
app.UseAuthentication();
Once this middleware is called, all the authentication schemes are taken into account. 调用此中间件后,将考虑所有身份验证方案。 When the authentication will success,
HttpContext.User
will be set (including all your issues claims). 身份验证成功后,将设置
HttpContext.User
(包括您所有的问题声明)。
The second part is authorization. 第二部分是授权。 The simplest way is to use
[Authorize]
attribute you can use as an annotation along with your action methods and controllers. 最简单的方法是使用
[Authorize]
属性,该属性可以与操作方法和控制器一起用作批注。 You can add custom role names or policy restriction. 您可以添加自定义角色名称或策略限制。
[Authorize(Roles = "admin")]
public class CmsControllerBase : Controller
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.