打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
spring boot security oauth2 实现第三方登录

添加过滤器

  1. private Filter ssoFilter() {  
  2.     CompositeFilter filter = new CompositeFilter();  
  3.     List<Filter> filters = new ArrayList<>();  
  4.     filters.add(ssoFilter(facebook(), "/login/facebook"));  
  5.     filters.add(ssoFilter(github(), "/login/github"));  
  6.     filter.setFilters(filters);  
  7.     return filter;  
  8. }  
  9. private Filter ssoFilter(ClientResources client, String path) {  
  10.     OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(path);  
  11.     OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);  
  12.     filter.setRestTemplate(template);  
  13.     UserInfoTokenServices tokenServices = new UserInfoTokenServices(  
  14.             client.getResource().getUserInfoUri(), client.getClient().getClientId());  
  15.     tokenServices.setRestTemplate(template);  
  16.     filter.setTokenServices(tokenServices);  
  17.     return filter;  
  18. }  

添加一个CompositeFilter,这里面有一组OAuth2ClientAuthenticationProcessingFilter拦截器,分别拦截github,facebook等实现第三方登录

CompositeFilter的位置

首先看拦截器链

第6个

ApplicationFilterConfig[name=springSecurityFilterChain, filterClass=org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean$1]

其中包含了springsecurity的一系列拦截器,如下


看到了CompositeFilter


oauth2流程,以github为例

首先过滤器拦截login/github(这个是自己配置的) 然后发现没有授权码,将用户重定向到github页面进行授权,

https://github.com/login/oauth/authorize?client_id=4f06c1dd2c0ecc9adfe2&redirect_uri=http://127.0.0.1:8080/login/github&response_type=code&state=5hLsa9

redirect_uri是回调地址,要和在github配置的Authorization callback URL一致,state是我们的服务端生成的

如果用户同意,则回调在github配置的Authorization callback URL,并且带上授权码,以及之前生成的state

http://127.0.0.1:8080/login/github?code=e31c7ee0b4fec76644f9&state=mz3AtX

服务端会使用授权码code去github获取令牌

https://github.com/login/oauth/access_token

grant_type=authorization_code&code=8d4c3ce6e0ecdb0840b5&redirect_uri=http%3A%2F%2F127.0.0.1%3A8080%2Flogin%2Fgithub&client_id=4f06c1dd2c0ecc9adfe2&client_secret=11596f35d4243f7969b3839fd076d5e9938d049b

获取令牌之后会从github获取用户信息,然后重定向到首页。


http://spring.io/guides/tutorials/spring-boot-oauth2/

https://my.oschina.NET/u/1778309/blog/498822?p={{page}}

https://developer.github.com/v3/oauth/

http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
Go 每日一库之goth
ASP.NET C# 开源库OAuth2登录:OAuth2Login
从头搭建一个flask鉴权系统之登陆
7 个值得收藏的 Python 身份验证库
CAS调研记录
ScottGu's Blog
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服