"[轉]三分鐘學會.NET Core Jwt 策略授權認證" 一.前言 " " 大家好我又回來了,前幾天講過一個關於Jwt的身份驗證最簡單的案例,但是功能還是不夠強大,不適用於真正的項目,是的,在真正面對複雜而又苛刻的客戶中,我們會不知所措,就現在需要將認證授權這一塊也變的複雜而又實用起來,那在專業 ...
[轉]三分鐘學會.NET Core Jwt 策略授權認證
一.前言#
大家好我又回來了,前幾天講過一個關於Jwt的身份驗證最簡單的案例,但是功能還是不夠強大,不適用於真正的項目,是的,在真正面對複雜而又苛刻的客戶中,我們會不知所措,就現在需要將認證授權這一塊也變的複雜而又實用起來,那在專業術語中就叫做自定義策略的API認證,本次案例運行在.NET Core 3.0中,最後我們將在swagger中進行瀏覽,來嘗試項目是否正常,對於.NET Core 2.x 版本,這篇文章有些代碼不適用,但我會在文中說明。
二.在.NET Core中嘗試#
我們都知道Jwt是為了認證,微軟給我們提供了進城打鬼子的城門,那就是 AuthorizationHandle。
我們首先要實現它,並且我們還可以根據依賴註入的 AuthorizationHandlerContext 來獲取上下文,就這樣我們就更可以做一些許可權的手腳
public class PolicyHandler : AuthorizationHandler<PolicyRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PolicyRequirement requirement)
{
var http = (context.Resource as Microsoft.AspNetCore.Routing.RouteEndpoint);
var questUrl = "/"+http.RoutePattern.RawText;
//賦值用戶許可權
var userPermissions = requirement.UserPermissions;
//是否經過驗證
var isAuthenticated = context.User.Identity.IsAuthenticated;
if (isAuthenticated)
{
if (userPermissions.Any(u=>u.Url == questUrl))
{
//用戶名
var userName = context.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.NameIdentifier).Value;
if (userPermissions.Any(w => w.UserName == userName))
{
context.Succeed(requirement);
}
}
}
return Task.CompletedTask;
}
}
首先,我們重寫了 HandleRequirementAsync 方法,如果你看過AspNetCore的源碼你一定知道,它是Jwt身份認證的開端,也就是說你重寫了它,原來那一套就不會走了,我們觀察一下源碼,我貼在下麵,可以看到這就是一個最基本的授權,通過 context.Succeed(requirement 完成了最後的認證動作!
public class DenyAnonymousAuthorizationRequirement : AuthorizationHandler<DenyAnonymousAuthorizationRequirement>, IAuthorizationRequirement
{
/// <summary>
/// Makes a decision if authorization is allowed based on a specific requirement.
/// </summary>
/// <param name="context">The authorization context.</param>
/// <param name="requirement">The requirement to evaluate.</param>
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DenyAnonymousAuthorizationRequirement requirement)
{
var user = context.User;
var userIsAnonymous =
user?.Identity == null ||
!user.Identities.Any(i => i.IsAuthenticated);
if (!userIsAnonymous)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
那麼 Succeed 是一個什麼呢?它是一個在 AuthorizationHandlerContext的定義動作,包括Fail() ,也是如此,當然具體實現我們不在細談,其內部還是挺複雜的,不過我們需要的是 DenyAnonymousAuthorizationRequirement 被當作了抽象的一部分。
public abstract class AuthorizationHandler<TRequirement> : IAuthorizationHandler
where TRequirement : IAuthorizationRequirement
{}
好吧,言歸正傳(看源碼挺刺激的),我們剛剛在 PolicyHandler實現了自定義認證策略,上面還說到了兩個方法。現在我們在項目中配置並啟動它,並且我在代碼中也是用了Swagger用於後面的演示。
在 AddJwtBearer中我們添加了jwt驗證包括了驗證參數以及幾個事件處理,這個很基本,不在解釋。不過在Swagger中添加jwt的一些功能是在 AddSecurityDefinition 中寫入的。
public void ConfigureServices(IServiceCollection services)
{
//添加策略鑒權模式
services.AddAuthorization(options =>
{
options.AddPolicy("Permission", policy => policy.Requirements.Add(new PolicyRequirement()));
})
.AddAuthentication(s =>
{
//添加JWT Scheme
s.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
s.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
s.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
//添加jwt驗證:
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateLifetime = true,//是否驗證失效時間
ClockSkew = TimeSpan.FromSeconds(30),
ValidateAudience = true,//是否驗證Audience
//ValidAudience = Const.GetValidudience(),//Audience
//這裡採用動態驗證的方式,在重新登陸時,刷新token,舊token就強制失效了
AudienceValidator = (m, n, z) =>
{
return m != null && m.FirstOrDefault().Equals(Const.ValidAudience);
},
ValidateIssuer = true,//是否驗證Issuer
ValidIssuer = Const.Domain,//Issuer,這兩項和前面簽發jwt的設置一致
ValidateIssuerSigningKey = true,//是否驗證SecurityKey
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey))//拿到SecurityKey
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
//Token expired
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "HaoZi JWT",
Description = "基於.NET Core 3.0 的JWT 身份驗證",
Contact = new OpenApiContact
{
Name = "zaranet",
Email = "[email protected]",
Url = new Uri("http://cnblogs.com/zaranet"),
},
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Description = "在下框中輸入請求頭中需要添加Jwt授權Token:Bearer Token",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});
//認證服務
services.AddSingleton<IAuthorizationHandler, PolicyHandler>();
services.AddControllers();
}
在以上代碼中,我們通過鑒權模式添加了認證規則,一個名叫 PolicyRequirement 的類,它實現了 IAuthorizationRequirement 介面,其中我們需要定義一些規則,通過構造函數我們可以添加我們要識別的許可權規則。那個UserName就是 Attribute 。
public class PolicyRequirement : IAuthorizationRequirement
{/// <summary>
/// User rights collection
/// </summary>
public List<UserPermission> UserPermissions { get; private set; }
/// <summary>
/// No permission action
/// </summary>
public string DeniedAction { get; set; }
/// <summary>
/// structure
/// </summary>
public PolicyRequirement()
{
//Jump to this route without permission
DeniedAction = new PathString("/api/nopermission");
//Route configuration that users have access to, of course you can read it from the database, you can also put it in Redis for persistence
UserPermissions = new List<UserPermission> {
new UserPermission { Url="/api/value3", UserName="admin"},
};
}
}
public class UserPermission
{
public string UserName { get; set; }
public string Url { get; set; }
}
隨後我們應當啟動我們的服務,在.NET Core 3.0 中身份驗證的中間件位置需要在路由和端點配置的中間。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
我們通常會有一個獲取token的API,用於讓Jwt通過 JwtSecurityTokenHandler().WriteToken(token) 用於生成我們的token,雖然jwt是沒有狀態的,但你應該也明白,如果你的jwt生成了隨後你重啟了你的網站,你的jwt會失效,這個是因為你的密鑰進行了改變,如果你的密鑰一直寫死,那麼這個jwt將不會再過期,這個還是有安全風險的,這個我不在這裡解釋,gettoken定義如下:
[ApiController]
public class AuthController : ControllerBase
{
[AllowAnonymous]
[HttpGet]
[Route("api/nopermission")]
public IActionResult NoPermission()
{
return Forbid("No Permission!");
}
/// <summary>
/// login
/// </summary>
[AllowAnonymous]
[HttpGet]
[Route("api/auth")]
public IActionResult Get(string userName, string pwd)
{
if (CheckAccount(userName, pwd, out string role))
{
Const.ValidAudience = userName + pwd + DateTime.Now.ToString();
// push the user’s name into a claim, so we can identify the user later on.
//這裡可以隨意加入自定義的參數,key可以自己隨便起
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
new Claim(ClaimTypes.NameIdentifier, userName),
new Claim("Role", role)
};
//sign the token using a secret key.This secret will be shared between your API and anything that needs to check that the token is legit.
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
//.NET Core’s JwtSecurityToken class takes on the heavy lifting and actually creates the token.
var token = new JwtSecurityToken(
issuer: Const.Domain, //頒發者
audience: Const.ValidAudience,//過期時間
expires: DateTime.Now.AddMinutes(30),// 簽名證書
signingCredentials: creds, //自定義參數
claims: claims );
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
else
{
return BadRequest(new { message = "username or password is incorrect." });
}
}
/// <summary>
/// 模擬登陸校驗
/// </summary>
private bool CheckAccount(string userName, string pwd, out string role)
{
role = "user";
if (string.IsNullOrEmpty(userName))
return false;
if (userName.Equals("admin"))
role = "admin";
return true;
}
可能比較特別的是 AllowAnonymous ,這個看我文章的同學可能頭一次見,其實怎麼說好呢,這個可無可有,沒有硬性的要求,我看到好幾個知名博主加上了,我也加上了~...最後我們創建了幾個資源控制器,它們是受保護的。
在你添加策略許可權的時候例如政策名稱是XXX,那麼在對應的api表頭就應該是XXX,隨後到了 PolicyHandler我們解析了 Claims 處理了它是否有許可權。
// GET api/values1
[HttpGet]
[Route("api/value1")]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value1" };
}
// GET api/values2
/**
* 該介面用Authorize特性做了許可權校驗,如果沒有通過許可權校驗,則http返回狀態碼為401
*/
[HttpGet]
[Route("api/value2")]
[Authorize]
public ActionResult<IEnumerable<string>> Get2()
{
var auth = HttpContext.AuthenticateAsync().Result.Principal.Claims;
var userName = auth.FirstOrDefault(t => t.Type.Equals(ClaimTypes.NameIdentifier))?.Value;
return new string[] { "這個介面登陸過的都能訪問", $"userName={userName}" };
}
/**
* 這個介面必須用admin
**/
[HttpGet]
[Route("api/value3")]
[Authorize("Permission")]
public ActionResult<IEnumerable<string>> Get3()
{
//這是獲取自定義參數的方法
var auth = HttpContext.AuthenticateAsync().Result.Principal.Claims;
var userName = auth.FirstOrDefault(t => t.Type.Equals(ClaimTypes.NameIdentifier))?.Value;
var role = auth.FirstOrDefault(t => t.Type.Equals("Role"))?.Value;
return new string[] { "這個介面有管理員許可權才可以訪問", $"userName={userName}", $"Role={role}" };
}
三.效果圖#
四.慄子源代碼和以往版本#
看到很多前輩彩的坑,原來的 (context.Resource as Microsoft.AspNetCore.Routing.RouteEndpoint); 實際上在.NET Core 3.0 已經不能用了,原因是.NET Core 3.0 啟用 EndpointRouting 後,許可權filter不再添加到 ActionDescriptor ,而將許可權直接作為中間件運行,同時所有filter都會添加到 endpoint.Metadata ,如果在.NET Core 2.1 & 2.2 版本中你通常Handler可以這麼寫:
public class PolicyHandler : AuthorizationHandler<PolicyRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PolicyRequirement requirement)
{
//賦值用戶許可權
var userPermissions = requirement.UserPermissions;
//從AuthorizationHandlerContext轉成HttpContext,以便取出表求信息
var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext;
//請求Url
var questUrl = httpContext.Request.Path.Value.ToUpperInvariant();
//是否經過驗證
var isAuthenticated = httpContext.User.Identity.IsAuthenticated;
if (isAuthenticated)
{
if (userPermissions.GroupBy(g => g.Url).Any(w => w.Key.ToUpperInvariant() == questUrl))
{
//用戶名
var userName = httpContext.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.NameIdentifier).Value;
if (userPermissions.Any(w => w.UserName == userName && w.Url.ToUpperInvariant() == questUrl))
{
context.Succeed(requirement);
}
else
{
//無許可權跳轉到拒絕頁面
httpContext.Response.Redirect(requirement.DeniedAction);
}
}
else
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
該案例源代碼在我的Github上:https://github.com/zaranetCore/aspNetCore_JsonwebToken/tree/master/Jwt_Policy_Demo 謝謝大家