ASP.Net核心 - 使用WebAPI和MVC前端的JWT身份验证无法正常工作

时间:2018-06-11 15:48:47

标签: asp.net-core jwt

该项目由两部分组成:

  • ASP.Net Core API
  • ASP.Net核心MVC前端

基本上,我想做的是通过JWT进行身份验证。因此,API发布JWT,MVC前端使用Identity与JWT中声明的声明和角色。

API中的Startup.cs:

private const string SecretKey = "my_Secret_Key";
private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

            #region JWT Auth


        // jwt wire up
        // Get options from app settings
        var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

        // Configure JwtIssuerOptions
        services.Configure<JwtIssuerOptions>(options =>
        {
            options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
            options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
            options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
        });

        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

            ValidateAudience = true,
            ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

            ValidateIssuerSigningKey = true,
            IssuerSigningKey = _signingKey,


            RequireExpirationTime = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

        }).AddJwtBearer(configureOptions =>
        {
            configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
            configureOptions.TokenValidationParameters = tokenValidationParameters;
            configureOptions.SaveToken = true;
        });

        // api user claim policy
        services.AddAuthorization(options =>
        {
            options.AddPolicy(Constants.Policies.ApiAccess, policy => policy.RequireClaim(Constants.JwtClaimIdentifiers.Rol, Constants.JwtClaims.ApiAccess));
        });

        #endregion

JWT代:

        public async Task<string> GenerateEncodedToken(string userName)
    {

        User user = _userManager.GetUserByUserName(userName);
        List<string> userRoles = _userManager.GetRoles(user.Guid);

        var claimsToEncode = new[]
     {
             new Claim(JwtRegisteredClaimNames.Sub, userName),
             new Claim("web", user.WebId),
             new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
             new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
             new Claim(Constants.JwtClaimIdentifiers.Rol,Constants.JwtClaims.ApiAccess),
     };


        // Create the JWT security token and encode it.
        var jwt = new JwtSecurityToken(
            issuer: _jwtOptions.Issuer,
            audience: _jwtOptions.Audience,
            claims: claimsToEncode,
            notBefore: _jwtOptions.NotBefore,
            expires: _jwtOptions.Expiration,
            signingCredentials: _jwtOptions.SigningCredentials);


        jwt.Payload.Add("roles", userRoles.ToArray());

        var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);



        return encodedJwt;
    }

授权在API中就像魅力一样。

现在我要做以下事情: 在前端实现相同,以便: MVC Frontend接收凭据,将它们发送到API,获取令牌,并使用令牌中的声明和角色进行授权。

我尝试了几件事,但到目前为止他们都没有。 我需要在前端的Startup.cs中插入什么,以便Identity不会检查密钥(前端不允许拥有),而是针对公钥?或者我是否必须在API中实现一个远程验证JWT的端点?

1 个答案:

答案 0 :(得分:0)

在Web客户端中获取令牌时,可以将其存储在会话对象中,并在您向Webapi请求某些内容时将其发送给