springsecurity 集成第三方登录
认证及自定义流程
首先我们提供一个实现了abstractauthenticationprocessingfilter抽象类的过滤器,用来代替usernamepasswordauthenticationfilter逻辑,然后提供一个authenticationprovider实现类代替abstractuserdetailsauthenticationprovider或daoauthenticationprovider,最后再提供一个userdetailsservice实现类。
1.验证码登录
1.通用过滤器实现–thirdauthenticationfilter
这个thirdauthenticationfilter过滤器我们可以仿照usernamepasswordauthenticationfilter来实现(也实现了abstractauthenticationprocessingfilter抽象类),主要是重新定义了attemptauthentication()方法,这里需要根据“authtype”参数值的类别构建不同的abstractauthenticationtoken,具体实现如下:
//验证类型,比如sms,uernamepassword等 private string authtypeparameter = "authtype"; //对应用户名或手机号等 private string principalparameter = "principal"; //对应密码或验证码等 private string credentialsparameter = "credentials"; private boolean postonly = true; public thirdauthenticationfilter() { super(new antpathrequestmatcher("/login/dologin", "post")); } @override public authentication attemptauthentication(httpservletrequest request, httpservletresponse response) throws authenticationexception, ioexception, servletexception { if (postonly && !request.getmethod().equals("post")) { throw new authenticationserviceexception( "authentication method not supported: " + request.getmethod()); } string authtype = request.getparameter(authtypeparameter); if(stringutils.isempty(authtype)){ authtype = authtypeenum.auth_type_default.getauthtype(); } string principal = request.getparameter(principalparameter); string credentials = request.getparameter(credentialsparameter); abstractauthenticationtoken authrequest = null; switch (authtype){ case "sms": authrequest = new smsauthenticationtoken(principal, credentials); ((smsauthenticationtoken)authrequest).setcode((string)request.getsession().getattribute("code")); break; case "github": authrequest = new githubauthenticationtoken(principal, credentials); break; case "default": authrequest = new usernamepasswordauthenticationtoken(principal, credentials); } authrequest.setdetails(authenticationdetailssource.builddetails(request)); return this.getauthenticationmanager().authenticate(authrequest); } }
定义了thirdauthenticationsecurityconfig 配置类,我们还需要在springsecurity配置类中应用才能生效,具体实现如下:
@override protected void configure(httpsecurity http) throws exception { http.authorizerequests() .antmatchers("/error","/login/**","/login/gologin","/login/dologin","/login/code","/login/authorization_code").anonymous() .anyrequest().authenticated() .and() .formlogin() .loginpage("/login/gologin") .loginprocessingurl("/login/dologin") .failureurl("/login/error") .permitall() .successhandler(new qriverauthenticationsuccesshandler("/index/toindex")); //这里我们省略了一些配置 …… //应用前面定义的配置 http.apply(thirdauthenticationsecurityconfig); }
至此,我们定义的通用第三方过滤器就完成了,并且也完成了在springsecurity中生效的配置。下面我们就开始分别实现不同类型登录的具体过程。
在thirdauthenticationfilter 类的attemptauthentication()方法中,我们通过authtype类型,然后创建对应的authentication实现来实现不同方式的登录,这里我们主要实现了如下三种方式,我们分别梳理一下。
3、默认的登录过程
默认的登录过程,即根据用户名密码进行登录,需要使用到usernamepasswordauthenticationtoken,当“authtype”参数为"default"时,这里就会创建usernamepasswordauthenticationtoken对象,然后后续通过providermanager的authenticate()方法,最后就会调用abstractuserdetailsauthenticationprovider(daoauthenticationprovider)的 authenticate()方法,最终又会调用定义的userdetailsservice实现类。这是默认的过程,这里就不再重复其中的逻辑,除了userdetailsservice实现类需要自己定义,其他都是springsecurity提供的实现类。
4、短信验证码登录实现
短信验证码登录,是最贴近用户名密码登录的一种方式,所以我们完全可以仿照用户名密码这种方式实现。我们这里先梳理一下短信验证码登录的业务逻辑:首先,登录界面输入手机号码,然后再点击“获取验证码”按钮获取短信验证码,然后输入收到的短信验证码,最后点击“登录”按钮进行登录认证。和用户名密码登录相比,短信验证码登录多了一个获取验证码的过程,其他其实都是一样的,我们下面逐步实现短信验证码登录:
@restcontroller @requestmapping("/login") public class smsvalidatecodecontroller { //生成验证码的实例对象 @autowired private validatecodegenerator smscodegenerator; //调用服务商接口,发送短信验证码的实例对象 @autowired private defaultsmscodesender defaultsmscodesender; @requestmapping("/code") public string createsmscode(httpservletrequest request, httpservletresponse response) throws servletrequestbindingexception { validatecode smscode = smscodegenerator.generate(new servletwebrequest(request)); string mobile = (string)request.getparameter("principal"); request.getsession().setattribute("code",smscode.getcode()); defaultsmscodesender.send(mobile, smscode.getcode()); system.out.println("验证码:" + smscode.getcode()); return "验证码发送成功!"; } }
在上述方法中,我们注入了smscodegenerator和defaultsmscodesender两个实例对象,分别用来生成验证码和发送短信验证码,这个可以根据项目的实际情况进行定义和实现,这里不再贴出其中的实现。同时在createsmscode()方法中,还有一点需要注意的就是,我们发出去的短信验证码需要进行保存,方便后续登录时进行验证,这个也可以选择很多方法,比如说会话、数据库、缓存等,我这里为了简单,直接存到了session会话中了。
然后,我们前面定义thirdauthenticationfilter过滤器时,根据登录方式不同,需要对应的authentication对象,这里我们还需要创建短信验证登录需要的authentication类,这里我们可以仿照usernamepasswordauthenticationtoken类进行编写,实现如下
public class smsauthenticationtoken extends abstractauthenticationtoken { //对应手机号码 private final object principal; //对应手机验证码 private object credentials; //后台存储的短信验证码,用于验证前端传过来的是否正确 private string code; public smsauthenticationtoken(string mobile, object credentials){ super(null); this.principal = mobile; this.credentials = credentials; this.code = code; setauthenticated(false); } public smsauthenticationtoken(object principal, collection<? extends grantedauthority> authorities, object credentials){ super(authorities); this.principal = principal; this.credentials = credentials; super.setauthenticated(true); } @override public object getcredentials() { return this.credentials; } @override public object getprincipal() { return this.principal; } public void setauthenticated(boolean isauthenticated) throws illegalargumentexception { if (isauthenticated) { throw new illegalargumentexception( "cannot set this token to trusted - use constructor which takes a grantedauthority list instead"); } super.setauthenticated(false); } public string getcode() { return code; } public void setcode(string code) { this.code = code; } @override public void erasecredentials() { super.erasecredentials(); credentials = null; } }
在smsauthenticationtoken 类中,我们增加了一个code属性,其实该属性不是必须的,我这里是为了方便传递存储在session会话中的验证码而添加的,如果使用缓存或数据库进行存储验证码,该属性就可以省略。
在authenticationmanager的authenticate()方法中,会根据authentication类型选择authenticationprovider对象,所以我们这里自定义短信验证码需要的authenticationprovider对象,实现如下:
@component public class smsauthenticationprovider implements authenticationprovider{ @autowired @qualifier("smsuserdetailsservice") private userdetailsservice userdetailsservice; @override public authentication authenticate(authentication authentication) throws authenticationexception { smsauthenticationtoken token = (smsauthenticationtoken) authentication; string mobile = (string)token.getprincipal(); //首先,验证验证码是否正确 string code = (string)token.getcredentials(); string scode = token.getcode(); if(stringutils.isempty(code) || !code.equalsignorecase(scode)){ throw new badcredentialsexception("手机验证码错误(bad credentials),请重试!"); } //然后,查询对应用户 userdetails user = userdetailsservice.loaduserbyusername(mobile); if (objects.isnull(user)) { throw new internalauthenticationserviceexception("根据手机号:" + mobile + ",无法获取对应的用户信息!"); } smsauthenticationtoken authenticationresult = new smsauthenticationtoken(user.getusername(), user.getauthorities(), token.getcredentials()); authenticationresult.setdetails(token.getdetails()); return authenticationresult; } @override public boolean supports(class<?> authentication) { return smsauthenticationtoken.class.isassignablefrom(authentication); } }
在smsauthenticationprovider 中,supports()方法决定了该实例对象仅支持smsauthenticationtoken对象的验证。同时,根据authenticate()方法传递参数authentication对象(包括了登录信息:手机号和验证码,session存储的验证码),我们这里session存储的验证码,是因为我们采用了会话存储的方式,如果使用数据库,我们这里就可以通过手机号,去数据库或缓存查询对应的验证码,然后和authentication对象传递过来的验证码进行比对,验证成功,说明登录认证成功,否则登录认证失败。登录成功后,我们就可以调用userdetailsservice对象的loaduserbyusername()方法获取登录用户的其他相关信息(权限等),具体实现在自定义的smsuserdetailsservice类中实现,具体如下:
@component("smsuserdetailsservice") public class smsuserdetailsservice implements userdetailsservice { private logger logger = loggerfactory.getlogger(smsuserdetailsservice.class); @autowired private sysuserservice sysuserservice; @override public userdetails loaduserbyusername(string username) throws usernamenotfoundexception { //1、查询用户信息 sysuser user = new sysuser(); user.setmobile(username); sysuser quser = sysuserservice.getone(new querywrapper<>(user),true); if(quser == null) { logger.info("手机号为”" + username + "“的用户不存在!!!"); throw new usernamenotfoundexception("手机号为”" + username + "“的用户不存在!!!"); } //2、封装用户角色 userrole userrole = sysuserservice.getrolebyuserid(quser.getid()); collection<grantedauthority> authorities = new arraylist<>(); authorities.add(new simplegrantedauthority(string.valueof(userrole.getroleid()))); return new loginuser(quser.getusername(), quser.getpassword(),authorities); } }
2.github登录
和短信验证码登录认证相比,github登录又会有自己的特殊性,我们这里先梳理一下基于github进行登录验证的大致逻辑:首先,点击github登录认证按钮,然后会跳转到github登录界面,输入github系统的用户名密码,登录成功,就会跳转到我们自己的系统中的首页。和基于用户名密码的登录方式相比,github登录不需要类似用户名和密码这样的输入(在自己的系统中),同时又需要根据获取到的github用户信息,换取在自己系统对应的用户信息。具体实现步骤如下:
在github的配置省略
@controller @requestmapping("/login") public class githubvalidatecontroller { @autowired private githubclientservice githubclientservice; @requestmapping("/authorization_code") public void authorization_code(httpservletrequest request, httpservletresponse response, string code) throws servletrequestbindingexception, ioexception { //github登录验证,并获取access_token map<string,string> resp = githubclientservice.queryaccesstoken(code); //跳转本系统的登录流程,获取用户信息,实现两个系统用户的对接 string url = "http://localhost:8888/qriver-admin/login/dologin"; this.sendbypost(response, url,resp.get("access_token"),"github"); //this.sendbypost(response, url,"access_token","github"); } public void sendbypost(httpservletresponse response,string url, string principal, string authtype) throws ioexception { response.setcontenttype("text/html"); printwriter out = response.getwriter(); out.println("<!doctype html public \"-//w3c//dtd html 4.01 transitional//en\">"); out.println("<html>"); out.println(" <head><title>post 方法</title></head>"); out.println(" <body>"); out.println("<form name=\"submitform\" action=\"" + url + "\" method=\"post\">"); out.println("<input type=\"hidden\" name=\"principal\" value=\"" + principal + "\"/>"); out.println("<input type=\"hidden\" name=\"authtype\" value=\"" + authtype + "\"/>"); out.println("</from>"); out.println("<script>window.document.submitform.submit();</script> "); out.println(" </body>"); out.println("</html>"); out.flush(); out.close(); } }
“/login/authorization_code”接口对应了我们在github中配置的回调函数,即在github登录验证成功后,就会回调该接口,我们就是就在回调方法中,模拟了用户名密码登录的方式,调用了springsecurity登录认证需要的“/login/dologin”接口。这里,我们通过queryaccesstoken()方法根据回调传递的code获取对应的accesstoken,然后把accesstoken作为登录使用的principal 参数值,之而立不需要传递密码,因为我们经过github授权,就可以认为完成了登录认证的判断过程了。
其中githubclientservice类,提供了获取accesstoken和用户信息的两个方法,具体实现方式如下:
@service public class githubclientservice { //前面在github中配置时产生的 private string clientid = "######"; private string clientsecret = "######"; private string state = "123"; private string redirecturi = "http://localhost:8888/qriver-admin/login/authorization_code"; @autowired private resttemplate resttemplate; @nullable private webapplicationcontext webapplicationcontext; //获取accesstoken public map<string, string> queryaccesstoken(string code ){ map<string, string> map = new hashmap<>(); map.put("client_id", clientid); map.put("client_secret", clientsecret); map.put("state", state); map.put("code", code); map.put("redirect_uri", redirecturi); map<string,string> resp = resttemplate.postforobject("https://github.com/login/oauth/access_token", map, map.class); return resp; } //获取用户信息 public map<string, object> queryuser(string accesstoken){ httpheaders httpheaders = new httpheaders(); httpheaders.add("authorization", "token " + accesstoken); httpentity<?> httpentity = new httpentity<>(httpheaders); responseentity<map> exchange = resttemplate.exchange("https://api.github.com/user", httpmethod.get, httpentity, map.class); system.out.println("exchange.getbody() = " + exchange.getbody()); return exchange == null ? null : exchange.getbody(); } }
其实,完成了上述的配置和方式后,后续的方式就和短信验证码的逻辑一样了,这里我们简要的再梳理一下。
首先,我们也需要定义一个基于github登录需要的authentication实现类,具体实现和前面的smsauthenticationtoken类似,这里不再重复贴代码了。
然后,我们再定义一个authenticationprovider实现类githubauthenticationprovider,具体实现如下:
@component public class githubauthenticationprovider implements authenticationprovider{ @autowired @qualifier("githubuserdetailsservice") private userdetailsservice userdetailsservice; @autowired private githubclientservice githubclientservice; @override public authentication authenticate(authentication authentication) throws authenticationexception { githubauthenticationtoken token = (githubauthenticationtoken) authentication; string accesstoken = (string)token.getprincipal(); //根据accesstoken 获取github用户信息 map<string, object> userinfo = githubclientservice.queryuser(accesstoken); //然后,根据github用户,查询对应系统用户信息 userdetails user = userdetailsservice.loaduserbyusername((string)userinfo.get("login")); if (objects.isnull(user)) { throw new internalauthenticationserviceexception("根据accesstoken:" + accesstoken + ",无法获取对应的用户信息!"); } githubauthenticationtoken authenticationresult = new githubauthenticationtoken(user.getusername(), user.getauthorities(), token.getcredentials()); authenticationresult.setdetails(token.getdetails()); return authenticationresult; } @override public boolean supports(class<?> authentication) { return githubauthenticationtoken.class.isassignablefrom(authentication); } }
在githubauthenticationprovider 类的authenticate()方法中,参数authentication中对应的是github授权后传递的accesstoken值,我们这里需要根据accesstoken值换取github用户信息,这里通过queryuser()方法实现,然后根据github用户名去获取对应的系统用户信息。如果根据github用户名用户获取的系统用户为空,我们可以根据自己的需求,自动生成一个用户或者跳转到注册页面,让用户注册一个页面,这里为了简单,我们直接抛出了一个异常。
关于自定义userdetailsservice实现类,主要需要实现根据github用户名查询对应系统用户的功能
当认证完成后要返回token可以实现authenticationsuccesshandler
import org.springframework.security.core.authentication; import org.springframework.security.web.authentication.authenticationsuccesshandler; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; public class customauthenticationsuccesshandler implements authenticationsuccesshandler { private final jwttokenprovider jwttokenprovider; // 假设你有一个jwttokenprovider类来生成jwt public customauthenticationsuccesshandler(jwttokenprovider jwttokenprovider) { this.jwttokenprovider = jwttokenprovider; } @override public void onauthenticationsuccess(httpservletrequest request, httpservletresponse response, authentication authentication) throws ioexception { // 生成jwt string token = jwttokenprovider.generatetoken(authentication); // 将jwt添加到响应头中 response.setheader("authorization", "bearer " + token); // 或者将jwt添加到响应体中(取决于你的api设计) // response.getwriter().write(token); response.setstatus(httpservletresponse.sc_ok); } }
并在securityconfig中设置
到此这篇关于springsecurity集成第三方登录的文章就介绍到这了,更多相关springsecurity登录内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论