应该将身份验证作为微服务架构中的一个单独服务吗?它应该做什么?

huangapple go评论76阅读模式
英文:

Should I make authentication as a separate service in a microservice architecture? What should it do?

问题

我正在尝试确定是否应该将身份验证作为我的应用程序中的单独服务进行抽象化。鉴于将其作为一个独立的微服务是一个好主意,那么它应该具体做什么呢?我的最初思考是在需要时发放JWT令牌并进行验证,但这是否会导致在每个应用程序中重复相同的身份验证代码呢?我对OpenID Connect的概念也相当陌生,即使在阅读文档后,仍然有点不清楚。

这是我认为我的微服务应该具有的内容:

public string CreateToken(User user)
{
    List<Claim> claims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, user.Name),
        //new Claim(ClaimTypes.Role, "Anonymous")
    };

    var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(
        _config.GetSection("AppSettings:Token").Value));

    var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

    var token = new JwtSecurityToken(
        claims: claims,
        expires: DateTime.Now.AddMinutes(30),
        signingCredentials: cred);

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

    return jwt;
}

public bool ValidateToken(string token)
{
    var tokenHandler = new JwtSecurityTokenHandler();
    var validationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])),
        ValidIssuer = _config["Jwt:Issuer"],
        ValidAudience = _config["Jwt:Issuer"],
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true
    };

    SecurityToken validatedToken;
    IPrincipal principal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
    return true;
}

最后,如果我最终将其抽象成一个单独的微服务,另一个微服务如何调用它呢?感谢您的时间,对于这么多问题,我感到抱歉,只是想确保我理解得对。

英文:

I am trying to figure out whether I should abstract authentication as a separate service in my application. Given that it is a good idea to have it as a standalone microservice, what should it do exactly? My initial thought process is to have it issue out JWT tokens and validate them when needed, but wouldn't this lead to me duplicating the same authentication code in every single application? I am also quite new to the concept of OpenID Connect and even after reading through the documentation, it is still a bit unclear.

This is what I think my microservice should have:

 public string CreateToken(User user)
    {
        List&lt;Claim&gt; claims = new List&lt;Claim&gt;
        {
            new Claim(ClaimTypes.Name, user.Name),
            //new Claim(ClaimTypes.Role, &quot;Anonymous&quot;)

        };

        var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(
            _config.GetSection(&quot;AppSettings:Token&quot;).Value));

        var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

        var token = new JwtSecurityToken(
            claims: claims,
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: cred);

        var jwt = new JwtSecurityTokenHandler().WriteToken(token);
        
        return jwt;
    }

    public bool ValidateToken(string token)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var validationParameters = 
        new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8
.GetBytes(_config[&quot;Jwt:Key&quot;])),
            ValidIssuer = _config[&quot;Jwt:Issuer&quot;],
            ValidAudience = _config[&quot;Jwt:Issuer&quot;],
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true
        };

        SecurityToken validatedToken;
        IPrincipal principal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
        return true;
    }

Lastly, if I do end up abstracting this into a separate microservice, how would the calling look like from another microservice? Thank you for the time and I apologize for the load of questions, just want to make sure I understand it right.

答案1

得分: 0

我的建议是始终将负责发行和管理令牌的服务放在其自己的服务中。否则,你将更难推理系统中谁在做什么以及进行故障排除。

我强烈建议使用IdentityServer来为你管理令牌。

英文:

My recommendation is to always place the service that issues and manages tokens in its own service. Otherwise you will have a much harder time reasoning about the system, who is doing what and troubleshooting.

I highly recommend using IdentityServer to manage the tokens for you.

huangapple
  • 本文由 发表于 2023年3月7日 23:19:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定