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

查看:14
本文介绍了如何将 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天全站免登陆