简体   繁体   English

具有Owin JWT身份的MVC

[英]MVC with Owin JWT Identity

I am trying to figure out how to get the claim out of my token. 我正在尝试弄清楚如何从代币中提出索赔。 I will try an keep the explanation short 我会尽量简短的解释

  • I have an HTML page that does a post to my web api, does and auth check and returns an JWT token 我有一个HTML页面,该页面向我的Web api进行发布,并进行身份验证并返回JWT令牌
  • when i get the token back i want to send it to different url, and the way i am doing it is using a querystring. 当我拿回令牌时,我想将其发送到其他网址,而我使用的方式是使用querystring。 I know i can use cookies but for this app we dont want to use them. 我知道我可以使用cookie,但是对于此应用程序,我们不想使用它们。 So if my url looks like this http://somedomain/checkout/?token=bearer token comes here 因此,如果我的网址看起来像这样http://somedomain/checkout/?token=bearer token comes here

I am using Owin middleware and this is what i have so far 我正在使用Owin middleware ,这就是到目前为止

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
                Provider = new ApplicationOAuthBearerAuthenticationProvider(),
            });

public class ApplicationOAuthBearerAuthenticationProvider
            : OAuthBearerAuthenticationProvider
        {

            public override Task RequestToken(OAuthRequestTokenContext context)
            {
                if (context == null)
                    throw new ArgumentNullException("context");

                var token = HttpContext.Current.Request.QueryString["token"];
                if (!string.IsNullOrEmpty(token))
                    context.Token = token;
                return Task.FromResult<object>(null);
            }
        }

But how do i get the Claims out of the Token or just check the IsAuthenticated 但是我如何从Token获取Claims或只是检查IsAuthenticated

I tried the Following inside my controller just to check, but the IsAuthenticated is always false 我在controller内尝试了Following只是为了检查,但IsAuthenticated始终为false

var identity = (ClaimsIdentity) HttpContext.Current.GetOwinContext().Authentication.User.Identity;
  if (!identity.IsAuthenticated)
      return;

  var id = identity.FindFirst(ClaimTypes.NameIdentifier);

OK so I managed to figure it out. 好的,所以我设法弄清楚了。 The above code that I had is all working well but I needed to add the UseJwtBearerAuthentication middle ware. 上面的代码运行良好,但是我需要添加UseJwtBearerAuthentication中间件。

One thing I did end up changing from my original code was i changed the context.Token = token; 我最终从原始代码更改的一件事是更改了context.Token = token; to context.Request.Headers.Add("Authorization", new[] { string.Format("Bearer {0}", token) }); context.Request.Headers.Add("Authorization", new[] { string.Format("Bearer {0}", token) });

So my startup class looks like this... 所以我的启动课程看起来像这样...

public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
                Provider = new ApplicationOAuthBearerAuthenticationProvider(),
            });
            app.UseJwtBearerAuthentication(JwtOptions());

            ConfigureAuth(app);
        }


        private static JwtBearerAuthenticationOptions JwtOptions()
        {
            var key = Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["auth:key"]);
            var jwt = new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudience = Some Audience,
                    ValidIssuer = Some Issuer,
                    IssuerSigningToken = new BinarySecretSecurityToken(key),
                    RequireExpirationTime = false,
                    ValidateLifetime = false
                }
            };
            return jwt;
        }

        public class ApplicationOAuthBearerAuthenticationProvider
            : OAuthBearerAuthenticationProvider
        {

            public override Task RequestToken(OAuthRequestTokenContext context)
            {
                if (context == null)
                    throw new ArgumentNullException("context");

                var token = HttpContext.Current.Request.QueryString["token"];
                if (!string.IsNullOrEmpty(token))
                    context.Request.Headers.Add("Authorization", new[] { string.Format("Bearer {0}", token) });
                return Task.FromResult<object>(null);
            }
        }
    }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM