使用Asp.net web api 2 owin和JwtBearerAuthentication中间件时,token为null

时间:2017-11-09 10:20:01

标签: c# asp.net cookies jwt owin

我有一个支持cookie和JwtBearerAuthentication的Web api 2应用程序。我们开始遇到一些令牌未被填充的问题(并非总是如此)。在调试并附加远程调试器之后,我注意到在使用JWT身份验证时,即使我在标头中发送了令牌,也不会填充令牌。我在提供商的OnRequestToken中获取令牌。以下是我在Startup.Auth.cs中使用的代码。不确定出了什么问题。检查请求后,我看到授权存在,所以不是我没有发送授权令牌。附有手表的图像。

public void ConfigureAuthentication(IAppBuilder app)
    { 

        // Enable the application to use a cookie to store information for the signed in user
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            /* LoginPath = new PathString("/Account/Login"), */
            CookieSecure = CookieSecureOption.Always,
            CookieDomain = ConfigurationManager.AppSettings["CookieDomain"],
            ExpireTimeSpan = TimeSpan.FromDays(30),
            SlidingExpiration = false
        });

        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        var authenticationClientSettings = AuthenticationClientSetting.GetFromAppSettings(ConfigurationManager.AppSettings).ToArray();
        var token = string.Empty;
        var sb = new StringBuilder();

        var provider = new OAuthBearerAuthenticationProvider
        {
            OnRequestToken = context =>
            {
                token = context.Token;
                return Task.FromResult<object>(null);
            },

            OnValidateIdentity = context =>
            {
                sb.AppendLine("came into provider=>OnValidateIdentity function");
                var log = log4net.LogManager.GetLogger("");
                if (!string.IsNullOrEmpty(token) && context.Ticket.Identity.Claims.All(c => c.Type.ToString() != BertusClaimTypes.Account))
                {
                    var notPadded = token.Split('.')[1];
                    var padded = notPadded.PadRight(notPadded.Length + (4 - notPadded.Length % 4) % 4, '=');
                    var urlUnescaped = padded.Replace('-', '+').Replace('_', '/');
                    var claimsPart = Convert.FromBase64String(urlUnescaped);

                    var obj = JObject.Parse(Encoding.UTF8.GetString(claimsPart, 0, claimsPart.Length));


                    if (obj[BertusClaimTypes.Account] != null)
                    {
                        //this is executed only if we get access token directly from Auth0
                        sb.AppendLine($"went into first block with account numb {obj.Value<string>(BertusClaimTypes.Account).ToString()}");
                        context.Ticket.Identity.AddClaims(new[]
                        {
                            new Claim("username", obj.Value<string>(ClaimTypes.Name).ToString()),
                            new Claim(ClaimTypes.Name, obj.Value<string>(ClaimTypes.Name).ToString()),
                            new Claim(BertusClaimTypes.Account, obj.Value<string>(BertusClaimTypes.Account).ToString())
                        });

                        obj[BertusClaimTypes.Roles]?.ForEach(x => context.Ticket.Identity.AddClaim(new Claim(ClaimTypes.Role, x.Value<string>())));
                    }
                    else
                    {
                        sb.AppendLine($"went into second block with account number {obj["user_metadata"].Value<string>("AccountNumber")}");

                        context.Ticket.Identity.AddClaims(new[]
                        {
                            new Claim("username", obj.Value<string>("username").ToString()),
                            new Claim(ClaimTypes.Name, obj.Value<string>("username").ToString()),
                            new Claim(BertusClaimTypes.Account, obj["user_metadata"].Value<string>("AccountNumber"))
                        });
                    }


                    if (obj["roles"] != null)
                    {
                        var roles = obj["roles"];
                        for (int i = 0; i < roles.Count(); i++)
                        {
                            context.Ticket.Identity.AddClaim(new Claim(ClaimTypes.Role, roles[i].Value<string>()));
                        }
                    }
                }
                if (context.Ticket.Identity.Claims.All(c => c.Type != BertusClaimTypes.Account))
                {
                    log.Debug($"There was not account claim. The token we have got is {token} and steps {Environment.NewLine} {sb}");
                }
                return Task.FromResult<object>(null);
            }

        };

        app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            AllowedAudiences = authenticationClientSettings.Select(cs => cs.ClientId),
            IssuerSecurityTokenProviders = authenticationClientSettings.Select(cs => new SymmetricKeyIssuerSecurityTokenProvider(cs.Domain, cs.ClientSecret)),
            AuthenticationType = "Auth0",
            Provider = provider
        });

        // Uncomment the following lines to enable logging in with third party login providers
        //app.UseMicrosoftAccountAuthentication(
        //    clientId: "",
        //    clientSecret: "");

        //app.UseTwitterAuthentication(
        //   consumerKey: "",
        //   consumerSecret: "");

        //app.UseFacebookAuthentication(
        //   appId: "",
        //   appSecret: "");

        //app.UseGoogleAuthentication();
    }
}

screenshot

0 个答案:

没有答案