【问题标题】:jwt token multi tenancyjwt 令牌多租户
【发布时间】:2017-09-11 19:40:46
【问题描述】:

我在我的 ASP.NET Core 项目中通过令牌实现了 Web API 用户授权。我在每次登录时创建一个令牌,一切似乎都正常。

我的问题是该应用程序将是多租户的,因此我将在客户端拥有许多子域,例如 (Client1.myapp.com、client2.myapp.com、client3.myapp.com)

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

一些例子:

apimyapp.com/client1/api/generateToken

apimyapp.com/client2/api/generateToken

apimyapp.com/client3/api/generateToken

现在,如果我从 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
    );

【问题讨论】:

    标签: jwt asp.net-core-mvc


    【解决方案1】:

    您可以将这样的键、受众等列表添加到 TokenValidationParameters

      ValidAudiences = new List<string> 
            {
                "AUDIENCE1",
                "AUDIENCE2" 
            }
    

    【讨论】:

    • 如果我有来自多个域的请求并且他们有自己的 JWT 颁发者和受众地址,该如何配置?
    猜你喜欢
    • 2020-06-23
    • 2020-06-28
    • 2020-01-15
    • 1970-01-01
    • 2020-06-10
    • 2017-04-29
    • 1970-01-01
    • 2020-12-17
    • 2012-12-20
    相关资源
    最近更新 更多