c# - 每个 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();
}
解决方案
你设置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);
推荐阅读
- r - 在新表中合并 2 列并删除重复项
- android - MDC Button MaterialShapeDrawable 奇怪的阴影并且没有波纹
- javascript - 比较 JSON 数组和 JSON 对象并找出差异
- javascript - Ramda:折叠一个对象
- ruby-on-rails - Bundler 找不到 gem "faraday" 的兼容版本:Upgrading rails from 4.2 to 5.2.3
- android - 如何通过意图在 facebook 应用程序中搜索主题标签?
- javascript - jest + enzyme + react16: src : request not sent
- ms-word - MS Word - 允许受保护文档中的接受/拒绝按钮
- wordpress - 以编程方式将所有产品类别分配给我的所有产品
- wordpress - 如何更新 ACF 中转发器字段内的克隆字段?