首页 > 解决方案 > 每个 CRUD .net Framework API 上的 401

问题描述

所以我有一个项目,它是一个 .net 框架 api 和一个角前端。

我最近添加了 OWIN JWT 身份验证,但似乎我所做的任何事情都会返回 401 错误。我已经尝试了 100 种解决方案,但都没有成功。

当我登录时,JWT 正确地传递到前端。

我的启动.cs

using System;
using System.Text;
using Microsoft.Owin.Security.Jwt;
using Microsoft.Owin.Security;
using Microsoft.IdentityModel.Tokens;
using System.Threading.Tasks;
using System.Web.Configuration;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(AgriLogBackend.Startup))]

namespace AgriLogBackend
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                    TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateIssuerSigningKey = true,
                          
                        
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("GuessThePassword----"))
                    }
                });
        }
    }
}

我的控制器具有 [Authorize] 属性。

而且我确实将正确的 JWT 传递回控制器,但似乎它未能授权。

任何帮助是极大的赞赏

在角度我使用这样的帖子:

const ops = {     // <<<<<< Initialize header with token
        headers: new HttpHeaders({
          
          'Authorization': 'Bearer ' + localStorage.getItem("jwtToken")
        })
      };
        return this.http.get<types>(this.baseURL + "EquipmentTypes/" + localStorage.getItem("currentFarm"),ops);

在 C# 中创建令牌:

 public IHttpActionResult Login(User user)
            {
                var finduser = db.Users.Where(x => x.User_Email == user.User_Email).FirstOrDefault();

                var encPass = encrypt(user.User_Password);
                if (finduser != null && finduser.User_Password == encPass)
                {
                    var claims = new[]
                    {
                   new Claim(ClaimTypes.Name,finduser.User_ID.ToString())



                };
                    var keytoReturn = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_key));

                    var Credentials = new SigningCredentials(keytoReturn, SecurityAlgorithms.HmacSha512Signature);
                    var descriptorToken = new SecurityTokenDescriptor
                    {
                        Subject = new ClaimsIdentity(claims),
                        Expires = DateTime.Now.AddDays(1),
                        SigningCredentials = Credentials
                    };
                    var Handler = new JwtSecurityTokenHandler();

                    var userToken = Handler.CreateToken(descriptorToken);
                    return Ok
                    (new
                    {
                        Token = Handler.WriteToken(userToken)
                    }
                    );

                }

                return Unauthorized();

            }

标签: c#.netangularjwt

解决方案


你设置TokenValidationParameters这样的:

TokenValidationParameters = new TokenValidationParameters()
{
    ValidateIssuer = true,
    ValidateAudience = true,
    ValidateIssuerSigningKey = true,
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("GuessThePassword----"))
}

它告诉 JwtBearerAuthentication 中间件检查每个令牌是否有有效的颁发者和受众声明(iss以及aud令牌中)。

由于您在创建令牌期间没有添加两个声明,因此验证将失败。您的选择是关闭选项:

ValidateIssuer = false,
ValidateAudience = false,

以便在创建令牌时不执行这些检查,或为它们添加适当的声明:

var descriptorToken = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(claims),
    Expires = DateTime.Now.AddDays(1),
    SigningCredentials = Credentials
    TokenIssuerName = "YourIssuer",                // add your issuer here
    AppliesToAddress = "YourAudience",             // add your audience here
};
var Handler = new JwtSecurityTokenHandler();
var userToken = Handler.CreateToken(descriptorToken);

SecurityTokenDescriptor参考


推荐阅读