资源服务器中的OwinMiddleware实现抑制令牌验证 [英] OwinMiddleware implementation in Resource Server suppresses Token validation

查看:116
本文介绍了资源服务器中的OwinMiddleware实现抑制令牌验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了资源服务器(Web Api 2)以验证传入请求的JWT令牌. JWT令牌由Aut​​h0颁发,我的客户端将其传递给我的Web api.如果发行者",受众"或到期日"无效,则所有这些都可以正常工作并引发401响应.当我添加从OwinMiddleware派生的自定义中间件时,它会抑制令牌验证逻辑,并且对于无效请求会收到200条响应.

I have set up my Resource Server (Web Api 2) to validate JWT token for incoming requests. The JWT token is issued by Auth0 and my client pass it to my web api. This all works fine and raises 401 response if Issuer, Audience or Expiry date is not valid. When I add my custom middleware derived from OwinMiddleware it suppresses token validation logic and I get 200 response for invalid requests.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
         var issuer = "my issuer";
         var audience= "my audience";
         var clientId= "my client id";
         app.UseActiveDirectoryFederationServicesBearerAuthentication(
            new ActiveDirectoryFederationServicesBearerAuthenticationOptions
            {
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudience = audience,
                    ValidIssuer = issuer,
                    IssuerSigningKeyResolver = (token, securityToken, identifier, parameters) => parameters.IssuerSigningTokens.FirstOrDefault()?.SecurityKeys?.FirstOrDefault()
                },
                // Setting the MetadataEndpoint so the middleware can download the RS256 certificate
                MetadataEndpoint = $"{issuer.TrimEnd('/')}/wsfed/{clientId}/FederationMetadata/2007-06/FederationMetadata.xml"
            });



        HttpConfiguration config = new HttpConfiguration();

        app.Use<HttpUsernameInjector>();

        // Web API routes
        config.MapHttpAttributeRoutes();
        app.UseWebApi(config);
    }
}

和我自定义的OwinMiddleWare:

and my custom OwinMiddleWare:

public class HttpUsernameInjector : OwinMiddleware
{
    public HttpUsernameInjector(OwinMiddleware next)
        : base(next)
    {
    }

    public override async Task Invoke(IOwinContext context)
    {
        const string usernameClaimKey = "my username claim key";

        var bearerString = context.Request.Headers["Authorization"];
        if (bearerString != null && bearerString.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
        {
            var tokenString = bearerString.Substring(7);

            var token = new JwtSecurityToken(tokenString);
            var claims = token.Claims.ToList();
            var username = claims.FirstOrDefault(x => x.Type == usernameClaimKey);

            if (username == null) throw new Exception("Token should have username");

            // Add to HttpContext
            var genericPrincipal = new GenericPrincipal(new GenericIdentity(username.Value), new string[] { });

            IPrincipal principal = genericPrincipal;

            context.Request.User = principal;
        }

        await Next.Invoke(context);
    }
}

我应该如何配置自定义中间件以避免冲突/抑制OWIN令牌认证逻辑?

How should I configure my custom middleware to avoid conflict/suppressing OWIN token authentication logic?

推荐答案

OWINMiddleware没什么问题,但是分配context.Request.User会引起问题.在此处创建的GenericIdentity具有等于true的只读IsAuthenticated,并且无法设置为false.分配context.Request.User = genericPrincipal;时,它会用genericPrincipal中的IsAuthenticated覆盖context.Request.User中的IsAuthenticated.需要在Invoke方法开始时检查身份验证结果,如果用户未通过身份验证,则跳过逻辑.因此它不会更改context.Request.User中的IsAuthenticated.

Nothing's wrong with OWINMiddleware but assigning context.Request.User causes problem. GenericIdentity created here has a Readonly IsAuthenticated equal to true and not possible to set to false. When assigning context.Request.User = genericPrincipal; it overrides IsAuthenticated inside context.Request.User with IsAuthenticated from genericPrincipal. Need to check for Authentication result at the beginning of Invoke method and skip the logic if user is not authenticated. So it wouldn't change IsAuthenticated in context.Request.User.

public override async Task Invoke(IOwinContext context)
    {
        if (context.Authentication.User.Identity.IsAuthenticated)
        {
            //my username injection logic
        }
        await Next.Invoke(context);
    }

这篇关于资源服务器中的OwinMiddleware实现抑制令牌验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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