前言
基于springcloud做微服务架构分布式系统时,oauth2.0作为认证的业内标准,spring security oauth2也提供了全套的解决方案来支持在spring cloud/spring boot环境下使用oauth2.0,提供了开箱即用的组件。但是在开发过程中我们会发现由于spring security oauth2的组件特别全面,这样就导致了扩展很不方便或者说是不太容易直指定扩展的方案,例如:
- 图片验证码登录
- 短信验证码登录
- 微信小程序登录
- 第三方系统登录
- cas单点登录
在面对这些场景的时候,预计很多对spring security oauth2不熟悉的人恐怕会无从下手。基于上述的场景要求,如何优雅的集成短信验证码登录及第三方登录,怎么样才算是优雅集成呢?有以下要求:
- 不侵入spring security oauth2的原有代码
- 对于不同的登录方式不扩展新的端点,使用/oauth/token可以适配所有的登录方式
- 可以对所有登录方式进行兼容,抽象一套模型只要简单的开发就可以集成登录
基于上述的设计要求,接下来将会在文章种详细介绍如何开发一套集成登录认证组件开满足上述要求。
阅读本篇文章您需要了解oauth2.0认证体系、springboot、springsecurity以及spring cloud等相关知识
思路
我们来看下spring security oauth2的认证流程:
这个流程当中,切入点不多,集成登录的思路如下:
- 在进入流程之前先进行拦截,设置集成认证的类型,例如:短信验证码、图片验证码等信息。
- 在拦截的通知进行预处理,预处理的场景有很多,比如验证短信验证码是否匹配、图片验证码是否匹配、是否是登录ip白名单等处理
- 在userdetailservice.loaduserbyusername方法中,根据之前设置的集成认证类型去获取用户信息,例如:通过手机号码获取用户、通过微信小程序openid获取用户等等
接入这个流程之后,基本上就可以优雅集成第三方登录。
实现
介绍完思路之后,下面通过代码来展示如何实现:
第一步,定义拦截器拦截登录的请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
/** * @author liqiu * @date 2018-3-30 **/ @component public class integrationauthenticationfilter extends genericfilterbean implements applicationcontextaware { private static final string auth_type_parm_name = "auth_type" ; private static final string oauth_token_url = "/oauth/token" ; private collection<integrationauthenticator> authenticators; private applicationcontext applicationcontext; private requestmatcher requestmatcher; public integrationauthenticationfilter(){ this .requestmatcher = new orrequestmatcher( new antpathrequestmatcher(oauth_token_url, "get" ), new antpathrequestmatcher(oauth_token_url, "post" ) ); } @override public void dofilter(servletrequest servletrequest, servletresponse servletresponse, filterchain filterchain) throws ioexception, servletexception { httpservletrequest request = (httpservletrequest) servletrequest; httpservletresponse response = (httpservletresponse) servletresponse; if (requestmatcher.matches(request)){ //设置集成登录信息 integrationauthentication integrationauthentication = new integrationauthentication(); integrationauthentication.setauthtype(request.getparameter(auth_type_parm_name)); integrationauthentication.setauthparameters(request.getparametermap()); integrationauthenticationcontext.set(integrationauthentication); try { //预处理 this .prepare(integrationauthentication); filterchain.dofilter(request,response); //后置处理 this .complete(integrationauthentication); } finally { integrationauthenticationcontext.clear(); } } else { filterchain.dofilter(request,response); } } /** * 进行预处理 * @param integrationauthentication */ private void prepare(integrationauthentication integrationauthentication) { //延迟加载认证器 if ( this .authenticators == null ){ synchronized ( this ){ map<string,integrationauthenticator> integrationauthenticatormap = applicationcontext.getbeansoftype(integrationauthenticator. class ); if (integrationauthenticatormap != null ){ this .authenticators = integrationauthenticatormap.values(); } } } if ( this .authenticators == null ){ this .authenticators = new arraylist<>(); } for (integrationauthenticator authenticator: authenticators) { if (authenticator.support(integrationauthentication)){ authenticator.prepare(integrationauthentication); } } } /** * 后置处理 * @param integrationauthentication */ private void complete(integrationauthentication integrationauthentication){ for (integrationauthenticator authenticator: authenticators) { if (authenticator.support(integrationauthentication)){ authenticator.complete(integrationauthentication); } } } @override public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception { this .applicationcontext = applicationcontext; } } |
在这个类种主要完成2部分工作:1、根据参数获取当前的是认证类型,2、根据不同的认证类型调用不同的integrationauthenticator.prepar进行预处理
第二步,将拦截器放入到拦截链条中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
/** * @author liqiu * @date 2018-3-7 **/ @configuration @enableauthorizationserver public class authorizationserverconfiguration extends authorizationserverconfigureradapter { @autowired private redisconnectionfactory redisconnectionfactory; @autowired private authenticationmanager authenticationmanager; @autowired private integrationuserdetailsservice integrationuserdetailsservice; @autowired private webresponseexceptiontranslator webresponseexceptiontranslator; @autowired private integrationauthenticationfilter integrationauthenticationfilter; @autowired private databasecachableclientdetailsservice redisclientdetailsservice; @override public void configure(clientdetailsserviceconfigurer clients) throws exception { // todo persist clients details clients.withclientdetails(redisclientdetailsservice); } @override public void configure(authorizationserverendpointsconfigurer endpoints) { endpoints .tokenstore( new redistokenstore(redisconnectionfactory)) // .accesstokenconverter(jwtaccesstokenconverter()) .authenticationmanager(authenticationmanager) .exceptiontranslator(webresponseexceptiontranslator) .reuserefreshtokens( false ) .userdetailsservice(integrationuserdetailsservice); } @override public void configure(authorizationserversecurityconfigurer security) throws exception { security.allowformauthenticationforclients() .tokenkeyaccess( "isauthenticated()" ) .checktokenaccess( "permitall()" ) .addtokenendpointauthenticationfilter(integrationauthenticationfilter); } @bean public passwordencoder passwordencoder() { return new bcryptpasswordencoder(); } @bean public jwtaccesstokenconverter jwtaccesstokenconverter() { jwtaccesstokenconverter jwtaccesstokenconverter = new jwtaccesstokenconverter(); jwtaccesstokenconverter.setsigningkey( "cola-cloud" ); return jwtaccesstokenconverter; } } |
通过调用security. .addtokenendpointauthenticationfilter(integrationauthenticationfilter);方法,将拦截器放入到认证链条中。
第三步,根据认证类型来处理用户信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
@service public class integrationuserdetailsservice implements userdetailsservice { @autowired private upmclient upmclient; private list<integrationauthenticator> authenticators; @autowired (required = false ) public void setintegrationauthenticators(list<integrationauthenticator> authenticators) { this .authenticators = authenticators; } @override public user loaduserbyusername(string username) throws usernamenotfoundexception { integrationauthentication integrationauthentication = integrationauthenticationcontext.get(); //判断是否是集成登录 if (integrationauthentication == null ) { integrationauthentication = new integrationauthentication(); } integrationauthentication.setusername(username); uservo uservo = this .authenticate(integrationauthentication); if (uservo == null ){ throw new usernamenotfoundexception( "用户名或密码错误" ); } user user = new user(); beanutils.copyproperties(uservo, user); this .setauthorize(user); return user; } /** * 设置授权信息 * * @param user */ public void setauthorize(user user) { authorize authorize = this .upmclient.getauthorize(user.getid()); user.setroles(authorize.getroles()); user.setresources(authorize.getresources()); } private uservo authenticate(integrationauthentication integrationauthentication) { if ( this .authenticators != null ) { for (integrationauthenticator authenticator : authenticators) { if (authenticator.support(integrationauthentication)) { return authenticator.authenticate(integrationauthentication); } } } return null ; } } |
这里实现了一个integrationuserdetailsservice ,在loaduserbyusername方法中会调用authenticate方法,在authenticate方法中会当前上下文种的认证类型调用不同的integrationauthenticator 来获取用户信息,接下来来看下默认的用户名密码是如何处理的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@component @primary public class usernamepasswordauthenticator extends abstractpreparableintegrationauthenticator { @autowired private ucclient ucclient; @override public uservo authenticate(integrationauthentication integrationauthentication) { return ucclient.finduserbyusername(integrationauthentication.getusername()); } @override public void prepare(integrationauthentication integrationauthentication) { } @override public boolean support(integrationauthentication integrationauthentication) { return stringutils.isempty(integrationauthentication.getauthtype()); } } |
usernamepasswordauthenticator只会处理没有指定的认证类型即是默认的认证类型,这个类中主要是通过用户名获取密码。接下来来看下图片验证码登录如何处理的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
/** * 集成验证码认证 * @author liqiu * @date 2018-3-31 **/ @component public class verificationcodeintegrationauthenticator extends usernamepasswordauthenticator { private final static string verification_code_auth_type = "vc" ; @autowired private vccclient vccclient; @override public void prepare(integrationauthentication integrationauthentication) { string vctoken = integrationauthentication.getauthparameter( "vc_token" ); string vccode = integrationauthentication.getauthparameter( "vc_code" ); //验证验证码 result< boolean > result = vccclient.validate(vctoken, vccode, null ); if (!result.getdata()) { throw new oauth2exception( "验证码错误" ); } } @override public boolean support(integrationauthentication integrationauthentication) { return verification_code_auth_type.equals(integrationauthentication.getauthtype()); } } |
verificationcodeintegrationauthenticator继承usernamepasswordauthenticator,因为其只是需要在prepare方法中验证验证码是否正确,获取用户还是用过用户名密码的方式获取。但是需要认证类型为"vc"才会处理
接下来来看下短信验证码登录是如何处理的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
@component public class smsintegrationauthenticator extends abstractpreparableintegrationauthenticator implements applicationeventpublisheraware { @autowired private ucclient ucclient; @autowired private vccclient vccclient; @autowired private passwordencoder passwordencoder; private applicationeventpublisher applicationeventpublisher; private final static string sms_auth_type = "sms" ; @override public uservo authenticate(integrationauthentication integrationauthentication) { //获取密码,实际值是验证码 string password = integrationauthentication.getauthparameter( "password" ); //获取用户名,实际值是手机号 string username = integrationauthentication.getusername(); //发布事件,可以监听事件进行自动注册用户 this .applicationeventpublisher.publishevent( new smsauthenticatebeforeevent(integrationauthentication)); //通过手机号码查询用户 uservo uservo = this .ucclient.finduserbyphonenumber(username); if (uservo != null ) { //将密码设置为验证码 uservo.setpassword(passwordencoder.encode(password)); //发布事件,可以监听事件进行消息通知 this .applicationeventpublisher.publishevent( new smsauthenticatesuccessevent(integrationauthentication)); } return uservo; } @override public void prepare(integrationauthentication integrationauthentication) { string smstoken = integrationauthentication.getauthparameter( "sms_token" ); string smscode = integrationauthentication.getauthparameter( "password" ); string username = integrationauthentication.getauthparameter( "username" ); result< boolean > result = vccclient.validate(smstoken, smscode, username); if (!result.getdata()) { throw new oauth2exception( "验证码错误或已过期" ); } } @override public boolean support(integrationauthentication integrationauthentication) { return sms_auth_type.equals(integrationauthentication.getauthtype()); } @override public void setapplicationeventpublisher(applicationeventpublisher applicationeventpublisher) { this .applicationeventpublisher = applicationeventpublisher; } } |
smsintegrationauthenticator会对登录的短信验证码进行预处理,判断其是否非法,如果是非法的则直接中断登录。如果通过预处理则在获取用户信息的时候通过手机号去获取用户信息,并将密码重置,以通过后续的密码校验。
总结
在这个解决方案中,主要是使用责任链和适配器的设计模式来解决集成登录的问题,提高了可扩展性,并对spring的源码无污染。如果还要继承其他的登录,只需要实现自定义的integrationauthenticator就可以。
项目地址:https://gitee.com/leecho/cola-cloud
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://segmentfault.com/a/1190000014371789