.NET核心Windows身份验证-React与Postman



我有一个问题,让我发疯。。。我得到了后端API,它启用了CORS和Windows身份验证,看起来像这个

launchSettings.json:

"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
....
}

启动.cs

public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

TokenController.cs

[ApiController]
[Route("[controller]")]
public class TokenController : ControllerBase
{
private TokenService userService;
IHttpContextAccessor httpContextAccessor;
public TokenController(TokenService _userService, 
IHttpContextAccessor _httpContextAccessor)
{
userService = _userService;
httpContextAccessor = _httpContextAccessor;
}
/// <summary>
/// Creates token for domain signed user of Unicredit group
/// </summary>
/// <returns>Authenticate</returns>
[HttpGet]
[Route("")]
[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[Produces("application/json")]
public IActionResult Authenticate()
{
string username = httpContextAccessor.HttpContext.User.Identity.Name;
... further reading from AD and making JWT token 
}

React-Authenticate.js(做简单的提取(

fetch(`${AuthenticationEndpoint}/`)
.then(response => response.json())
.then(data => this.onSetResult(data));

因此,当我使用Boomerang(类似Postman(调用我的API并仅为https://localhost:{port}/Token/执行简单的GET时,我会得到status 200和JWT令牌,但一旦我从React应用程序中提取,我就会不断得到错误:

Access to fetch at 'https://localhost:44351/Token/' from origin 'http://localhost:3000' has been blocked by CORS policy

我知道Boomerang和Postman不受政策限制,这就是为什么它们可以传递到我的API,但我如何让我的应用程序访问我的API?

固定信息

因为我有

"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,

我的cors期望用户名,我确实需要它来查询AD并制作JWT令牌

我不得不更改fetch,将credentials设置为include,并在Startup.cs 中更改useCors

fetch(`${AuthenticationEndpoint}/Authenticate`, {
credentials: "include",
method: "GET",
'Accept': 'application/json',
'Content-Type': 'application/json',
}).then((response) => {
response.json().then(data => {
this.onSetResult(data);
})
});

后端的CORS设置如下:

app.UseCors(builder => builder.WithOrigins("http://localhost:3000")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());

相关内容

  • 没有找到相关文章

最新更新