.Net Core中自定义认证实现
程序员文章站
2022-06-10 09:22:04
目录一、起因二、自定义认证实现三、多认证支持四、总结一、起因 最近项目中需要对项目同时支持jwt认证,以及自定义的认证校验方式认证。通过对官方文档了解,得到认证实现主要通过继承 iauthentica...
一、起因
最近项目中需要对项目同时支持jwt认证,以及自定义的认证校验方式认证。通过对官方文档了解,得到认证实现主要通过继承 iauthenticationhandler 或 authenticationhandler<toptions>来实现自定义认证的处理。
那么接下来实现一个自定义的认证访问。
二、自定义认证实现
1、根据前面内容得知,处理认证通过iauthenticationhandler 实例处理;那么首先添加一个自定义iauthenticationhandler 类型:
/// <summary> /// 方式一:自定义认证处理器 /// </summary> public class customerauthenticationhandler : iauthenticationhandler { private iuserservice _userservice; public customerauthenticationhandler(iuserservice userservice) { _userservice = userservice; } /// <summary> /// 自定义认证scheme名称 /// </summary> public const string customerschemename = "cusauth"; private authenticationscheme _scheme; private httpcontext _context; /// <summary> /// 认证逻辑:认证校验主要逻辑 /// </summary> /// <returns></returns> public task<authenticateresult> authenticateasync() { authenticateresult result; _context.request.headers.trygetvalue("authorization", out stringvalues values); string valstr = values.tostring(); if (!string.isnullorwhitespace(valstr)) { //认证模拟basic认证:cusauth ywrtaw46ywrtaw4= string[] authval = system.text.encoding.utf8.getstring(convert.frombase64string(valstr.substring(customerschemename.length + 1))).split(':'); var logininfo = new dto.logindto() { username = authval[0], password = authval[1] }; var validvale = _userservice.isvalid(logininfo); if (!validvale) result = authenticateresult.fail("未登陆"); else { var ticket = getauthticket(logininfo.username, "admin"); result = authenticateresult.success(ticket); } } else { result = authenticateresult.fail("未登陆"); } return task.fromresult(result); } /// <summary> /// 未登录时的处理 /// </summary> /// <param name="properties"></param> /// <returns></returns> public task challengeasync(authenticationproperties properties) { _context.response.statuscode = (int)httpstatuscode.unauthorized; return task.completedtask; } /// <summary> /// 权限不足时处理 /// </summary> /// <param name="properties"></param> /// <returns></returns> public task forbidasync(authenticationproperties properties) { _context.response.statuscode = (int)httpstatuscode.forbidden; return task.completedtask; } /// <summary> /// 初始化认证 /// </summary> /// <param name="scheme"></param> /// <param name="context"></param> /// <returns></returns> public task initializeasync(authenticationscheme scheme, httpcontext context) { _scheme = scheme; _context = context; return task.completedtask; } #region 认证校验逻辑 /// <summary> /// 生成认证票据 /// </summary> /// <param name="name"></param> /// <param name="role"></param> /// <returns></returns> private authenticationticket getauthticket(string name, string role) { var claimsidentity = new claimsidentity(new claim[] { new claim(claimtypes.name, name), new claim(claimtypes.role, role), }, customerschemename); var principal = new claimsprincipal(claimsidentity); return new authenticationticket(principal, _scheme.name); } #endregion } /// <summary> /// 方式二:继承已实现的基类 /// </summary> public class subauthenticationhandler : authenticationhandler<authenticationschemeoptions> { public subauthenticationhandler(ioptionsmonitor<authenticationschemeoptions> options, iloggerfactory logger, urlencoder encoder, isystemclock clock) : base(options, logger, encoder, clock) { } protected override task<authenticateresult> handleauthenticateasync() { throw new notimplementedexception(); } }
2、在startup.cs中启用自定义认证:
public void configureservices(iservicecollection services) { //other code services.addauthentication(o => { x.defaultauthenticatescheme = customerauthenticationhandler.customerschemename; x.defaultchallengescheme = customerauthenticationhandler.customerschemename; o.addscheme<customerauthenticationhandler>(customerauthenticationhandler.customerschemename, customerauthenticationhandler.customerschemename); }); //other code } public void configure(iapplicationbuilder app) { //other code app.userouting(); //在userouting后;useendpoints前添加以下代码 app.useauthentication(); app.useauthorization(); //other code app.useendpoints() }
3、在控制器上添加认证标记,测试验证
//指定认证时,采用customerauthenticationhandler.customerschemename [authorize(authenticationschemes = customerauthenticationhandler.customerschemename)] [route("api/[controller]")] [apicontroller] public class auditlogcontroller : controllerbase { //code }
调用
三、多认证支持
在实际项目中可能存在,对一个控制器支持多种认证方式如:常用的jwt认证、自定义认证等,那么如何实现呢?
1、在startup的configureservices 方法中添加以下逻辑:
public void configureservices(iservicecollection services) { //other code services.configure<jwtsetting>(configuration.getsection("jwtsetting")); var token = configuration.getsection("jwtsetting").get<jwtsetting>(); //jwt认证 services.addauthentication(x => { x.defaultauthenticatescheme = jwtbearerdefaults.authenticationscheme; x.defaultchallengescheme = jwtbearerdefaults.authenticationscheme; //添加自定义认证处理器 x.addscheme<customerauthenticationhandler>(customerauthenticationhandler.customerschemename, customerauthenticationhandler.customerschemename); }).addjwtbearer(x => { x.requirehttpsmetadata = false; x.savetoken = true; x.tokenvalidationparameters = new tokenvalidationparameters { validateissuersigningkey = true, issuersigningkey = new symmetricsecuritykey(encoding.ascii.getbytes(token.secretkey)), validissuer = token.issuer, validaudience = token.audience, validateissuer = false, validateaudience = false }; }); //other code }
2、在需要支持多种认证方式的控制器上添加标记:
//指定认证时,采用customerauthenticationhandler.customerschemename [authorize(authenticationschemes = customerauthenticationhandler.customerschemename)] [route("api/[controller]")] [apicontroller] public class auditlogcontroller : controllerbase { //code } //指定认证采用jwt [authorize(authenticationschemes = jwtbearerdefaults.authenticationscheme)] public class weatherforecastcontroller : controllerbase { //code }
这样就支持了两种认证方式
3、一个控制器支持多种认证类型:继承jwt认证处理,并根据scheme那么调用自定义的认证处理器:
/// <summary> /// 方式二:同时支持多种认证方式 /// </summary> public class multauthenticationhandler : jwtbearerhandler { public const string multauthname = "multauth"; iuserservice _userservice; public multauthenticationhandler(ioptionsmonitor<jwtbeareroptions> options, iloggerfactory logger, urlencoder encoder, isystemclock clock, iuserservice userservice) : base(options, logger, encoder, clock) { _userservice = userservice; } protected override task<authenticateresult> handleauthenticateasync() { context.request.headers.trygetvalue("authorization", out stringvalues values); string valstr = values.tostring(); if (valstr.startswith(customerauthenticationhandler.customerschemename)) { var result = valid(); if (result != null) return task.fromresult(authenticateresult.success(result)); else return task.fromresult(authenticateresult.fail("未认证")); } else return base.authenticateasync(); } private authenticationticket valid() { context.request.headers.trygetvalue("authorization", out stringvalues values); string valstr = values.tostring(); if (!string.isnullorwhitespace(valstr)) { //认证模拟basic认证:cusauth ywrtaw46ywrtaw4= string[] authval = system.text.encoding.utf8.getstring(convert.frombase64string(valstr.substring(customerauthenticationhandler.customerschemename.length + 1))).split(':'); var logininfo = new dto.logindto() { username = authval[0], password = authval[1] }; if (_userservice.isvalid(logininfo)) return getauthticket(logininfo.username, "admin"); } return null; } /// <summary> /// 生成认证票据 /// </summary> /// <param name="name"></param> /// <param name="role"></param> /// <returns></returns> private authenticationticket getauthticket(string name, string role) { var claimsidentity = new claimsidentity(new claim[] { new claim(claimtypes.name, name), new claim(claimtypes.role, role), }, customerauthenticationhandler.customerschemename); var principal = new claimsprincipal(claimsidentity); return new authenticationticket(principal, customerauthenticationhandler.customerschemename); } }
四、总结
.net core中的自定义认证主要通过实现iauthenticationhandler 接口实现,如果要实现多认证方式通过addscheme 应用自定义实现的认证处理器。
源码:github
到此这篇关于.net core中自定义认证实现的文章就介绍到这了,更多相关.net core 自定义认证内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
推荐阅读
-
.NET Core实现分表分库、读写分离的通用 Repository功能
-
ASP.NET Core利用Jaeger实现分布式追踪详解
-
在ASP.NET 2.0中操作数据之六十:创建一个自定义的Database-Driven Site Map Provider
-
C#设计模式之Template模板方法模式实现ASP.NET自定义控件 密码强度检测功能
-
浅谈.net core 注入中的三种模式:Singleton、Scoped 和 Transient
-
详解ASP.Net Core 中如何借助CSRedis实现一个安全高效的分布式锁
-
.net core 1.0 实现单点登录负载多服务器
-
NET Core TagHelper实现分页标签
-
ASP.NET Core 1.0实现邮件发送功能
-
解析在Android中为TextView增加自定义HTML标签的实现方法