我的项目结构的概述:
我有两个项目。
Web Api项目中的
LoginAction方法将对数据库中的用户进行身份验证,并生成JWT令牌。生成令牌
        [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();
            }
        }启动类中的
// 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验证部分(作为部分启动类)
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项目中的
我正在尝试实现如下所示:
            {
                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);
            }问题
我把
项目中从JWT获取声明,以便能够使用cookie登录用户?
想要以正确的方式来做,任何帮助都会非常感谢。
发布于 2018-06-02 07:51:46
以下内容似乎对我很有帮助:http://blogs.quovantis.com/json-web-token-jwt-with-web-api/不确定这是不是正确的做法。
/// 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;
        }https://stackoverflow.com/questions/50651734
复制相似问题