当前位置:   article > 正文

spring security oauth2 使用说明_oauth2authorizedclientservice

oauth2authorizedclientservice

spring security oauth2 使用说明

 

spring security oauth2实现了oauth2协议,可搭建client(客户端)resource server(资源服务器)authorization server(认证服务器)

其中client(客户端)可用来实现三方登陆,spring-security-oauth2-client默认集成了githubgooglefacebookokta,也提供了一些接口,可实现支付宝qq微信等三方授权登录

 

 

**************************

相关 jar 包

 

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-security</artifactId>
  4. <version>2.2.6.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.security</groupId>
  8. <artifactId>spring-security-oauth2-client</artifactId>
  9. <version>5.3.1.RELEASE</version>
  10. </dependency>

 

 

**************************

配置类

 

OAuth2ClientAutoConfiguration:客户端自动配置类

  1. @Configuration(
  2. proxyBeanMethods = false
  3. )
  4. @AutoConfigureBefore({SecurityAutoConfiguration.class})
  5. @ConditionalOnClass({EnableWebSecurity.class, ClientRegistration.class})
  6. @ConditionalOnWebApplication(
  7. type = Type.SERVLET
  8. )
  9. @Import({OAuth2ClientRegistrationRepositoryConfiguration.class, OAuth2WebSecurityConfiguration.class})
  10. public class OAuth2ClientAutoConfiguration {
  11. public OAuth2ClientAutoConfiguration() {
  12. }
  13. }

说明:该自动配置类导入OAuth2ClientRegistrationRepositoryConfigurationOAuth2WebSecurityConfiguration

 

 

OAuth2ClientRegistrationRepositoryConfiguration:客户端配置类

  1. @Configuration(
  2. proxyBeanMethods = false
  3. )
  4. @EnableConfigurationProperties({OAuth2ClientProperties.class})
  5. @Conditional({ClientsConfiguredCondition.class})
  6. class OAuth2ClientRegistrationRepositoryConfiguration {
  7. OAuth2ClientRegistrationRepositoryConfiguration() {
  8. }
  9. @Bean
  10. @ConditionalOnMissingBean({ClientRegistrationRepository.class})
  11. InMemoryClientRegistrationRepository clientRegistrationRepository(OAuth2ClientProperties properties) {
  12. List<ClientRegistration> registrations = new ArrayList(OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties).values());
  13. return new InMemoryClientRegistrationRepository(registrations);
  14. }//如果不存在ClientRegistrationRepository实例,则创建InMemoryClientRegistrationRepository实例
  15. }

 

OAuth2ClientProperties:自动配置属性

  1. @ConfigurationProperties(
  2. prefix = "spring.security.oauth2.client"
  3. )
  4. public class OAuth2ClientProperties {
  5. private final Map<String, OAuth2ClientProperties.Provider> provider = new HashMap();
  6. private final Map<String, OAuth2ClientProperties.Registration> registration = new HashMap();
  7. *****************
  8. 内部类
  9. public static class Provider {
  10. private String authorizationUri;
  11. private String tokenUri;
  12. private String userInfoUri;
  13. private String userInfoAuthenticationMethod;
  14. private String userNameAttribute;
  15. private String jwkSetUri;
  16. private String issuerUri;
  17. *****************
  18. 内部类
  19. public static class Registration {
  20. private String provider;
  21. private String clientId;
  22. private String clientSecret;
  23. private String clientAuthenticationMethod;
  24. private String authorizationGrantType;
  25. private String redirectUri;
  26. private Set<String> scope;
  27. private String clientName;

 

ClientRegistrationRepository:根据registrationId查找ClientRegistration类

  1. public interface ClientRegistrationRepository {
  2. ClientRegistration findByRegistrationId(String var1);
  3. }

 

InMemoryClientRegistrationRepository:使用内存保存客户端配置

  1. public final class InMemoryClientRegistrationRepository implements ClientRegistrationRepository, Iterable<ClientRegistration> {
  2. private final Map<String, ClientRegistration> registrations;
  3. public InMemoryClientRegistrationRepository(ClientRegistration... registrations) {
  4. this(Arrays.asList(registrations));
  5. }
  6. public InMemoryClientRegistrationRepository(List<ClientRegistration> registrations) {
  7. this(createRegistrationsMap(registrations));
  8. }
  9. private static Map<String, ClientRegistration> createRegistrationsMap(List<ClientRegistration> registrations) {
  10. Assert.notEmpty(registrations, "registrations cannot be empty");
  11. return toUnmodifiableConcurrentMap(registrations);
  12. }
  13. private static Map<String, ClientRegistration> toUnmodifiableConcurrentMap(List<ClientRegistration> registrations) {
  14. ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap();
  15. Iterator var2 = registrations.iterator();
  16. while(var2.hasNext()) {
  17. ClientRegistration registration = (ClientRegistration)var2.next();
  18. if (result.containsKey(registration.getRegistrationId())) {
  19. throw new IllegalStateException(String.format("Duplicate key %s", registration.getRegistrationId()));
  20. }
  21. result.put(registration.getRegistrationId(), registration);
  22. }
  23. return Collections.unmodifiableMap(result);
  24. }
  25. public InMemoryClientRegistrationRepository(Map<String, ClientRegistration> registrations) {
  26. Assert.notNull(registrations, "registrations cannot be null");
  27. this.registrations = registrations;
  28. }
  29. public ClientRegistration findByRegistrationId(String registrationId) {
  30. Assert.hasText(registrationId, "registrationId cannot be empty");
  31. return (ClientRegistration)this.registrations.get(registrationId);
  32. }
  33. public Iterator<ClientRegistration> iterator() {
  34. return this.registrations.values().iterator();
  35. }
  36. }

 

 

OAuth2WebSecurityConfiguration:oauth2客户端安全配置

  1. @Configuration(
  2. proxyBeanMethods = false
  3. )
  4. @ConditionalOnBean({ClientRegistrationRepository.class})
  5. class OAuth2WebSecurityConfiguration {
  6. OAuth2WebSecurityConfiguration() {
  7. }
  8. @Bean
  9. @ConditionalOnMissingBean
  10. OAuth2AuthorizedClientService authorizedClientService(ClientRegistrationRepository clientRegistrationRepository) {
  11. return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
  12. }//不存在 OAuth2AuthorizedClientService,则创建该类
  13. @Bean
  14. @ConditionalOnMissingBean
  15. OAuth2AuthorizedClientRepository authorizedClientRepository(OAuth2AuthorizedClientService authorizedClientService) {
  16. return new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService);
  17. }//不存在授权客户端,则创建AuthenticatedPrincipalOAuth2AuthorizedClientRepository
  18. @Configuration(
  19. proxyBeanMethods = false
  20. )
  21. @ConditionalOnMissingBean({WebSecurityConfigurerAdapter.class})
  22. static class OAuth2WebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
  23. OAuth2WebSecurityConfigurerAdapter() {
  24. }
  25. protected void configure(HttpSecurity http) throws Exception {
  26. http.authorizeRequests((requests) -> {
  27. ((AuthorizedUrl)requests.anyRequest()).authenticated();
  28. });
  29. http.oauth2Login(Customizer.withDefaults());
  30. http.oauth2Client();
  31. }//配置默认的安全策略
  32. }
  33. }

 

OAuth2AuthorizedClientService:授权客户端操作接口

  1. public interface OAuth2AuthorizedClientService {
  2. <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String var1, String var2); //加载授权客户端
  3. void saveAuthorizedClient(OAuth2AuthorizedClient var1, Authentication var2); //保存授权客户端
  4. void removeAuthorizedClient(String var1, String var2); //删除授权客户端
  5. }

 

InMemoryOAuth2AuthorizedClientService:授权客户端操作类

  1. public final class InMemoryOAuth2AuthorizedClientService implements OAuth2AuthorizedClientService {
  2. private final Map<OAuth2AuthorizedClientId, OAuth2AuthorizedClient> authorizedClients; //保存授权客户端
  3. private final ClientRegistrationRepository clientRegistrationRepository;
  4. public InMemoryOAuth2AuthorizedClientService(ClientRegistrationRepository clientRegistrationRepository) {
  5. Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
  6. this.clientRegistrationRepository = clientRegistrationRepository;
  7. this.authorizedClients = new ConcurrentHashMap();
  8. }
  9. public InMemoryOAuth2AuthorizedClientService(ClientRegistrationRepository clientRegistrationRepository, Map<OAuth2AuthorizedClientId, OAuth2AuthorizedClient> authorizedClients) {
  10. Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
  11. Assert.notEmpty(authorizedClients, "authorizedClients cannot be empty");
  12. this.clientRegistrationRepository = clientRegistrationRepository;
  13. this.authorizedClients = new ConcurrentHashMap(authorizedClients);
  14. }
  15. public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId, String principalName) {
  16. Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
  17. Assert.hasText(principalName, "principalName cannot be empty");
  18. ClientRegistration registration = this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId);
  19. return registration == null ? null : (OAuth2AuthorizedClient)this.authorizedClients.get(new OAuth2AuthorizedClientId(clientRegistrationId, principalName));
  20. }
  21. public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
  22. Assert.notNull(authorizedClient, "authorizedClient cannot be null");
  23. Assert.notNull(principal, "principal cannot be null");
  24. this.authorizedClients.put(new OAuth2AuthorizedClientId(authorizedClient.getClientRegistration().getRegistrationId(), principal.getName()), authorizedClient);
  25. }
  26. public void removeAuthorizedClient(String clientRegistrationId, String principalName) {
  27. Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
  28. Assert.hasText(principalName, "principalName cannot be empty");
  29. ClientRegistration registration = this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId);
  30. if (registration != null) {
  31. this.authorizedClients.remove(new OAuth2AuthorizedClientId(clientRegistrationId, principalName));
  32. }
  33. }
  34. }

 

OAuth2AuthorizedClientId:Map<OAuth2AuthorizedClientId, OAuth2AuthorizedClient> authorizedClients中的key

  1. public final class OAuth2AuthorizedClientId implements Serializable {
  2. private static final long serialVersionUID = 530L;
  3. private final String clientRegistrationId;
  4. private final String principalName;
  5. public OAuth2AuthorizedClientId(String clientRegistrationId, String principalName) {
  6. public boolean equals(Object obj) {
  7. public int hashCode() {

 

OAuth2AuthorizedClient:oauth2授权客户端

  1. public class OAuth2AuthorizedClient implements Serializable {
  2. private static final long serialVersionUID = 530L;
  3. private final ClientRegistration clientRegistration;
  4. private final String principalName;
  5. private final OAuth2AccessToken accessToken;
  6. private final OAuth2RefreshToken refreshToken;
  7. public OAuth2AuthorizedClient(ClientRegistration clientRegistration, String principalName, OAuth2AccessToken accessToken) {
  8. public OAuth2AuthorizedClient(ClientRegistration clientRegistration, String principalName, OAuth2AccessToken accessToken, @Nullable OAuth2RefreshToken refreshToken) {
  9. public ClientRegistration getClientRegistration() { //获取客户端配置类
  10. public String getPrincipalName() { //获取认证用户名称
  11. public OAuth2AccessToken getAccessToken() { //获取access token
  12. @Nullable
  13. public OAuth2RefreshToken getRefreshToken() {

 

ClientRegistration:客户端类

  1. public final class ClientRegistration implements Serializable {
  2. private static final long serialVersionUID = 530L;
  3. private String registrationId;
  4. private String clientId;
  5. private String clientSecret;
  6. private ClientAuthenticationMethod clientAuthenticationMethod;
  7. private AuthorizationGrantType authorizationGrantType;
  8. private String redirectUriTemplate;
  9. private Set<String> scopes;
  10. private ClientRegistration.ProviderDetails providerDetails;
  11. private String clientName;
  12. private ClientRegistration() {
  13. this.clientAuthenticationMethod = ClientAuthenticationMethod.BASIC;
  14. this.scopes = Collections.emptySet();
  15. this.providerDetails = new ClientRegistration.ProviderDetails();
  16. }
  17. public String getRegistrationId() {
  18. public String getClientId() {
  19. public String getClientSecret() {
  20. public ClientAuthenticationMethod getClientAuthenticationMethod() {
  21. public AuthorizationGrantType getAuthorizationGrantType() {
  22. public String getRedirectUriTemplate() {
  23. public Set<String> getScopes() {
  24. public ClientRegistration.ProviderDetails getProviderDetails() {
  25. public String getClientName() {
  26. public String toString() {
  27. public static ClientRegistration.Builder withRegistrationId(String registrationId) {
  28. Assert.hasText(registrationId, "registrationId cannot be empty");
  29. return new ClientRegistration.Builder(registrationId);
  30. }
  31. public static ClientRegistration.Builder withClientRegistration(ClientRegistration clientRegistration) {
  32. Assert.notNull(clientRegistration, "clientRegistration cannot be null");
  33. return new ClientRegistration.Builder(clientRegistration);
  34. }
  35. *****************
  36. 内部类:ClientRegistration.Builder
  37. public static class Builder implements Serializable {
  38. private static final long serialVersionUID = 530L;
  39. private String registrationId;
  40. private String clientId;
  41. private String clientSecret;
  42. private ClientAuthenticationMethod clientAuthenticationMethod;
  43. private AuthorizationGrantType authorizationGrantType;
  44. private String redirectUriTemplate;
  45. private Set<String> scopes;
  46. private String authorizationUri;
  47. private String tokenUri;
  48. private String userInfoUri;
  49. private AuthenticationMethod userInfoAuthenticationMethod;
  50. private String userNameAttributeName;
  51. private String jwkSetUri;
  52. private Map<String, Object> configurationMetadata;
  53. private String clientName;
  54. private Builder(String registrationId) {
  55. this.clientAuthenticationMethod = ClientAuthenticationMethod.BASIC;
  56. this.userInfoAuthenticationMethod = AuthenticationMethod.HEADER;
  57. this.configurationMetadata = Collections.emptyMap();
  58. this.registrationId = registrationId;
  59. }
  60. private Builder(ClientRegistration clientRegistration) {
  61. public ClientRegistration.Builder registrationId(String registrationId) {
  62. public ClientRegistration.Builder clientId(String clientId) {
  63. public ClientRegistration.Builder clientSecret(String clientSecret) {
  64. public ClientRegistration.Builder clientAuthenticationMethod(ClientAuthenticationMethod clientAuthenticationMethod) {
  65. public ClientRegistration.Builder authorizationGrantType(AuthorizationGrantType authorizationGrantType) {
  66. public ClientRegistration.Builder redirectUriTemplate(String redirectUriTemplate) {
  67. public ClientRegistration.Builder scope(String... scope) {
  68. public ClientRegistration.Builder scope(Collection<String> scope) {
  69. public ClientRegistration.Builder authorizationUri(String authorizationUri) {
  70. public ClientRegistration.Builder tokenUri(String tokenUri) {
  71. public ClientRegistration.Builder userInfoUri(String userInfoUri) {
  72. public ClientRegistration.Builder userInfoAuthenticationMethod(AuthenticationMethod userInfoAuthenticationMethod) {
  73. public ClientRegistration.Builder userNameAttributeName(String userNameAttributeName) {
  74. public ClientRegistration.Builder jwkSetUri(String jwkSetUri) {
  75. public ClientRegistration.Builder providerConfigurationMetadata(Map<String, Object> configurationMetadata) {
  76. public ClientRegistration.Builder clientName(String clientName) {
  77. public ClientRegistration build() {
  78. private ClientRegistration create() {
  79. private void validateAuthorizationCodeGrantType() {
  80. private void validateImplicitGrantType() {
  81. private void validatePasswordGrantType() {
  82. private void validateScopes() {
  83. private static boolean validateScope(String scope) {
  84. *****************
  85. 内部类:ClientRegistration.ProviderDetails
  86. public class ProviderDetails implements Serializable {
  87. private static final long serialVersionUID = 530L;
  88. private String authorizationUri;
  89. private String tokenUri;
  90. private ClientRegistration.ProviderDetails.UserInfoEndpoint userInfoEndpoint;
  91. private String jwkSetUri;
  92. private Map<String, Object> configurationMetadata;
  93. private ProviderDetails() {
  94. this.userInfoEndpoint = new ClientRegistration.ProviderDetails.UserInfoEndpoint();
  95. this.configurationMetadata = Collections.emptyMap();
  96. }
  97. public String getAuthorizationUri() {
  98. public String getTokenUri() {
  99. public ClientRegistration.ProviderDetails.UserInfoEndpoint getUserInfoEndpoint() {
  100. public String getJwkSetUri() {
  101. public Map<String, Object> getConfigurationMetadata() {
  102. *****************
  103. 内部类:ClientRegistration.ProviderDetails.UserInfoEndpoint
  104. public class UserInfoEndpoint implements Serializable {
  105. private static final long serialVersionUID = 530L;
  106. private String uri;
  107. private AuthenticationMethod authenticationMethod;
  108. private String userNameAttributeName;
  109. private UserInfoEndpoint() {
  110. this.authenticationMethod = AuthenticationMethod.HEADER;
  111. }
  112. public String getUri() {
  113. public AuthenticationMethod getAuthenticationMethod() {
  114. public String getUserNameAttributeName() {

 

 

OAuth2AuthorizedClientRepository:授权客户端操作接口

  1. public interface OAuth2AuthorizedClientRepository {
  2. <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String var1, Authentication var2, HttpServletRequest var3);
  3. void saveAuthorizedClient(OAuth2AuthorizedClient var1, Authentication var2, HttpServletRequest var3, HttpServletResponse var4);
  4. void removeAuthorizedClient(String var1, Authentication var2, HttpServletRequest var3, HttpServletResponse var4);
  5. }

 

AuthenticatedPrincipalOAuth2AuthorizedClientRepository:OAuth2AuthorizedClientRepository接口实现类

  1. public final class AuthenticatedPrincipalOAuth2AuthorizedClientRepository implements OAuth2AuthorizedClientRepository {
  2. private final AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
  3. private final OAuth2AuthorizedClientService authorizedClientService;
  4. //内部调用authorizedClientService方法
  5. private OAuth2AuthorizedClientRepository anonymousAuthorizedClientRepository = new HttpSessionOAuth2AuthorizedClientRepository();
  6. public AuthenticatedPrincipalOAuth2AuthorizedClientRepository(OAuth2AuthorizedClientService authorizedClientService) {
  7. Assert.notNull(authorizedClientService, "authorizedClientService cannot be null");
  8. this.authorizedClientService = authorizedClientService;
  9. }
  10. public void setAnonymousAuthorizedClientRepository(OAuth2AuthorizedClientRepository anonymousAuthorizedClientRepository) {
  11. Assert.notNull(anonymousAuthorizedClientRepository, "anonymousAuthorizedClientRepository cannot be null");
  12. this.anonymousAuthorizedClientRepository = anonymousAuthorizedClientRepository;
  13. }
  14. public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId, Authentication principal, HttpServletRequest request) {
  15. return this.isPrincipalAuthenticated(principal) ? this.authorizedClientService.loadAuthorizedClient(clientRegistrationId, principal.getName()) : this.anonymousAuthorizedClientRepository.loadAuthorizedClient(clientRegistrationId, principal, request);
  16. //通过认证后,调用authotizedClientService的loadAuthorizedClient加载授权客户端
  17. }
  18. public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal, HttpServletRequest request, HttpServletResponse response) {
  19. if (this.isPrincipalAuthenticated(principal)) {
  20. this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal);
  21. //通过认证后,调用authoriedClientService的saveAuthorizedClient保存授权客户端
  22. } else {
  23. this.anonymousAuthorizedClientRepository.saveAuthorizedClient(authorizedClient, principal, request, response);
  24. }
  25. }
  26. public void removeAuthorizedClient(String clientRegistrationId, Authentication principal, HttpServletRequest request, HttpServletResponse response) {
  27. if (this.isPrincipalAuthenticated(principal)) {
  28. this.authorizedClientService.removeAuthorizedClient(clientRegistrationId, principal.getName());
  29. //通过认证后,调用authoriedClientService的removeAuthorizedClient删除授权客户端
  30. } else {
  31. this.anonymousAuthorizedClientRepository.removeAuthorizedClient(clientRegistrationId, principal, request, response);
  32. }
  33. }
  34. private boolean isPrincipalAuthenticated(Authentication authentication) {
  35. return authentication != null && !this.authenticationTrustResolver.isAnonymous(authentication) && authentication.isAuthenticated();
  36. }
  37. }

 

CommonOAuth2Provider:默认提供的三方客户端配置,google、github、facebook、okta

  1. public enum CommonOAuth2Provider {
  2. GOOGLE {
  3. public Builder getBuilder(String registrationId) {
  4. Builder builder = this.getBuilder(registrationId, ClientAuthenticationMethod.BASIC, "{baseUrl}/{action}/oauth2/code/{registrationId}");
  5. builder.scope(new String[]{"openid", "profile", "email"});
  6. builder.authorizationUri("https://accounts.google.com/o/oauth2/v2/auth");
  7. builder.tokenUri("https://www.googleapis.com/oauth2/v4/token");
  8. builder.jwkSetUri("https://www.googleapis.com/oauth2/v3/certs");
  9. builder.userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo");
  10. builder.userNameAttributeName("sub");
  11. builder.clientName("Google");
  12. return builder;
  13. }
  14. },
  15. GITHUB {
  16. public Builder getBuilder(String registrationId) {
  17. Builder builder = this.getBuilder(registrationId, ClientAuthenticationMethod.BASIC, "{baseUrl}/{action}/oauth2/code/{registrationId}");
  18. builder.scope(new String[]{"read:user"});
  19. builder.authorizationUri("https://github.com/login/oauth/authorize");
  20. builder.tokenUri("https://github.com/login/oauth/access_token");
  21. builder.userInfoUri("https://api.github.com/user");
  22. builder.userNameAttributeName("id");
  23. builder.clientName("GitHub");
  24. return builder;
  25. }
  26. },
  27. FACEBOOK {
  28. public Builder getBuilder(String registrationId) {
  29. Builder builder = this.getBuilder(registrationId, ClientAuthenticationMethod.POST, "{baseUrl}/{action}/oauth2/code/{registrationId}");
  30. builder.scope(new String[]{"public_profile", "email"});
  31. builder.authorizationUri("https://www.facebook.com/v2.8/dialog/oauth");
  32. builder.tokenUri("https://graph.facebook.com/v2.8/oauth/access_token");
  33. builder.userInfoUri("https://graph.facebook.com/me?fields=id,name,email");
  34. builder.userNameAttributeName("id");
  35. builder.clientName("Facebook");
  36. return builder;
  37. }
  38. },
  39. OKTA {
  40. public Builder getBuilder(String registrationId) {
  41. Builder builder = this.getBuilder(registrationId, ClientAuthenticationMethod.BASIC, "{baseUrl}/{action}/oauth2/code/{registrationId}");
  42. builder.scope(new String[]{"openid", "profile", "email"});
  43. builder.userNameAttributeName("sub");
  44. builder.clientName("Okta");
  45. return builder;
  46. }
  47. };
  48. private static final String DEFAULT_REDIRECT_URL = "{baseUrl}/{action}/oauth2/code/{registrationId}";
  49. private CommonOAuth2Provider() {
  50. }
  51. protected final Builder getBuilder(String registrationId, ClientAuthenticationMethod method, String redirectUri) {
  52. Builder builder = ClientRegistration.withRegistrationId(registrationId);
  53. builder.clientAuthenticationMethod(method);
  54. builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE);
  55. builder.redirectUriTemplate(redirectUri);
  56. return builder;
  57. }
  58. public abstract Builder getBuilder(String var1);
  59. }

 

 

**************************

安全配置类

 

HttpSecurity:安全配置

  1. public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain, HttpSecurity> implements SecurityBuilder<DefaultSecurityFilterChain>, HttpSecurityBuilder<HttpSecurity> {
  2. ***************
  3. OAuth2Login 相关配置
  4. public OAuth2LoginConfigurer<HttpSecurity> oauth2Login() throws Exception {
  5. return (OAuth2LoginConfigurer)this.getOrApply(new OAuth2LoginConfigurer());
  6. }
  7. public HttpSecurity oauth2Login(Customizer<OAuth2LoginConfigurer<HttpSecurity>> oauth2LoginCustomizer) throws Exception {
  8. oauth2LoginCustomizer.customize(this.getOrApply(new OAuth2LoginConfigurer()));
  9. return this;
  10. }

 

OAuth2LoginConfigurer

  1. public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> extends AbstractAuthenticationFilterConfigurer<B, OAuth2LoginConfigurer<B>, OAuth2LoginAuthenticationFilter> {
  2. private final OAuth2LoginConfigurer<B>.AuthorizationEndpointConfig authorizationEndpointConfig = new OAuth2LoginConfigurer.AuthorizationEndpointConfig();
  3. private final OAuth2LoginConfigurer<B>.TokenEndpointConfig tokenEndpointConfig = new OAuth2LoginConfigurer.TokenEndpointConfig();
  4. private final OAuth2LoginConfigurer<B>.RedirectionEndpointConfig redirectionEndpointConfig = new OAuth2LoginConfigurer.RedirectionEndpointConfig();
  5. private final OAuth2LoginConfigurer<B>.UserInfoEndpointConfig userInfoEndpointConfig = new OAuth2LoginConfigurer.UserInfoEndpointConfig();
  6. private String loginPage;
  7. private String loginProcessingUrl = "/login/oauth2/code/*"; //获得授权码code后的回调路径
  8. public OAuth2LoginConfigurer() {
  9. }
  10. public OAuth2LoginConfigurer<B> clientRegistrationRepository(ClientRegistrationRepository clientRegistrationRepository) {
  11. public OAuth2LoginConfigurer<B> authorizedClientRepository(OAuth2AuthorizedClientRepository authorizedClientRepository) {
  12. public OAuth2LoginConfigurer<B> authorizedClientService(OAuth2AuthorizedClientService authorizedClientService) {
  13. public OAuth2LoginConfigurer<B> loginPage(String loginPage) {
  14. public OAuth2LoginConfigurer<B> loginProcessingUrl(String loginProcessingUrl) {
  15. *************
  16. authorizationEndpoint:请求获取授权码相关操作
  17. public OAuth2LoginConfigurer<B>.AuthorizationEndpointConfig authorizationEndpoint() {
  18. public OAuth2LoginConfigurer<B> authorizationEndpoint(Customizer<OAuth2LoginConfigurer<B>.AuthorizationEndpointConfig> authorizationEndpointCustomizer) {
  19. *************
  20. tokenEndpoint:token相关操作
  21. public OAuth2LoginConfigurer<B>.TokenEndpointConfig tokenEndpoint() {
  22. public OAuth2LoginConfigurer<B> tokenEndpoint(Customizer<OAuth2LoginConfigurer<B>.TokenEndpointConfig> tokenEndpointCustomizer) {
  23. *************
  24. redirectionEndpoint:获取授权码code后的回调操作
  25. public OAuth2LoginConfigurer<B>.RedirectionEndpointConfig redirectionEndpoint() {
  26. public OAuth2LoginConfigurer<B> redirectionEndpoint(Customizer<OAuth2LoginConfigurer<B>.RedirectionEndpointConfig> redirectionEndpointCustomizer) {
  27. *************
  28. userInfoEndpoint:用户信息操作(用户权限、自定义用户类)
  29. public OAuth2LoginConfigurer<B>.UserInfoEndpointConfig userInfoEndpoint() {
  30. public OAuth2LoginConfigurer<B> userInfoEndpoint(Customizer<OAuth2LoginConfigurer<B>.UserInfoEndpointConfig> userInfoEndpointCustomizer) {
  31. public void init(B http) throws Exception { //初始化操作
  32. OAuth2LoginAuthenticationFilter authenticationFilter = new OAuth2LoginAuthenticationFilter(OAuth2ClientConfigurerUtils.getClientRegistrationRepository((HttpSecurityBuilder)this.getBuilder()), OAuth2ClientConfigurerUtils.getAuthorizedClientRepository((HttpSecurityBuilder)this.getBuilder()), this.loginProcessingUrl);
  33. this.setAuthenticationFilter(authenticationFilter); //设置登录认证过滤器
  34. super.loginProcessingUrl(this.loginProcessingUrl); //设置登陆处理路径,默认为:/login/oauth2/code/*
  35. if (this.loginPage != null) {
  36. super.loginPage(this.loginPage);
  37. super.init(http);
  38. } else {
  39. Map<String, String> loginUrlToClientName = this.getLoginLinks();
  40. if (loginUrlToClientName.size() == 1) {
  41. this.updateAuthenticationDefaults();
  42. this.updateAccessDefaults(http);
  43. String providerLoginPage = (String)loginUrlToClientName.keySet().iterator().next();
  44. this.registerAuthenticationEntryPoint(http, this.getLoginEntryPoint(http, providerLoginPage));
  45. } else {
  46. super.init(http);
  47. }
  48. } //登陆页面路径设置,默认为:/login
  49. OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient = this.tokenEndpointConfig.accessTokenResponseClient;
  50. if (accessTokenResponseClient == null) {
  51. accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient();
  52. }
  53. OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService = this.getOAuth2UserService();
  54. OAuth2LoginAuthenticationProvider oauth2LoginAuthenticationProvider = new OAuth2LoginAuthenticationProvider((OAuth2AccessTokenResponseClient)accessTokenResponseClient, oauth2UserService);
  55. GrantedAuthoritiesMapper userAuthoritiesMapper = this.getGrantedAuthoritiesMapper();
  56. if (userAuthoritiesMapper != null) {
  57. oauth2LoginAuthenticationProvider.setAuthoritiesMapper(userAuthoritiesMapper);
  58. }
  59. http.authenticationProvider((AuthenticationProvider)this.postProcess(oauth2LoginAuthenticationProvider));
  60. boolean oidcAuthenticationProviderEnabled = ClassUtils.isPresent("org.springframework.security.oauth2.jwt.JwtDecoder", this.getClass().getClassLoader());
  61. if (oidcAuthenticationProviderEnabled) {
  62. OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService = this.getOidcUserService();
  63. OidcAuthorizationCodeAuthenticationProvider oidcAuthorizationCodeAuthenticationProvider = new OidcAuthorizationCodeAuthenticationProvider((OAuth2AccessTokenResponseClient)accessTokenResponseClient, oidcUserService);
  64. JwtDecoderFactory<ClientRegistration> jwtDecoderFactory = this.getJwtDecoderFactoryBean();
  65. if (jwtDecoderFactory != null) {
  66. oidcAuthorizationCodeAuthenticationProvider.setJwtDecoderFactory(jwtDecoderFactory);
  67. }
  68. if (userAuthoritiesMapper != null) {
  69. oidcAuthorizationCodeAuthenticationProvider.setAuthoritiesMapper(userAuthoritiesMapper);
  70. }
  71. http.authenticationProvider((AuthenticationProvider)this.postProcess(oidcAuthorizationCodeAuthenticationProvider));
  72. } else {
  73. http.authenticationProvider(new OAuth2LoginConfigurer.OidcAuthenticationRequestChecker());
  74. }
  75. this.initDefaultLoginFilter(http);
  76. }
  77. public void configure(B http) throws Exception {
  78. OAuth2AuthorizationRequestRedirectFilter authorizationRequestFilter;
  79. if (this.authorizationEndpointConfig.authorizationRequestResolver != null) {
  80. authorizationRequestFilter = new OAuth2AuthorizationRequestRedirectFilter(this.authorizationEndpointConfig.authorizationRequestResolver);
  81. } else {
  82. String authorizationRequestBaseUri = this.authorizationEndpointConfig.authorizationRequestBaseUri;
  83. if (authorizationRequestBaseUri == null) {
  84. authorizationRequestBaseUri = "/oauth2/authorization";
  85. }
  86. authorizationRequestFilter = new OAuth2AuthorizationRequestRedirectFilter(OAuth2ClientConfigurerUtils.getClientRegistrationRepository((HttpSecurityBuilder)this.getBuilder()), authorizationRequestBaseUri);
  87. }
  88. if (this.authorizationEndpointConfig.authorizationRequestRepository != null) {
  89. authorizationRequestFilter.setAuthorizationRequestRepository(this.authorizationEndpointConfig.authorizationRequestRepository);
  90. }
  91. RequestCache requestCache = (RequestCache)http.getSharedObject(RequestCache.class);
  92. if (requestCache != null) {
  93. authorizationRequestFilter.setRequestCache(requestCache);
  94. }
  95. http.addFilter((Filter)this.postProcess(authorizationRequestFilter));
  96. OAuth2LoginAuthenticationFilter authenticationFilter = (OAuth2LoginAuthenticationFilter)this.getAuthenticationFilter();
  97. if (this.redirectionEndpointConfig.authorizationResponseBaseUri != null) {
  98. authenticationFilter.setFilterProcessesUrl(this.redirectionEndpointConfig.authorizationResponseBaseUri);
  99. }
  100. if (this.authorizationEndpointConfig.authorizationRequestRepository != null) {
  101. authenticationFilter.setAuthorizationRequestRepository(this.authorizationEndpointConfig.authorizationRequestRepository);
  102. }
  103. super.configure(http);
  104. }
  105. protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) {
  106. private JwtDecoderFactory<ClientRegistration> getJwtDecoderFactoryBean() {
  107. private GrantedAuthoritiesMapper getGrantedAuthoritiesMapper() {
  108. private GrantedAuthoritiesMapper getGrantedAuthoritiesMapperBean() {
  109. private OAuth2UserService<OidcUserRequest, OidcUser> getOidcUserService() {
  110. //返回OidcUserService对象
  111. if (this.userInfoEndpointConfig.oidcUserService != null) {
  112. return this.userInfoEndpointConfig.oidcUserService;
  113. } else {
  114. ResolvableType type = ResolvableType.forClassWithGenerics(OAuth2UserService.class, new Class[]{OidcUserRequest.class, OidcUser.class});
  115. OAuth2UserService<OidcUserRequest, OidcUser> bean = (OAuth2UserService)this.getBeanOrNull(type);
  116. return (OAuth2UserService)(bean == null ? new OidcUserService() : bean);
  117. }
  118. }
  119. private OAuth2UserService<OAuth2UserRequest, OAuth2User> getOAuth2UserService() {
  120. if (this.userInfoEndpointConfig.userService != null) {
  121. //如果设置了userService,直接返回userService对象
  122. return this.userInfoEndpointConfig.userService;
  123. } else {
  124. ResolvableType type = ResolvableType.forClassWithGenerics(OAuth2UserService.class, new Class[]{OAuth2UserRequest.class, OAuth2User.class});
  125. OAuth2UserService<OAuth2UserRequest, OAuth2User> bean = (OAuth2UserService)this.getBeanOrNull(type);
  126. if (bean == null) {
  127. if (!this.userInfoEndpointConfig.customUserTypes.isEmpty()) {
  128. //如果userInfoEndpointConfig中customUserTypes不为空,返回代理对象DelegatingOAuth2UserService
  129. List<OAuth2UserService<OAuth2UserRequest, OAuth2User>> userServices = new ArrayList();
  130. userServices.add(new CustomUserTypesOAuth2UserService(this.userInfoEndpointConfig.customUserTypes));
  131. userServices.add(new DefaultOAuth2UserService());
  132. return new DelegatingOAuth2UserService(userServices);
  133. } else {
  134. //如果为空,直接返回DefaultOAuth2UserService对象
  135. return new DefaultOAuth2UserService();
  136. }
  137. } else {
  138. return bean;
  139. }
  140. }
  141. }
  142. private <T> T getBeanOrNull(ResolvableType type) {
  143. private void initDefaultLoginFilter(B http) { //生成默认的登陆页面
  144. DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = (DefaultLoginPageGeneratingFilter)http.getSharedObject(DefaultLoginPageGeneratingFilter.class);
  145. if (loginPageGeneratingFilter != null && !this.isCustomLoginPage()) {
  146. loginPageGeneratingFilter.setOauth2LoginEnabled(true);
  147. loginPageGeneratingFilter.setOauth2AuthenticationUrlToClientName(this.getLoginLinks());
  148. loginPageGeneratingFilter.setLoginPageUrl(this.getLoginPage());
  149. loginPageGeneratingFilter.setFailureUrl(this.getFailureUrl());
  150. }
  151. }
  152. private Map<String, String> getLoginLinks() { //授权认证的uri地址
  153. Iterable<ClientRegistration> clientRegistrations = null;
  154. ClientRegistrationRepository clientRegistrationRepository = OAuth2ClientConfigurerUtils.getClientRegistrationRepository((HttpSecurityBuilder)this.getBuilder());
  155. ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository).as(Iterable.class);
  156. if (type != ResolvableType.NONE && ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) {
  157. clientRegistrations = (Iterable)clientRegistrationRepository;
  158. }
  159. if (clientRegistrations == null) {
  160. return Collections.emptyMap();
  161. } else {
  162. String authorizationRequestBaseUri = this.authorizationEndpointConfig.authorizationRequestBaseUri != null ? this.authorizationEndpointConfig.authorizationRequestBaseUri : "/oauth2/authorization";
  163. Map<String, String> loginUrlToClientName = new HashMap();
  164. clientRegistrations.forEach((registration) -> {
  165. String var10000 = (String)loginUrlToClientName.put(authorizationRequestBaseUri + "/" + registration.getRegistrationId(), registration.getClientName());
  166. }); //授权请求默认为:/oauth2/authorization + registration.getRegistrationId()
  167. return loginUrlToClientName;
  168. }
  169. }
  170. private AuthenticationEntryPoint getLoginEntryPoint(B http, String providerLoginPage) {
  171. ***************
  172. 内部类:OAuth2LoginConfigurer.OidcAuthenticationRequestChecker
  173. private static class OidcAuthenticationRequestChecker implements AuthenticationProvider {
  174. private OidcAuthenticationRequestChecker() {
  175. }
  176. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  177. public boolean supports(Class<?> authentication) {
  178. ***************
  179. 内部类:OAuth2LoginConfigurer.UserInfoEndpointConfig
  180. public class UserInfoEndpointConfig {
  181. private OAuth2UserService<OAuth2UserRequest, OAuth2User> userService;
  182. private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;
  183. private Map<String, Class<? extends OAuth2User>> customUserTypes;
  184. private UserInfoEndpointConfig() {
  185. this.customUserTypes = new HashMap();
  186. }
  187. public OAuth2LoginConfigurer<B>.UserInfoEndpointConfig userService(OAuth2UserService<OAuth2UserRequest, OAuth2User> userService) {
  188. //设置OAuth2UserService,通过OAuth2UserRequest请求获取user
  189. public OAuth2LoginConfigurer<B>.UserInfoEndpointConfig oidcUserService(OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService) {
  190. //设置OAuth2UserService,通过OidcUserRequest请求获取OidcUser
  191. public OAuth2LoginConfigurer<B>.UserInfoEndpointConfig customUserType(Class<? extends OAuth2User> customUserType, String clientRegistrationId) {
  192. //设置用户类型OAuth2User
  193. public OAuth2LoginConfigurer<B>.UserInfoEndpointConfig userAuthoritiesMapper(GrantedAuthoritiesMapper userAuthoritiesMapper) {
  194. //设置用户权限
  195. public OAuth2LoginConfigurer<B> and() {
  196. ***************
  197. 内部类:OAuth2LoginConfigurer.RedirectionEndpointConfig
  198. public class RedirectionEndpointConfig {
  199. private String authorizationResponseBaseUri;
  200. private RedirectionEndpointConfig() {
  201. }
  202. public OAuth2LoginConfigurer<B>.RedirectionEndpointConfig baseUri(String authorizationResponseBaseUri) {
  203. //获取授权码code后,回调的baseUri
  204. public OAuth2LoginConfigurer<B> and() {
  205. ***************
  206. 内部类:OAuth2LoginConfigurer.TokenEndpointConfig
  207. public class TokenEndpointConfig {
  208. private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
  209. private TokenEndpointConfig() {
  210. }
  211. public OAuth2LoginConfigurer<B>.TokenEndpointConfig accessTokenResponseClient(OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient) {
  212. //设置OAuth2AccessTokenResponseClient,通过该客户端获取token
  213. public OAuth2LoginConfigurer<B> and() {
  214. ***************
  215. 内部类:OAuth2LoginConfigurer.AuthorizationEndpointConfig
  216. public class AuthorizationEndpointConfig {
  217. private String authorizationRequestBaseUri;
  218. private OAuth2AuthorizationRequestResolver authorizationRequestResolver;
  219. private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
  220. private AuthorizationEndpointConfig() {
  221. }
  222. public OAuth2LoginConfigurer<B>.AuthorizationEndpointConfig baseUri(String authorizationRequestBaseUri) {
  223. //设置授权请求的baseUri,如果不设置,默认为:/oauth2/authorization
  224. public OAuth2LoginConfigurer<B>.AuthorizationEndpointConfig authorizationRequestResolver(OAuth2AuthorizationRequestResolver authorizationRequestResolver) {
  225. //设置授权请求解析类,将HttpServletRequest转换为OAuth2AuthorizationRequest
  226. public OAuth2LoginConfigurer<B>.AuthorizationEndpointConfig authorizationRequestRepository(AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) {
  227. //设置授权请求操作类,加载、保存、删除授权请求
  228. public OAuth2LoginConfigurer<B> and() {

 

UserService:加载用户

  1. @FunctionalInterface
  2. public interface OAuth2UserService<R extends OAuth2UserRequest, U extends OAuth2User> {
  3. U loadUser(R var1) throws OAuth2AuthenticationException;
  4. }

 

DefaultOAuth2UserService:默认的用户加载类

  1. public class DefaultOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
  2. private static final String MISSING_USER_INFO_URI_ERROR_CODE = "missing_user_info_uri";
  3. private static final String MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE = "missing_user_name_attribute";
  4. private static final String INVALID_USER_INFO_RESPONSE_ERROR_CODE = "invalid_user_info_response";
  5. private static final ParameterizedTypeReference<Map<String, Object>> PARAMETERIZED_RESPONSE_TYPE = new ParameterizedTypeReference<Map<String, Object>>() {
  6. };
  7. private Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter = new OAuth2UserRequestEntityConverter();
  8. private RestOperations restOperations;
  9. public DefaultOAuth2UserService() {
  10. RestTemplate restTemplate = new RestTemplate();
  11. restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
  12. this.restOperations = restTemplate;
  13. }
  14. public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
  15. Assert.notNull(userRequest, "userRequest cannot be null");
  16. if (!StringUtils.hasText(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri())) {
  17. OAuth2Error oauth2Error = new OAuth2Error("missing_user_info_uri", "Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), (String)null);
  18. throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
  19. } else {
  20. String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
  21. if (!StringUtils.hasText(userNameAttributeName)) {
  22. OAuth2Error oauth2Error = new OAuth2Error("missing_user_name_attribute", "Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), (String)null);
  23. throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
  24. } else {
  25. RequestEntity request = (RequestEntity)this.requestEntityConverter.convert(userRequest);
  26. ResponseEntity response;
  27. OAuth2Error oauth2Error;
  28. try {
  29. response = this.restOperations.exchange(request, PARAMETERIZED_RESPONSE_TYPE);
  30. } catch (OAuth2AuthorizationException var10) {
  31. oauth2Error = var10.getError();
  32. StringBuilder errorDetails = new StringBuilder();
  33. errorDetails.append("Error details: [");
  34. errorDetails.append("UserInfo Uri: ").append(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri());
  35. errorDetails.append(", Error Code: ").append(oauth2Error.getErrorCode());
  36. if (oauth2Error.getDescription() != null) {
  37. errorDetails.append(", Error Description: ").append(oauth2Error.getDescription());
  38. }
  39. errorDetails.append("]");
  40. oauth2Error = new OAuth2Error("invalid_user_info_response", "An error occurred while attempting to retrieve the UserInfo Resource: " + errorDetails.toString(), (String)null);
  41. throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), var10);
  42. } catch (RestClientException var11) {
  43. oauth2Error = new OAuth2Error("invalid_user_info_response", "An error occurred while attempting to retrieve the UserInfo Resource: " + var11.getMessage(), (String)null);
  44. throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), var11);
  45. }
  46. Map<String, Object> userAttributes = (Map)response.getBody();
  47. Set<GrantedAuthority> authorities = new LinkedHashSet();
  48. authorities.add(new OAuth2UserAuthority(userAttributes)); //给用户添加默认的权限:ROLE_USER
  49. OAuth2AccessToken token = userRequest.getAccessToken();
  50. Iterator var8 = token.getScopes().iterator();
  51. while(var8.hasNext()) {
  52. String authority = (String)var8.next();
  53. authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
  54. }//读取OAuth2AccessToken中的scopes,添加对应的权限,前缀为:SCOPE_
  55. return new DefaultOAuth2User(authorities, userAttributes, userNameAttributeName);
  56. }
  57. }
  58. }
  59. public final void setRequestEntityConverter(Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter) {
  60. Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null");
  61. this.requestEntityConverter = requestEntityConverter;
  62. }
  63. public final void setRestOperations(RestOperations restOperations) {
  64. Assert.notNull(restOperations, "restOperations cannot be null");
  65. this.restOperations = restOperations;
  66. }
  67. }

 

OAuth2UserAuthority:用户权限类

  1. public class OAuth2UserAuthority implements GrantedAuthority {
  2. private static final long serialVersionUID = 520L;
  3. private final String authority;
  4. private final Map<String, Object> attributes;
  5. public OAuth2UserAuthority(Map<String, Object> attributes) {
  6. this("ROLE_USER", attributes);
  7. }
  8. public OAuth2UserAuthority(String authority, Map<String, Object> attributes) {
  9. Assert.hasText(authority, "authority cannot be empty");
  10. Assert.notEmpty(attributes, "attributes cannot be empty");
  11. this.authority = authority;
  12. this.attributes = Collections.unmodifiableMap(new LinkedHashMap(attributes));
  13. }
  14. public String getAuthority() {
  15. public Map<String, Object> getAttributes() {
  16. public boolean equals(Object obj) {
  17. public int hashCode() {
  18. public String toString() {
  19. return this.getAuthority();
  20. }
  21. }

 

DefaultOAuth2User:默认用户类

  1. public class DefaultOAuth2User implements OAuth2User, Serializable {
  2. private static final long serialVersionUID = 520L;
  3. private final Set<GrantedAuthority> authorities;
  4. private final Map<String, Object> attributes;
  5. private final String nameAttributeKey;
  6. public DefaultOAuth2User(Collection<? extends GrantedAuthority> authorities, Map<String, Object> attributes, String nameAttributeKey) {
  7. Assert.notEmpty(authorities, "authorities cannot be empty");
  8. Assert.notEmpty(attributes, "attributes cannot be empty");
  9. Assert.hasText(nameAttributeKey, "nameAttributeKey cannot be empty");
  10. if (!attributes.containsKey(nameAttributeKey)) {
  11. throw new IllegalArgumentException("Missing attribute '" + nameAttributeKey + "' in attributes");
  12. } else {
  13. this.authorities = Collections.unmodifiableSet(new LinkedHashSet(this.sortAuthorities(authorities)));
  14. this.attributes = Collections.unmodifiableMap(new LinkedHashMap(attributes));
  15. this.nameAttributeKey = nameAttributeKey;
  16. }
  17. }
  18. public String getName() {
  19. return this.getAttribute(this.nameAttributeKey).toString();
  20. }
  21. public Collection<? extends GrantedAuthority> getAuthorities() {
  22. public Map<String, Object> getAttributes() {
  23. private Set<GrantedAuthority> sortAuthorities(Collection<? extends GrantedAuthority> authorities) {
  24. public boolean equals(Object obj) {
  25. public int hashCode() {
  26. public String toString() {
  27. StringBuilder sb = new StringBuilder();
  28. sb.append("Name: [");
  29. sb.append(this.getName());
  30. sb.append("], Granted Authorities: [");
  31. sb.append(this.getAuthorities());
  32. sb.append("], User Attributes: [");
  33. sb.append(this.getAttributes());
  34. sb.append("]");
  35. return sb.toString();
  36. }
  37. }

 

 

**************************

相关过滤器

 

DefaultLoginPageGeneratingFilter:生成默认的登陆页面

  1. public class DefaultLoginPageGeneratingFilter extends GenericFilterBean {
  2. public static final String DEFAULT_LOGIN_PAGE_URL = "/login";
  3. public static final String ERROR_PARAMETER_NAME = "error";
  4. private String loginPageUrl;
  5. private String logoutSuccessUrl;
  6. private String failureUrl;
  7. private boolean formLoginEnabled;
  8. private boolean openIdEnabled;
  9. private boolean oauth2LoginEnabled;
  10. private boolean saml2LoginEnabled;
  11. private String authenticationUrl;
  12. private String usernameParameter;
  13. private String passwordParameter;
  14. private String rememberMeParameter;
  15. private String openIDauthenticationUrl;
  16. private String openIDusernameParameter;
  17. private String openIDrememberMeParameter;
  18. private Map<String, String> oauth2AuthenticationUrlToClientName;
  19. private Map<String, String> saml2AuthenticationUrlToProviderName;
  20. private Function<HttpServletRequest, Map<String, String>> resolveHiddenInputs = (request) -> {
  21. return Collections.emptyMap();
  22. };
  23. public DefaultLoginPageGeneratingFilter() {
  24. public DefaultLoginPageGeneratingFilter(AbstractAuthenticationProcessingFilter filter) {
  25. public DefaultLoginPageGeneratingFilter(UsernamePasswordAuthenticationFilter authFilter, AbstractAuthenticationProcessingFilter openIDFilter) {
  26. private void init(UsernamePasswordAuthenticationFilter authFilter, AbstractAuthenticationProcessingFilter openIDFilter) {
  27. this.loginPageUrl = "/login";
  28. this.logoutSuccessUrl = "/login?logout";
  29. this.failureUrl = "/login?error";
  30. if (authFilter != null) {
  31. this.formLoginEnabled = true;
  32. this.usernameParameter = authFilter.getUsernameParameter();
  33. this.passwordParameter = authFilter.getPasswordParameter();
  34. if (authFilter.getRememberMeServices() instanceof AbstractRememberMeServices) {
  35. this.rememberMeParameter = ((AbstractRememberMeServices)authFilter.getRememberMeServices()).getParameter();
  36. }
  37. }
  38. if (openIDFilter != null) {
  39. this.openIdEnabled = true;
  40. this.openIDusernameParameter = "openid_identifier";
  41. if (openIDFilter.getRememberMeServices() instanceof AbstractRememberMeServices) {
  42. this.openIDrememberMeParameter = ((AbstractRememberMeServices)openIDFilter.getRememberMeServices()).getParameter();
  43. }
  44. }
  45. }

 

OAuth2AuthorizationRequestRedirectFilter:授权请求跳转过滤器

  1. public class OAuth2AuthorizationRequestRedirectFilter extends OncePerRequestFilter {
  2. public static final String DEFAULT_AUTHORIZATION_REQUEST_BASE_URI = "/oauth2/authorization";
  3. private final ThrowableAnalyzer throwableAnalyzer;
  4. private final RedirectStrategy authorizationRedirectStrategy;
  5. private OAuth2AuthorizationRequestResolver authorizationRequestResolver;
  6. private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
  7. private RequestCache requestCache;
  8. public OAuth2AuthorizationRequestRedirectFilter(ClientRegistrationRepository clientRegistrationRepository) {
  9. this(clientRegistrationRepository, "/oauth2/authorization");
  10. }
  11. public OAuth2AuthorizationRequestRedirectFilter(ClientRegistrationRepository clientRegistrationRepository, String authorizationRequestBaseUri) {
  12. public OAuth2AuthorizationRequestRedirectFilter(OAuth2AuthorizationRequestResolver authorizationRequestResolver) {

 

OAuth2LoginAuthenticationFilter:获取授权码code后的认证过滤器

  1. public class OAuth2LoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
  2. public static final String DEFAULT_FILTER_PROCESSES_URI = "/login/oauth2/code/*";
  3. private static final String AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE = "authorization_request_not_found";
  4. private static final String CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE = "client_registration_not_found";
  5. private ClientRegistrationRepository clientRegistrationRepository;
  6. private OAuth2AuthorizedClientRepository authorizedClientRepository;
  7. private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
  8. public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientService authorizedClientService) {
  9. this(clientRegistrationRepository, authorizedClientService, "/login/oauth2/code/*");
  10. }
  11. public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientService authorizedClientService, String filterProcessesUrl) {
  12. public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientRepository authorizedClientRepository, String filterProcessesUrl) {

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/224578
推荐阅读
相关标签
  

闽ICP备14008679号