介绍
在微服务的应用中,统一的认证授权是必不可少的组件,本文将介绍微服务中网关和子服务如何使用统一的权限认证
主要介绍内容为:
1、子服务如何实现和网关相同的鉴权方式
2、接口权限如何动态配置与修改
3、前后端分离模式下通用的后台管理系统(用户、权限、菜单、平台)
需提前了解知识点:
1、Jwt (JSON Web Token)
2、ClaimsPrincipal
3、Microsoft.AspNetCore.Authorization、AuthorizationPolicy、AuthorizationHandler
子服务和网关鉴权方式
首先我们需要了解一下Ocelot网关权限的使用方式,直接上代码
配置
"AuthenticationOptions": {
"AuthenticationProviderKey": "TestKey",
"AllowedScopes": ["admin","user"]
}
认证
var result = await context.HttpContext.AuthenticateAsync(context.DownstreamReRoute.AuthenticationOptions.AuthenticationProviderKey);
context.HttpContext.User = result.Principal;
if (context.HttpContext.User.Identity.IsAuthenticated)
{await _next.Invoke(context);
}
权限验证
var authorised = _scopesAuthoriser.Authorise(context.HttpContext.User, context.DownstreamReRoute.AuthenticationOptions.AllowedScopes);
从以前的代码我们可以看出认证授权的逻辑
1、HttpContext.AuthenticateAsync来进行认证验证,即验证Jwt token的有效可用性,其中AuthenticationProviderKey为身份验证提供程序标识,例如
public void ConfigureServices(IServiceCollection services)
{
var authenticationProviderKey = "TestKey";
services.AddAuthentication().AddJwtBearer(authenticationProviderKey, x => { });
}
2、当1验证通过后,我们可以通过context.HttpContext.User获取key为scope的Claim数组信息(所以token生成要带上此参数),然后与配置的AllowedScopes的数组进行交集验证,当交集大于0时即为有权限访问
所以子服务如果需要实现和网关相同的权限验证就需要实现以上的方式,用过net core默认的权限认证时会发现,权限的验证都需要体现设定好接口的可访问角色等参数,这不符合我们的需求所以我们需要实现一个自定义的权限认证AuthorizationHandler,直接上代码:
public class PermissionHandler : AuthorizationHandler<JwtAuthorizationRequirement>
{
/// <summary>
/// authentication scheme provider
/// </summary>
readonly IAuthenticationSchemeProvider _schemes;
/// <summary>
/// validate permission
/// </summary>
readonly IPermissionAuthoriser _permissionAuthoriser;
/// <summary>
/// ctor
/// </summary>
/// <param name="schemes"></param>
public PermissionHandler(IAuthenticationSchemeProvider schemes, IPermissionAuthoriser permissionAuthoriser)
{
_schemes = schemes;
_permissionAuthoriser = permissionAuthoriser;
}
/// <summary>
/// handle requirement
/// </summary>
/// <param name="context">authorization handler context</param>
/// <param name="jwtAuthorizationRequirement">jwt authorization requirement</param>
/// <returns></returns>
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, JwtAuthorizationRequirement jwtAuthorizationRequirement)
{
//convert AuthorizationHandlerContext to HttpContext
var httpContext = context.Resource.GetType().GetProperty("HttpContext").GetValue(context.Resource) as HttpContext; var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();
if (defaultAuthenticate != null)
{
var result = await httpContext.AuthenticateAsync(defaultAuthenticate.Name);
if (result?.Principal != null)
{
var invockResult = _permissionAuthoriser.Authorise(httpContext);
if (invockResult)
{
context.Succeed(jwtAuthorizationRequirement);
}
else
{
context.Fail();
}
}
else
{
httpContext.Response.Headers.Add("error", "authenticate fail");
context.Fail();
}
}
else
{
httpContext.Response.Headers.Add("error", "can't find authenticate");
context.Fail();
}
}
}
其中_permissionAuthoriser.Authorise为权限验证方法,继续往下看实现逻辑
public class ScopesAuthoriser : IPermissionAuthoriser
{
private readonly IPermissionRepository _permissionRepository;
private readonly IClaimsParser _claimsParser;
private readonly string _scope = "scope";
private bool _loaded = false;
public ScopesAuthoriser(IPermissionRepository permissionRepository, IClaimsParser claimsParser)
{
_permissionRepository = permissionRepository;
_claimsParser = claimsParser;
} public bool Authorise(HttpContext httpContext)
{
if (!_loaded && _permissionRepository.Permissions.Count == )
_permissionRepository.Get();
_loaded = true; var permission = _permissionRepository.Permissions
.FirstOrDefault(it => string.Equals(it.Path, httpContext.Request.Path, StringComparison.CurrentCultureIgnoreCase) && it.Method == httpContext.Request.Method); if (permission == null)
return true; var values = _claimsParser.GetValuesByClaimType(httpContext.User.Claims, _scope); var matchesScopes = permission.Scope.Intersect(values).ToList(); if (matchesScopes.Count == )
return false; return true;
}
}
其中_permissionRepository.Permissions是应用的接口列表与接口对应的可访问scope;权限仓储下面进行介绍
接口权限如何动态配置与修改
认证授权数据库设计,tb_api_resources Api资源表、tb_roles 角色表、tb_role_apis 角色Api资源关系表、tb_users 用户表、tb_user_roles 用户角色表
常规验证权限方式,是根据用户的id查询用户角色,然后验证角色是否拥有接口权限;而在网关中是反过来该接口有哪些角色可以访问;
所以我们需要初始化出应用接口对应所需角色,目前我们实现了mysql版本的权限仓储IPermissionRepository的数据查询,代码如下
public class MySqlPermissionRepository : IPermissionRepository
{
private readonly string _dbConnectionString;
private readonly string _projectName; public MySqlPermissionRepository(string dbConnectionString, string projectName)
{
_dbConnectionString = dbConnectionString;
_projectName = projectName;
}
public List<Permission> Permissions { get; private set; } = new List<Permission>();
public async Task Get()
{
using (var dbContext = new MySqlConnection(_dbConnectionString))
{
// 平台下所有需要认证Scope的接口
var apiList = await dbContext.QueryAsync<ApiInfo>(@"SELECT api.Url,api.Method,roleapi.RoleId
FROM tb_api_resources AS api
LEFT JOIN tb_role_apis AS roleapi ON api.Id = roleapi.ApiId
WHERE AllowScope = 2 AND ProjectName = @ProjectName", new { ProjectName = _projectName });
// 所有角色
var roleList = await dbContext.QueryAsync<RoleInfo>(@"SELECT Id, `Key` from tb_roles WHERE IsDel=0", new { ProjectName = _projectName });
if (apiList.Any())
{
var permission = new List<Permission>();
var apiUrlList = apiList.GroupBy(it => it.Url).Select(it => it.FirstOrDefault()).ToList();
apiUrlList.ForEach(api =>
{
var apiMethodList = apiList.Where(it => it.Url == api.Url).GroupBy(it => it.Method).Select(it => it.FirstOrDefault()).ToList();
apiMethodList.ForEach(method =>
{
var apiInfo = apiList.Where(it => it.Url == api.Url && it.Method == method.Method).FirstOrDefault();
var roleids = apiList.Where(it => it.Url == api.Url && it.Method == method.Method).Select(it => it.RoleId).ToArray();
var scopes = roleList.Where(it => roleids.Contains(it.Id)).Select(it => it.Key).ToList();
permission.Add(new Permission
{
Path = apiInfo.Url,
Method = apiInfo.Method,
Scope = scopes
});
});
});
if (permission.Count > )
Permissions = permission;
}
}
}
}
这里只会实现一次查询,如果中间有接口权限进行了修改,那么如何进行更新呢,在上一篇配置中间使用中,我们介绍了如何使用组件的定时任务和组件的监听方式,所以我们只需做对应扩展即可,定时代码就不贴了,监听代码如下:
public class BucketAuthorizeListener : IBucketListener
{
private readonly IPermissionRepository _permissionRepository; public BucketAuthorizeListener(IPermissionRepository permissionRepository)
{
_permissionRepository = permissionRepository;
} public string ListenerName => "Bucket.Authorize"; public async Task ExecuteAsync(string commandText)
{
if (!string.IsNullOrWhiteSpace(commandText) && commandText == NetworkCommandType.Reload.ToString())
await _permissionRepository.Get();
}
}
下面贴一下Bucket.Authorize如何使用代码
public void ConfigureServices(IServiceCollection services)
{
// 添加授权
services.AddApiJwtAuthorize(Configuration);
// 添加授权认证
services.AddApiJwtAuthorize(Configuration).UseAuthoriser(services, builder => { builder.UseMySqlAuthorize(); });
}
然后在需要认证授权的action或者controller加上[Authorize("permission")]属性,appsetting配置如下,也可移至配置中心
"JwtAuthorize": {
"ProjectName": "",
"Secret": "",
"Issuer": "",
"Audience": "",
"PolicyName": "",
"DefaultScheme": "",
"IsHttps": false,
"RequireExpirationTime": true,
"MySqlConnectionString": "",
"RefreshInteval":
},
前后端分离模式下通用的后台管理系统
在FamilyBucket-UI中我们可以对项目的接口权限认证方式、用户、用户角色、角色、角色权限、角色菜单等等进行配置,
同时FamilyBucket-UI还具有通用管理系统的基础模块,里面增加一个管理平台的概念,可以直接多个管理平台使用同一个用户体系
本章就不做介绍了,内容有点长,下次再做详细介绍,在多平台同时管理时项目还需要进行一些升级,截图如下
本章涉及源码均可在github中进行查看