jwt令牌多租户

问题描述 投票:4回答:1

我通过令牌在我的asp网络核心项目WebAPI验证中实现,我在每次登录时创建一个令牌,一切似乎都有效。

我的问题是该应用程序将是多租户我,所以我将有许多子域客户端(Client1.myapp.com,client2.myapp.com,client3.myapp.com)

服务器端我管理蜜蜂的应用程序将接受一个参数,该参数将成为租户的名称。一些例子:

API密钥app.com/client1/API/generate token

API密钥app.com/client2/API/generate token

API密钥app.com/client3/API/generate token

现在,如果我从client1创建令牌,并且我调用了apimyapp.com/client2/api/users(在client1生成的令牌中插入标头,但是对client2进行了调用)

我验证令牌。

相反,我希望令牌仅对生成它的租户有效。

在我的startup.cs中:

 app.UseJwtBearerAuthentication(new JwtBearerOptions()
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidIssuer = _config["Tokens:Issuer"],
                ValidAudience = _config["Tokens:Audience"],
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])),
                ValidateLifetime = true
            }
        });

并在我的控制器中生成令牌:

    var userClaims =  _userManagerRepository.GetClaims(user);

    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(JwtRegisteredClaimNames.GivenName, user.UserName),
        new Claim(JwtRegisteredClaimNames.FamilyName, user.UserName),
        new Claim(JwtRegisteredClaimNames.Email, user.Email)
    }.Union(userClaims);

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

    var token = new JwtSecurityToken(
        issuer: _config["Tokens:Issuer"],
        audience: _config["Tokens:Audience"],
        claims: claims,
        expires: DateTime.UtcNow.AddMinutes(90),
        signingCredentials: creds
    );
asp.net-mvc jwt core
1个回答
0
投票

您可以在密钥,受众等上添加列表,如TokenValidationParameters

  ValidAudiences = new List<string> 
        {
            "AUDIENCE1",
            "AUDIENCE2" 
        }
© www.soinside.com 2019 - 2024. All rights reserved.