具有Owin JWT身份的MVC [英] MVC with Owin JWT Identity

查看:162
本文介绍了具有Owin JWT身份的MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清楚如何从令牌中提出索赔. 我会尽量使解释简短

I am trying to figure out how to get the claim out of my token. I will try an keep the explanation short

  • 我有一个HTML页面,该页面在我的Web api上发布内容,并进行身份验证 检查并返回JWT令牌
  • 当我取回令牌时,我想将其发送到不同的url,而我执行该操作的方式是使用querystring.我知道我可以使用cookie,但是对于此应用程序,我们不想使用它们.因此,如果我的网址看起来像这样http://somedomain/checkout/?token=bearer token comes here
  • I have an HTML page that does a post to my web api, does and auth check and returns an JWT token
  • 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. I know i can use cookies but for this app we dont want to use them. So if my url looks like this http://somedomain/checkout/?token=bearer token comes here

我正在使用Owin middleware,这是我到目前为止所拥有的

I am using Owin middleware and this is what i have so far

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);
            }
        }

但是我如何从Token中取出Claims或只是检查IsAuthenticated

But how do i get the Claims out of the Token or just check the IsAuthenticated

我尝试在我的controller内尝试执行跟踪",但IsAuthenticated始终为false

I tried the Following inside my controller just to check, but the IsAuthenticated is always false

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

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

推荐答案

好,所以我设法弄清楚了.上面的代码运行良好,但是我需要添加UseJwtBearerAuthentication中间件.

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.

我最终从原始代码更改的一件事是我将context.Token = token;更改为context.Request.Headers.Add("Authorization", new[] { string.Format("Bearer {0}", token) });

One thing I did end up changing from my original code was i changed the context.Token = token; to 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);
            }
        }
    }

这篇关于具有Owin JWT身份的MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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