简体   繁体   中英

Jwt Token signature always invalid

I am going to implement jwt Token authentication in my application, here i have 2 apis, in which 1 is my token server which create token and share it with other. Startup file

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

Token Generation (Login)

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

my creatkey = 123456789@test is i am doing anything wrong. i am getting message like invalid token. signature invalid.

Please give me hint or guideline. Thank you,

您的密钥应超过 16 个字符

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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