如何验证请求标头,JWT令牌

时间:2019-04-27 15:39:56

标签: asp.net angular asp.net-web-api asp.net-core jwt

对,我有一个面向角7的项目和asp.net核心Web API。从Web API创建JWT Web令牌后,我返回到fronted,它将保存在本地存储中。我想将请求发送到Web API之后,我将把JWT Web令牌放入请求标头部分。那会很好的。所以我想使用JWT有效负载数据对请求进行身份验证。我的JWT有效负载数据具有记录用户名,用户角色的一些信息。我想通过http get请求获取产品详细信息时检查它的有效令牌。您能帮我在asp.net核心网络api中进行身份验证吗?

asp.net核心Web API Angular 7 CLI

Startup.cs-WEB API

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
 {
  options.TokenValidationParameters = new TokenValidationParameters
  {
  ValidateIssuer = true,
  ValidateAudience = true,
  ValidateLifetime = true,
  ValidateIssuerSigningKey = true,
  ValidIssuer = Configuration["Jwt:Issuer"],
  ValidAudience = Configuration["Jwt:Issuer"],
  IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
 };
});

services.AddMvc();

构建Web令牌-WEB API

private string BuildToken(MYWebApi.Models.CustomerModel user)
{
  var claims = new[] {
  new Claim(JwtRegisteredClaimNames.NameId,user.CusId.ToString()),
  new Claim(JwtRegisteredClaimNames.Sub,user.CusName),
  new Claim(JwtRegisteredClaimNames.Email,user.CusEmail),
  new Claim("role","user"),
};

 var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
 var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

 var token = new JwtSecurityToken(_config["Jwt:Issuer"],
  _config["Jwt:Issuer"],
 claims,
 expires: DateTime.Now.AddMinutes(30),
 signingCredentials: creds);

 return new JwtSecurityTokenHandler().WriteToken(token);
}

将令牌放入标头部分-前部结束

 @Injectable( )
    export class TokenInterceptorService implements HttpInterceptor{

      constructor(private injector:Injector) { }

      intercept(req, next){
        let serverService = this.injector.get(ServerService)
        let tokenizedReq = req.clone({
            setHeaders:{
              Autherization:`Bearer ${serverService.getToken()}`
            }
         })
        return next.handle(tokenizedReq)
      }
    }

控制器-WEB API

[Route("GetProduct")]
        [HttpGet]
        public List<ProductModel> GetProduct(int productId)
        {
            var repo = new MEData.Repository.ProductRepo();

            var productData = repo.GetProduct(productId);

            return productData;
        }

2 个答案:

答案 0 :(得分:0)

确保在“启动类”的“配置”方法的app.UseAuthentication();之前添加了app.UseMvc();代码

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            app.UseAuthentication();

            app.UseMvc();
        }

然后根据您的要求在操作或控制器级别添加[Authorize]属性

答案 1 :(得分:0)

除了进行app.UseAuthentication()调用之外,请尝试以下其他选项:

1。。将[Authorize]属性与AuthenticationSchemes

一起应用
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Route("GetProduct")]
[HttpGet]
public List<ProductModel> GetProduct(int productId)
{
   //...
}

此外,请尝试在ConfigureServices

中添加以下行
services.AddAuthorization();

2。。尝试将services.AddAuthorization与策略和选定的方案一起使用

services.AddAuthorization(options =>
{
    options.AddPolicy("Jwt", policy =>
    {
        policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
        policy.RequireAuthenticatedUser();
    });
});

然后使用[Authorize]属性使用策略

[Authorize(Policy = "Jwt")]
[Route("GetProduct")]
[HttpGet]
public List<ProductModel> GetProduct(int productId)
{
   //...
}

一般来说,我认为services.AddAuthorization行是必需的。查看哪个选项适合您。