SpringBoot第三方登录流程
OAuth2AuthenticationService
该类执行获取code,token,创建connection,由SocailAuthenticationFilter调用
public class OAuth2AuthenticationService<S> extends AbstractSocialAuthenticationService<S> {
public SocialAuthenticationToken getAuthToken(HttpServletRequest request, HttpServletResponse response) throws SocialAuthenticationRedirectException {
String code = request.getParameter("code");
if (!StringUtils.hasText(code)) {
OAuth2Parameters params = new OAuth2Parameters();
//拼接redirectUrl
params.setRedirectUri(this.buildReturnToUrl(request));
this.setScope(request, params);
params.add("state", this.generateState(this.connectionFactory, request));
this.addCustomParameters(params);
throw new SocialAuthenticationRedirectException(this.getConnectionFactory().getOAuthOperations().buildAuthenticateUrl(params));
} else if (StringUtils.hasText(code)) {
try {
String returnToUrl = this.buildReturnToUrl(request);
//获取token,并返回AccessGrant
AccessGrant accessGrant = this.getConnectionFactory().getOAuthOperations().exchangeForAccess(code, returnToUrl, (MultiValueMap)null);
//创建connection
Connection<S> connection = this.getConnectionFactory().createConnection(accessGrant);
return new SocialAuthenticationToken(connection, (Map)null);
} catch (RestClientException var7) {
this.logger.debug("failed to exchange for access", var7);
return null;
}
} else {
return null;
}
}
}
SocialConfigurerAdapter
为第三方登录添加一些组件到容器,比如SpringSocialConfigurer(只是添加到容器中,需在WebSecurityConfigurerAdapter应用才可生效),JdbcUsersConnectionRepository等
- 添加Filter
SpringSecurity在添加验证时都是通过在其FilterChain上添加Filter来实现,第三方登录需要配置的是AutenticationFilter
代码演示
@Configuration
@EnableSocial
public class SocialConfig extends SocialConfigurerAdapter {
@Autowired
DataSource dataSource;
@Autowired
SecurityProperties securityProperties;
@Override
public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
return new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
}
//配置将 SpringSocialConfigurer添加到容器中,
//SpringSocialConfigurer的构造方法会在FilterChain上添加AutenticationFilter
//配置自定义SpringSocialConfigurer,需要在
@Bean
public SpringSocialConfigurer imoocSocialSecurityConfig