如何将Windows身份验证和JWT与.Net Core 2.1结合使用 [英] How to combine the windows authentication and JWT with .Net Core 2.1

查看:100
本文介绍了如何将Windows身份验证和JWT与.Net Core 2.1结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将Windows身份验证和JWT与.NET Core 2.1一起使用.

I have tried to use the windows authentication and JWT together with .NET Core 2.1.

我具有以下身份验证的启动设置:

I have following startup settings of the authentication:

services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = IISDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,

                    ValidIssuer = "Test",
                    ValidAudience = "Test",
                    IssuerSigningKey = JwtSecurityKey.Create("677efa87-aa4d-42d6-adc8-9f866e5f75f7")
                };

                options.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = OnAuthenticationFailed
                };
            });

IIS设置:

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

我尝试使用以下代码段通过Windows身份验证创建JWT令牌:

I have tried following code snippet to create the JWT token with windows authentication:

[Route("api/[controller]")]
    [ApiController]
    [Authorize(AuthenticationSchemes = "Windows")]
    public class AuthController : ControllerBase
    {
        [HttpPost("token")]
        public IActionResult Token()
        {
            //Setup claims
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, User.Identity.Name),
                //Add additional claims
            };

            //Read signing symmetric key
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("677efa87-aa4d-42d6-adc8-9f866e5f75f7"));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //Create a token
            var token = new JwtSecurityToken(
                issuer: "Test",
                audience: "Test",
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);

            //Return signed JWT token
            return Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token)
            });
        }
    }

在另一个控制器中,我只需要使用JWT身份验证:

And in another controller I need use only JWT authentication:

[Route("api/[controller]")]
    [ApiController]
    [Authorize(AuthenticationSchemes = "Bearer")]
    public class ProductController : ControllerBase
    {
        [HttpGet]
        public IActionResult Get()
        {
            var userName = User.Identity.Name;

            var claims = User.Claims.Select(x => new { x.Type, x.Value });

            return Ok(new { userName, claims });
        }
    }

如果JWT令牌已过期,那么我正确地收到了响应代码401,但是我仍然在浏览器中看到用于放置凭据的对话框.

If the JWT token is expired then I correctly received the response code 401 but I still get the dialog in the browser for putting the credentials.

当我要创建JWT令牌并禁用负责显示带有凭据的浏览器对话框的响应时,如何仅对一部分配置Windows身份验证?如何正确组合这些东西?

How can I configure the windows authentication only for a part when I want to create the JWT token and disable response which is responsible for showing the browser dialog with credentials? How to correctly combine these things?

推荐答案

我处理此问题的方式是创建两个不同的Web应用程序:一个用于Windows身份验证,一个用于JWT令牌身份验证.

The way I would handle this is to create two different web applications: one for Windows Authentication and one that uses JWT Token Authentication.

Windows身份验证Web应用程序将很小,只能做一件事.通过终结点计算机上的Windows身份验证对用户进行身份验证,然后返回JWT令牌.

The Windows Authentication web application would be very small and only does one thing. Authenticate the user via Windows Authentication at an endpoint and return a JWT Token.

然后,该令牌可用于主应用程序.只要您的签名密钥和访问者相同,就可以在其他Web应用程序上创建令牌.

Then, that token can be used for the main application. As long as your signing key and audience is the same, it doesn't matter if the token is created on a different web application.

您无需费力尝试同时处理两者.

You won't need to struggle with trying to handle both at the same time.

这篇关于如何将Windows身份验证和JWT与.Net Core 2.1结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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