简体   繁体   English

Header 中自定义字段的 Bearer Token

[英]Bearer Token by custom field in Header

My endpoint uses a token to authorize the execution but the header "Authorization" field is used for the gateway token.我的端点使用令牌来授权执行,但 header“授权”字段用于网关令牌。 I'd like to set a different header key to pass and read the token in my endpoints and avoid conflicts.我想设置一个不同的 header 密钥来传递和读取我端点中的令牌并避免冲突。

This is my controller code:这是我的 controller 代码:

        [HttpPost]
        [ApiVersion("1.0")]
        [ProducesResponseType(typeof(ErrorMessageDto), 500)]
        [Authorize(AuthenticationSchemes = "Bearer")]
        [ProducesResponseType(typeof(NavMenuItemReturnDto), 201)]
        public IActionResult CreateNavMenuItem(NavMenuItemUpdateCreateDto newNavMenuItem)
        {
            try
            {
                return StatusCode(201, _navMenuItemsBL.CreateNewNavMenuItem(newNavMenuItem).Result);
            }
            catch (Exception ex)
            {
                return StatusCode(500, new ErrorMessageDto { Error = ex.Message });
            }
        }

This is my startup code:这是我的启动代码:

 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = Configuration.GetSection("JwtAuthority").Get<string>();

                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = false,
                        ValidateAudience = false,
                        RequireExpirationTime = false,
                        ValidateLifetime = false,
                        ValidateIssuer = false,
                    };
                });

Any suggestions?有什么建议么? Thanks for the help谢谢您的帮助

Could you achieve what you are after with adding Multiple Authentication Schemas?您能否通过添加多个身份验证模式来实现您的目标?

An Example is below:一个例子如下:

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Audience = "https://localhost:5000/";
            options.Authority = "https://localhost:5000/identity/";
        })
        .AddJwtBearer("AzureAD", options =>
        {
            options.Audience = "https://localhost:5000/";
            options.Authority = "https://login.microsoftonline.com/eb971100-6f99-4bdc-8611-1bc8edd7f436/";
        });
}

Only one JWT bearer authentication is registered with the default authentication scheme JwtBearerDefaults.AuthenticationScheme.默认认证方案JwtBearerDefaults.AuthenticationScheme只注册了一个JWT承载认证。 Additional authentication has to be registered with a unique authentication scheme.必须使用唯一的身份验证方案注册其他身份验证。

The next step is to update the default authorization policy to accept both authentication schemes.下一步是更新默认授权策略以接受两种身份验证方案。 For example:例如:

        services.AddAuthorization(options =>
        {
            var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(
                JwtBearerDefaults.AuthenticationScheme,
                "AzureAD");
            defaultAuthorizationPolicyBuilder = 
                defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
            options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();
        });

As the default authorization policy is overridden, it's possible to use the [Authorize] attribute in controllers.由于默认授权策略被覆盖,因此可以在控制器中使用 [Authorize] 属性。 The controller then accepts requests with JWT issued by the first or second issuer.然后 controller 接受第一或第二发行人发出的带有 JWT 的请求。

Now you have the default, and AzureAD现在您有了默认值和 AzureAD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Azure Function 的模拟测试中为 HttpRequest 添加自定义 header 和不记名令牌 - How to add custom header and bearer token for HttpRequest in Mock Test for Azure Function 带有授权标头和不记名令牌的 Blazor 导航 - Blazor navigation with authorization header and bearer token 不记名令牌的 NSwag CSharpClientGenerator 自定义请求标头 - NSwag CSharpClientGenerator custom request headers for bearer token Web API 2 OWIN Bearer令牌自定义身份验证 - Web API 2 OWIN Bearer token custom authentication 从 swagger UI 传递 header 中的 Jwt 令牌作为不记名令牌不起作用 - Passing Jwt token in header from swagger UI as bearer token not working C#:如何在 header 中使用不记名令牌获取请求 - C#: How to htttps get request with bearer token in header .NET Core API-中间件是否在标头中设置了JWT承载令牌? - .NET Core API - does the middleware set the JWT bearer token in the header? 如何在HTTP请求的标头中添加承载令牌? - How do I add a Bearer Token to the header of a HTTP request? C# 将不记名令牌传递给生成的代理 class 以添加 header - C# Passing bearer token to generated proxy class to add header 从没有承载前缀的授权 header 中获取访问令牌 - Fetch access token from authorization header without bearer prefix
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM