asp.net核心中无效的jwt令牌

时间:2020-07-30 04:49:45

标签: c# jwt asp.net-core-webapi

我正在尝试在Angular应用程序和ASP.net核心中使用JWT。首先,我使用“邮递员”来测试我的终点。 在我的API中,这就是我设置JWT的方式

launchsettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:22468",
      "sslPort": 0
    }
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "ancmHostingModel": "InProcess"
    },
    "autosweeprfid_api": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:5000"
    }
  }
}

appsettings.json

"Jwt": {
    "SecretKey": "KqcL7s998JrfFHRP1",
    "Issuer": "http://localhost:22468",
    "Audience": "http://localhost:4201"
  }

startup.cs => ConfigureServices

 // Get the Validators in appsettings
            var validIssuer = Configuration["Jwt:Issuer"];
            var validAudience = Configuration["Jwt:Audience"];

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
               .AddJwtBearer(options =>
               {
                   options.TokenValidationParameters = new TokenValidationParameters
                   {
                       ValidateIssuer = true,
                       ValidateAudience = false,
                       ValidateLifetime = true,
                       ValidateIssuerSigningKey = true,

                       ValidIssuer = validIssuer,
                       ValidAudience = validAudience,
                       IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"]))

                   };
               });

启动=>配置

 app.UseCors("MyPolicy");

            // Make the "PrivateImages" forlder servable
            app.UseStaticFiles();
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"PrivateImages")),
                RequestPath = new PathString("/PrivateImages")
            });

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<MessageHub>("/MessageHub");
            });

AuthorizationController

[HttpPost, Route("login")]
        public IActionResult Login([FromBody] LoginModelDto model)
        {
            IActionResult response = Unauthorized();

            User user = context.Users.SingleOrDefault(x => x.UserName == model.UserName);

            if (user == null) return response;
            if (!user.IsActive) return response;

            var decryptedPassword = Decryption.Decrypt(user.Password, user.SaltValue);
            if (decryptedPassword == model.Password)
            {
                var roles = (from a in context.UserRoles
                             join b in context.Roles on a.RoleId equals b.Id into ab
                             from x in ab.DefaultIfEmpty()
                             where a.UserId == user.Id
                             select new Role
                             {
                                 RoleName = x.RoleName,
                             }).ToList();

                var claims = new List<Claim>
                {
                    new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Sub, user.UserName),
                    new Claim("UserId", user.Id.ToString()),
                    new Claim("FirstName", user.FirstName.ToString()),
                    new Claim("MiddleName", user.MiddleName.ToString()),
                    new Claim("LastName", user.LastName.ToString()),
                    new Claim("EmailAddress", user.EmailAddress.ToString()),
                    new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                };

                foreach (var role in roles)
                {
                    //claims.Add(new Claim(ClaimTypes.Role, role.RoleName));
                    claims.Add(new Claim("role", role.RoleName));
                }

                var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:SecretKey"]));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                var tokeOptions = new JwtSecurityToken(
                        issuer: "http://localhost:22468",
                        audience: "http://localhost:4201",
                        claims: claims,
                        expires: DateTime.Now.AddMinutes(30),
                        signingCredentials: signinCredentials
                    );
                var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);

                user.Online = true;
                context.SaveChanges();

                return Ok(new { Token = tokenString });
            }
            else
            {
                return response;
            }
        }

我可以很好地登录,但是当我尝试使用属性为[Authorize]的方法时,Postman给我一个401。

enter image description here

2 个答案:

答案 0 :(得分:3)

您刚刚在管道中配置了authorization。您还需要配置authentication。请记住,必须在管道内部进行授权之前完成此操作。订购很重要,因为首先我们需要验证用户的身份,然后我们需要检查他/她拥有什么权限。

app.UseRouting();

app.UseAuthentication(); //Authentication

app.UseAuthorization(); //Authorization

答案 1 :(得分:0)

我明白了。所有代码均正确。我只是错过了使用“身份验证”本身。因此,我只是在app.UseAuthentication();app.UseRouting();之间放置了app.UseAuthorization();行,它运行良好。谢谢。

相关问题