簡體   English   中英

基於角色的身份驗證ASP.NET Core

[英]Role-based Authentication ASP.NET Core

我有一個使用JWT承載身份驗證的Web API。 現在,我想知道如何使用asp.net核心上的JWT令牌實現基於角色的授權。 我想這aritcle使用基於角色的授權,但我沒有得到太多的幫助。

有沒有人有一篇不錯的文章來研究或示例代碼以實現基於角色的授權?

謝謝。

抱歉,我忘記了該帳戶的密碼,但是我已經有了一種解決方案,該解決方案涉及如何使用JWT令牌承載來實現基於角色的授權。

var user = _userRepository.CheckLogin(login);
                if (user.UserID > 0)
                {
                    var _userManager = HttpContext.User.Claims;
                    var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Token:SecretKey"]));
                    var credentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha512);

                    var claims = new[] {
                        new Claim(JwtRegisteredClaimNames.UniqueName, user.Username), // ClaimType.Name
                        new Claim(JwtRegisteredClaimNames.Email, user.EmailAddress), // ClaimType.EmailAddress
                        new Claim(JwtRegisteredClaimNames.NameId, user.UserID.ToString()), // ClaimType.NameIdentifier
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), // jti
                        new Claim(JwtRegisteredClaimNames.Actort, user.UserKey), // ClaimType.Actor
                        new Claim(ClaimTypes.Role, user.Type) // ClaimType.Role add role for authorization.
                    };

                    var stringToken = new JwtSecurityToken(
                        _configuration["Token:Issuer"],
                        _configuration["Token:Issuer"],
                        claims,
                        expires: DateTime.Now.AddMinutes(Convert.ToInt32(_configuration["Token:ExpirationMinutes"])),
                        notBefore: DateTime.Now,
                        signingCredentials: credentials
                    );

                    var userToken = new JwtSecurityTokenHandler().WriteToken(stringToken);
                    return Ok(new { token = userToken });
                }

在聲明列表中添加ClaimTypes.Role將解決此問題,現在您可以在控制器中使用[Authorize(Roles = "???")]

我希望這將對使用JWT Bearer身份驗證添加角色的所有人有所幫助。

我已經在帶有自定義表的asp.net核心上使用JWT令牌實現了基於角色的授權。 我將示例工作源代碼放在Github上,在medium上進行了詳細解釋。

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM