1. 程式人生 > >spring boot security oauth2 實現第三方登入

spring boot security oauth2 實現第三方登入

新增過濾器

private Filter ssoFilter() {
    CompositeFilter filter = new CompositeFilter();
    List<Filter> filters = new ArrayList<>();
    filters.add(ssoFilter(facebook(), "/login/facebook"));
    filters.add(ssoFilter(github(), "/login/github"));
    filter.setFilters(filters);
    return filter;
}
private Filter ssoFilter(ClientResources client, String path) {
    OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(path);
    OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
    filter.setRestTemplate(template);
    UserInfoTokenServices tokenServices = new UserInfoTokenServices(
            client.getResource().getUserInfoUri(), client.getClient().getClientId());
    tokenServices.setRestTemplate(template);
    filter.setTokenServices(tokenServices);
    return filter;
}

新增一個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

http://blog.csdn.net/w1054993544/article/details/78932614