Jwt令牌签名始终无效

时间:2018-07-25 14:08:06

标签: c# asp.net-core jwt

我将在我的应用程序中实现jwt令牌认证,这里我有2个api,其中1是我的令牌服务器,用于创建令牌并与其他人共享。 启动文件

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
               options.UseSqlServer(Configuration.GetConnectionString("TestConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = _config["Jwt:Issuer"],
                    ValidAudience = _config["Client"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetValue<string>("Jwt:Key")))
                };
            });

services.AddIdentityServer()
               // .AddDeveloperSigningCredential()
               // .AddInMemoryPersistedGrants()
               .AddJwtBearerClientAuthentication()
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients(Config.GetUrls(Configuration)))
                .AddAspNetIdentity<ApplicationUser>();

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();
            app.UseCors("CorsPolicy");
            app.UseIdentityServer();
            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

令牌生成(登录)

public IActionResult CreateToken([FromForm]LoginModel login)
        {
            IActionResult response = Unauthorized();
            //var user = Authenticate(login);
            var userIdentity = _userManager.FindByNameAsync(login.username).Result;
            var loginResult = _signInManager.CheckPasswordSignInAsync(userIdentity, login.password, false).Result;
            if (userIdentity != null && loginResult.Succeeded)
            {
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            ClaimsIdentity identity = new ClaimsIdentity(
                            new GenericIdentity(user.UserName, "Login"),
                            new[] {
                                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                                new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
                            }
                        );

            var token = new JwtSecurityToken(issuer: _config["Jwt:Issuer"],
              audience: _config["Client"],
              claims: identity.Claims,
              expires: DateTime.Now.AddMinutes(30),
              signingCredentials: creds);

            var tokenString = new JwtSecurityTokenHandler().WriteToken(token);

                return Ok(new ResponseModel
                {
                    access_token = tokenString,
                    expires_in = "3600",
                    token_type = "Bearer"
                });
            }
            return null;
        }

我的creatkey = 123456789 @ test 我做错什么了吗? 我收到像无效令牌这样的消息。签名无效。

请给我提示或指导。 谢谢

1 个答案:

答案 0 :(得分:0)

您的密钥应超过16个字符