[英]Invalid JWT Token Auth in .NET/Angular App
I have a problem while authenticating an user.我在验证用户时遇到问题。 Login works perfectly and I receive a token from API.
登录工作完美,我从 API 收到一个令牌。 I save it in JwtTokenService in my Angular App and while performing a request (ex. Delete) I add "Authorization" header with value "Bearer token" as I did before in PostMan.
我将它保存在我的 Angular 应用程序中的 JwtTokenService 中,并且在执行请求(例如删除)时,我像之前在 PostMan 中所做的那样添加了值为“Bearer token”的“Authorization”标头。 Request from client:
来自客户的请求:
I get 302 status code and redirection to Account/Login even though I dont have such rout我得到 302 状态代码并重定向到帐户/登录,即使我没有这样的溃败
Error in console:控制台中的错误:
Access to XMLHttpRequest at 'https://localhost:44332/api/car/2' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
从源“http://localhost:4200”访问“https://localhost:44332/api/car/2”的 XMLHttpRequest 已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头在请求的资源上。
But GETs (which have [AllowAnonymous] attribute are working fine)但是 GET(具有 [AllowAnonymous] 属性的工作正常)
Request in postman works well.邮递员中的请求效果很好。 I think it's something messed up with my cookies.
我想这是我的饼干出了问题。 .Net Conf:
.Net 配置:
[Route("api/[controller]")]
[ApiController]
[Authorize]
[ExceptionHandlingFilter]
public class CarController : ControllerBase
{
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
}
and Startup和启动
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = 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"]))
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
(path.StartsWithSegments("/chat")))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
app.UseCors("CorsPolicy");
EDIT1:编辑1:
[HttpDelete("{id}")]
[Authorize(Policy = JwtBearerDefaults.AuthenticationScheme)]
public async Task<IActionResult> Delete(int id)
{
Error: System.InvalidOperationException: The AuthorizationPolicy named: 'Bearer' was not found.错误:System.InvalidOperationException:未找到名为“Bearer”的 AuthorizationPolicy。
Console error: Access to XMLHttpRequest at 'https://localhost:44332/api/car/2' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.控制台错误:从源 'http://localhost:4200' 访问 XMLHttpRequest at 'https://localhost:44332/api/car/2' 已被 CORS 策略阻止:没有 'Access-Control-Allow-Origin'请求的资源上存在标头。 zone-evergreen.js:2845 DELETE https://localhost:44332/api/car/2 net::ERR_FAILED
zone-evergreen.js:2845 删除 https://localhost:44332/api/car/2 net::ERR_FAILED
Here is an example of how I achieve this.这是我如何实现这一目标的示例。
Server
服务器
Add this to your start up file.将此添加到您的启动文件中。
services.AddCors(options =>
{
options.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin();
builder.AllowAnyHeader();
builder.AllowAnyMethod();
});
});
app.UseRouting();
app.UseCors();
app.UseAuthorization();
...
Add this to your controller file.将此添加到您的控制器文件中。
[ApiController]
[Route("[controller]")]
// <Mainly just need to add the below attribute>
[Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
// </Mainly just need to add the below attribute>
public class WeatherForecastController : ControllerBase
{
[HttpPost]
[Route("PostRequest")]
public IActionResult PostRequest(string parameter)
{
return Ok(new { result = parameter });
}
}
Client客户
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with
ASP.NET Core</a>.</p>
</div>
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
<script>
$(document).ready(() =>{
$.ajax({
type: 'POST',
url : 'https://localhost:44304/weatherforecast/PostRequest?parameter=someValue',
contentType: 'application/json',
success: function (data){
console.log(data);
},
error: function (data){
console.log(data);
},
});
});
</script>
If I remove [Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
from the controller, it will fail.如果我从控制器中删除
[Microsoft.AspNetCore.Cors.EnableCors("MyPolicy")]
,它将失败。
All the information you need can be found here and shouldn't be too difficult to add your project.您需要的所有信息都可以在这里找到,添加项目应该不会太难。
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#enable-cors-with-attributes https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#enable-cors-with-attributes
You have to use in ConfugureServices of Startup :您必须在 Startup 的 ConfugureServices 中使用:
services.AddCors(options =>
{
options.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin();
builder.AllowAnyHeader();
builder.AllowAnyMethod();
});
});
And add policy name to configure in startup file:并在启动文件中添加要配置的策略名称:
app.UseCors("MyPolicy");
App.UseCors() without policy name can be used only if you use .AddDefaultPolicy(...)仅当您使用 .AddDefaultPolicy(...) 时,才能使用没有策略名称的 App.UseCors()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.