問題描述
我在 ASP.NET Core 2 Web 應(yīng)用程序中使用 JWT 令牌
I use JWT tokens in my ASP.NET Core 2 web application
如果 JWT 令牌失敗,我仍然希望調(diào)用控制器方法,但 ASP.NET 標(biāo)識 User
對象將為空.目前,如果身份驗證失敗,將不會輸入控制器方法,因此我無法在該方法中應(yīng)用邏輯來處理我想以訪客身份處理而不是阻止他們的未經(jīng)身份驗證的用戶.
If the JWT token fails I still want the controller method to be hit but the ASP.NET Identity User
object will just be null. Currently the controller method won't get entered if authentication fails so I can't apply logic inside the method to deal with non authenticated users which I want to deal with as guests instead of blocking them.
我的代碼:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication()
.AddJwtBearer(cfg =>
{
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = _config["Tokens:Issuer"],
ValidAudience = _config["Tokens:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]))
};
});
當(dāng)用戶登錄時
private IActionResult CreateToken(ApplicationUser user, IList<string> roles)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
_config["Tokens:Issuer"],
_config["Tokens:Audience"],
claims.ToArray(),
expires: DateTime.Now.AddMinutes(60),
signingCredentials: creds);
var results = new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo,
};
return Created("", results);
我確保在經(jīng)過身份驗證后,各種 API 調(diào)用都會傳遞 JWT 令牌.
I make sure after authenticated the various API calls pass the JWT token.
在我的控制器中,我使用了 Authorize 屬性
In my Controller I make use of an Authorize attribute
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class MyController : Controller
{
這允許我使用以下代碼捕獲登錄用戶以進(jìn)行各種 API 調(diào)用
This allows me to capture the logged in user with the following code for the various API calls
var loggedInUser = User.Identity.Name;
如果我刪除了授權(quán)屬性,那么 User.Identity.Name
將始終為 null,即使用戶已通過身份驗證.
If I remove the authorize attribute then User.Identity.Name
will always be null even if the user is authenticated.
如果令牌無效,如何使用授權(quán)屬性但仍允許輸入控制器方法?我想對要輸入的授權(quán)用戶和非授權(quán)用戶使用相同的方法.然后,我將使用 User.Identity.Name
來確定他們是否未經(jīng)身份驗證,并在他們的方法中包含來賓用戶邏輯.
How do I use the authorize attribute but still allow the controller method to be entered if the token is not valid? I want to use the same method for both Authorized and non Authorized users to be entered. I will then use the User.Identity.Name
to determine if they are not authenticated and have guest user logic inside the method for them.
推薦答案
這實際上比你想象的要容易.您可以只使用 both Authorize
和 AllowAnonymous
,如下所示:
It's actually easier than you might expect. You can just use both Authorize
and AllowAnonymous
, like so:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[AllowAnonymous]
public class MyController : Controller
如果授權(quán)成功,您將擁有一個經(jīng)過身份驗證的 User
(User.Identity.IsAuthenticated = true
),否則,您將擁有一個匿名 User
.
If authorization was successful, you'll have an authenticated User
(User.Identity.IsAuthenticated = true
), otherwise, you will have an anonymous User
.
這篇關(guān)于如何在控制器方法中使 JWT 令牌授權(quán)可選的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!