JWT和Windows身份验证的ASP.Net Core 2.0混合身份验证不接受凭据 [英] ASP.Net Core 2.0 mixed authentication of JWT and Windows Authentication doesn't accept credentials

查看:115
本文介绍了JWT和Windows身份验证的ASP.Net Core 2.0混合身份验证不接受凭据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在asp.net core 2.0中创建了API,在其中我正在使用混合模式身份验证.对于某些控制器JWT和某些使用Windows身份验证的人.

I've API created in asp.net core 2.0 where I am using mixed mode authentication. For some controllers JWT and for some using windows authentication.

我对使用JWT授权的控制器没有任何问题.但是对于要使用Windows身份验证的控制器,我会无限期地提示我使用chrome的用户名和密码对话框.

I've no problem with the controllers which authorize with JWT. But for the controllers where I want to use windows authentication I am indefinitely prompted with user name and password dialog of chrome.

这里是我要使用Windows身份验证而不是JWT的示例控制器代码.

Here my sample controller code where I want to use Windows Authentication instead of JWT.

[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = "Windows")]
public class TestController : Controller
{
    [HttpPost("processUpload")]
    public async Task<IActionResult> ProcessUploadAsync(UploadFileModel uploadFileModel)
    {

    }
}

我的配置服务代码

public void ConfigureServices(IServiceCollection services)
{
     services.AddAuthentication(options =>
     {
        options.DefaultAuthenticateScheme = IISDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
     })
     .AddJwtBearer("Bearer", options =>
     {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateAudience = false,       
            ValidateIssuer = false,  
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("blahblahKey")),
            ValidateLifetime = true, //validate the expiration and not before values in the token
            ClockSkew = TimeSpan.FromMinutes(5) //5 minute tolerance for the expiration date
        };
     });

     // let only my api users to be able to call 
     services.AddAuthorization(auth =>
     {
        auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
            .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
            .RequireClaim(ClaimTypes.Name, "MyApiUser").Build());
     });

     services.AddMvc();
}

我的配置方法.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("CorsPolicy");

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseAuthentication(); //needs to be up in the pipeline, before MVC
    app.UseMvc();
}

赞赏您的建议和帮助.

更新:到目前为止,我一直在chrome上调试我的代码.但是,当我使用IE 11时,上面的代码正在运行,没有任何问题.

Update: Till now I've been debugging my code on chrome. But when I have used IE 11, the above code is running without any issue.

这可能是Chrome的CORS问题,而印前检查问题是这样吗?

Can this be CORS issue of chrome where preflight issue?

谢谢

推荐答案

您需要确保在尝试使用Windows Auth时设置Authorization: Bearer <JWT_token> HTTP标头.这里的关键是"Windows Auth"的实际工作方式.让我们看看它如何与浏览器一起工作.

You need to ensure, that you NOT setting Authorization: Bearer <JWT_token> HTTP header when you trying to use Windows Auth. The key point here is how "Windows Auth" actually works. Let's look how it works with browser for example.

我们称其为正常流程":

Let's call this "a normal flow":

  1. 您在浏览器中导航到http://example.com/api/resource
  2. 您的浏览器暂时没有任何 Authorization HTTP标头就向http://example.com/api/resource发送HTTP GET请求(匿名请求);
  3. Web服务器(或WebAPI本身)接收到一个请求,发现没有 Authorization 标头,并使用 WWW-Authenticate: NTLM,Negotiate 响应并带有401 Not Authorized状态代码. >设置HTTP标头(走开,没有匿名访问.只欢迎'NTLM'或'Negotiate'家伙!");
  4. 浏览器收到401响应,发现请求是匿名的,查找 WWW-Authenticate 标头并立即重复请求,现在使用 Authorization: NTLM <NTLM_token> HTTP标头(好,请放心,Web服务器先生!这是我的NTLM令牌." );
  5. 服务器收到第二个请求,在 Authorization 标头中找到NTLM令牌,对其进行验证并执行请求(好,您可以通过.这是您的资源." ).
  1. You navigate to http://example.com/api/resource in your browser;
  2. Your browser send a HTTP GET request to http://example.com/api/resource without any Authorization HTTP Header for now (an anonymous request);
  3. Web server (or WebAPI themself) recieve a request, find out, that there is no Authorization header and respond with 401 Not Authorized status code with WWW-Authenticate: NTLM,Negotiate HTTP Header setted up ("Go away, no anonymous access. Only 'NTLM' or 'Negotiate' guys are welcome!");
  4. Browser receive a 401 response, find out that request was anonymous, looks to WWW-Authenticate header and instantly repeat request, now with Authorization: NTLM <NTLM_token> HTTP Header ("Ok, take it easy, mr. Web server! Here is my NTLM token.");
  5. Server receive a second request, find NTLM token in Authorization header, verify it and execute request ("Ok, you may pass. Here is your resource.").

最初将 Authorization 标头设置为某个值时,情况有所不同:

Things goes a little different, when you initialy set Authorization header to some value:

  1. 您的JS需要具有JWT授权的http://example.com/api/resource
  2. 您的浏览器现在使用 Authorization: Bearer <JWT_token> HTTP标头向http://example.com/api/resource发送HTTP GET请求;
  3. Web服务器(或WebAPI本身)接收到一个请求,发现存在带有"Bearer"身份验证方案的 Authorization 标头,并再次使用响应状态码为401 Not Authorized WWW-Authenticate: NTLM,Negotiate 设置了HTTP标头(走开,我们不知道谁是轴承"人,但我们不喜欢他们.只有"NTLM"或谈判"人是欢迎!" );
  4. 浏览器收到401响应,发现请求已得到授权,并确定此令牌是错误的.但是,当您实际设置 Authorization 标头时,这意味着您实际上拥有一些凭据.因此,它会要求您在此对话框中提供此凭据.
  1. Your JS require http://example.com/api/resource with JWT authorization;
  2. Your browser send a HTTP GET request to http://example.com/api/resource with Authorization: Bearer <JWT_token> HTTP Header now;
  3. Web server (or WebAPI themself) recieve a request, find out, that there is Authorization header with "Bearer" authentication scheme and again respond with 401 Not Authorized status code with WWW-Authenticate: NTLM,Negotiate HTTP Header setted up ("Go away, we don't know who are this 'Bearer' guys, but we don't like them. Only 'NTLM' or 'Negotiate' guys are welcome!");
  4. Browser receive a 401 response, find out that request was authorized and decide that this token is bad. But, as you actually set Authorization header, this means that you actually have some credentials. And so it ask you for this credentials with this dialog.

这篇关于JWT和Windows身份验证的ASP.Net Core 2.0混合身份验证不接受凭据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆