首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JWT令牌身份验证-以正确的方式进行验证

JWT令牌身份验证-以正确的方式进行验证
EN

Stack Overflow用户
提问于 2018-06-02 06:29:59
回答 1查看 3.5K关注 0票数 3

我的项目结构的概述:

我有两个项目。

  1. Asp.net核心网页Api
  2. Asp.net核心网页MVC

Web Api项目中的

  • 我没有使用Asp.net核心身份进行登录,而是使用我自己的登录机制。
  • LoginAction方法将对数据库中的用户进行身份验证,并生成JWT令牌。
  • I能够生成JWT令牌,到目前为止一切都很顺利。

生成令牌

代码语言:javascript
复制
        [AllowAnonymous]
        [Route("requesttoken")]
        [HttpPost]
        public async Task<IActionResult> RequestToken([FromBody] TokenRequest request)
        {        
            var result = await IsValidUser(request);
            if(result)
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, request.Email)
                };

                var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_myAppSettings.SecurityKey));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var token = new JwtSecurityToken(
                    issuer: _myAppSettings.WebsiteName.ToLower(),
                    audience: _myAppSettings.WebsiteName.ToLower(),
                    claims: claims,
                    notBefore: Utilities.GetEST_DateTimeNow(),
                    expires: Utilities.GetEST_DateTimeNow().AddMinutes(5),                    
                    signingCredentials: creds);

                return Ok(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token)
                });
            }
            else
            {
                return Unauthorized();
            }
        }

启动类中的

代码语言:javascript
复制
// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<MyAppSettings>(Configuration.GetSection("MyAppSettings"));

            #region Validate JWT Token
            ConfigureJwtAuthService(services, Configuration);
            #endregion

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();

            app.UseMvc();
        }

JWT验证部分(作为部分启动类)

代码语言:javascript
复制
public void ConfigureJwtAuthService(IServiceCollection services, IConfiguration configuration)
        {
            var symmetricKeyAsBase64 = configuration["MyAppSettings:SecurityKey"];
            var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey = new SymmetricSecurityKey(keyByteArray);

            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer = Configuration["MyAppSettings:WebsiteName"].ToLower(),

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience = Configuration["MyAppSettings:WebsiteName"].ToLower(),

                // Validate the token expiry
                ValidateLifetime = true,

                ClockSkew = TimeSpan.Zero
            };

            services.AddAuthentication(
            options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o => o.TokenValidationParameters = tokenValidationParameters);
        }

LoginAction方法的样本响应。 { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkrDtGhuIETDs8OoIiwiYWRtaW4iOnRydWV9.469tBeJmYLERjlKi9u6gylb-2NsjHLC_6kZNdtoOGsA" }

Web MVC项目中的

  • 我正在使用上述Web并传递登录参数,并能够获得JWT令牌响应。
  • 我正在手动将JWT令牌响应存储在cookie中-在收到JWT令牌响应时,我正在尝试从JWT令牌中提取声明,以便能够在web上创建用户和登录用户的有效身份。

我正在尝试实现如下所示:

代码语言:javascript
复制
            {
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, model.Email)
                };
                var userIdentity = new ClaimsIdentity(claims, "login");
                ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
                return RedirectToLocal(returnUrl);
            }

问题

我把

  1. Token存储在cookie中是对的吗?我手动存储cookie的方法是否正确,或者是否有更好的方法?
  2. 如何在

项目中从JWT获取声明,以便能够使用cookie登录用户?

想要以正确的方式来做,任何帮助都会非常感谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-02 07:51:46

以下内容似乎对我很有帮助:http://blogs.quovantis.com/json-web-token-jwt-with-web-api/不确定这是不是正确的做法。

代码语言:javascript
复制
/// Using the same key used for signing token, user payload is generated back
        public JwtSecurityToken GenerateUserClaimFromJWT(string authToken)
        {

            var tokenValidationParameters = new TokenValidationParameters()
            {
                ValidAudiences = new string[]
                      {
                    "http://www.example.com",
                      },

                ValidIssuers = new string[]
                  {
                      "self",
                  },
                IssuerSigningKey = signingKey
            };
            var tokenHandler = new JwtSecurityTokenHandler();

            SecurityToken validatedToken;

            try {

              tokenHandler.ValidateToken(authToken,tokenValidationParameters, out validatedToken);
            }
            catch (Exception)
            {
                return null;

            }

            return validatedToken as JwtSecurityToken;

        }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50651734

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档