问题描述
所以我有一个项目,它是一个.net框架api和一个有角度的前端。
我最近添加了OWIN JWT身份验证,但似乎我做的任何事情都会返回401错误。而且我尝试了100种解决方案都没有成功。
当我登录时,JWT正确地传递到了前端。
我的startup.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);