From 3ca53ad82b5e41ea0669ac9e791a756b76b03ee0 Mon Sep 17 00:00:00 2001 From: "shengzhaoli.shengz" Date: Sun, 21 Nov 2021 23:44:00 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8D=87=E7=BA=A7spring=20security=20oauth2?= =?UTF-8?q?=E4=B8=BA=20spring-security-oauth2-authorization-server?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + others/database/oauth.ddl | 174 +++++--- others/reference-v2.1.1.md | 7 + pom.xml | 29 +- .../config/JWTTokenStoreConfiguration.java | 85 ++-- .../config/JdbcTokenStoreConfiguration.java | 47 +- .../OAuth2MethodSecurityConfiguration.java | 11 +- .../sos/config/OAuth2ServerConfiguration.java | 418 +++++++++++------- .../oauth/CustomJdbcClientDetailsService.java | 14 +- .../sos/domain/shared/GuidGenerator.java | 8 +- ...ntCredentialsInlineAccessTokenInvoker.java | 15 +- .../business/InlineAccessTokenInvoker.java | 169 ++++--- .../PasswordInlineAccessTokenInvoker.java | 17 +- .../RefreshTokenInlineAccessTokenInvoker.java | 15 +- .../sos/service/dto/AccessTokenDto.java | 32 +- .../sos/service/impl/UserServiceImpl.java | 43 +- .../sos/web/context/SOSContextHolder.java | 9 +- .../web/controller/OAuthRestController.java | 332 +++++++------- .../web/oauth/OauthUserApprovalHandler.java | 34 +- .../JWTTokenStoreConfigurationTest.java | 24 +- ...edentialsInlineAccessTokenInvokerTest.java | 16 +- .../PasswordInlineAccessTokenInvokerTest.java | 14 +- ...reshTokenInlineAccessTokenInvokerTest.java | 26 +- 23 files changed, 828 insertions(+), 713 deletions(-) create mode 100644 others/reference-v2.1.1.md diff --git a/README.md b/README.md index ff8786c..7b247b9 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Base on Spring-Boot
  • JDK (1.8.0_40)
  • Servlet (3.1.0)
  • Spring Boot(2.4.2)
  • +
  • spring-security-oauth2-authorization-server(0.2.0)
  • 技术视频

    http://list.youku.com/albumlist/show/id_51900110.html @@ -172,6 +173,7 @@ Base on Spring-Boot

    1. 升级spring-boot v2.4.2,改变可直接运行 SpringOauthServerApplication.java

    2. +
    3. 升级spring security oauth2为 spring-security-oauth2-authorization-server


    diff --git a/others/database/oauth.ddl b/others/database/oauth.ddl index 397a0e2..6206ec3 100644 --- a/others/database/oauth.ddl +++ b/others/database/oauth.ddl @@ -2,65 +2,123 @@ -- Oauth sql -- MYSQL -- -Drop table if exists oauth_client_details; -create table oauth_client_details ( - client_id VARCHAR(255) PRIMARY KEY, - resource_ids VARCHAR(255), - client_secret VARCHAR(255), - scope VARCHAR(255), - authorized_grant_types VARCHAR(255), - web_server_redirect_uri VARCHAR(255), - authorities VARCHAR(255), - access_token_validity INTEGER, - refresh_token_validity INTEGER, - additional_information TEXT, - create_time timestamp default now(), - archived tinyint(1) default '0', - trusted tinyint(1) default '0', - autoapprove VARCHAR (255) default 'false' -) ENGINE=InnoDB DEFAULT CHARSET=utf8; +-- oauth2_registered_client v2.1.1 +-- from oauth2-registered-client-schema.sql +CREATE TABLE oauth2_registered_client ( + id varchar(100) NOT NULL, + client_id varchar(100) NOT NULL, + client_id_issued_at timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL, + client_secret varchar(200) DEFAULT NULL, + client_secret_expires_at timestamp DEFAULT NULL, + client_name varchar(200) NOT NULL, + client_authentication_methods varchar(1000) NOT NULL, + authorization_grant_types varchar(1000) NOT NULL, + redirect_uris varchar(1000) DEFAULT NULL, + scopes varchar(1000) NOT NULL, + client_settings varchar(2000) NOT NULL, + token_settings varchar(2000) NOT NULL, + PRIMARY KEY (id) +); + +-- oauth2_authorization v2.1.1 +-- from oauth2-authorization-schema.sql +CREATE TABLE oauth2_authorization ( + id varchar(100) NOT NULL, + registered_client_id varchar(100) NOT NULL, + principal_name varchar(200) NOT NULL, + authorization_grant_type varchar(100) NOT NULL, + attributes varchar(4000) DEFAULT NULL, + state varchar(500) DEFAULT NULL, + authorization_code_value blob DEFAULT NULL, + authorization_code_issued_at timestamp DEFAULT NULL, + authorization_code_expires_at timestamp DEFAULT NULL, + authorization_code_metadata varchar(2000) DEFAULT NULL, + access_token_value blob DEFAULT NULL, + access_token_issued_at timestamp DEFAULT NULL, + access_token_expires_at timestamp DEFAULT NULL, + access_token_metadata varchar(2000) DEFAULT NULL, + access_token_type varchar(100) DEFAULT NULL, + access_token_scopes varchar(1000) DEFAULT NULL, + oidc_id_token_value blob DEFAULT NULL, + oidc_id_token_issued_at timestamp DEFAULT NULL, + oidc_id_token_expires_at timestamp DEFAULT NULL, + oidc_id_token_metadata varchar(2000) DEFAULT NULL, + refresh_token_value blob DEFAULT NULL, + refresh_token_issued_at timestamp DEFAULT NULL, + refresh_token_expires_at timestamp DEFAULT NULL, + refresh_token_metadata varchar(2000) DEFAULT NULL, + PRIMARY KEY (id) +); + +-- oauth2_authorization_consent v2.1.1 +-- from oauth2-authorization-consent-schema.sql +CREATE TABLE oauth2_authorization_consent ( + registered_client_id varchar(100) NOT NULL, + principal_name varchar(200) NOT NULL, + authorities varchar(1000) NOT NULL, + PRIMARY KEY (registered_client_id, principal_name) +); -Drop table if exists oauth_access_token; -create table oauth_access_token ( - create_time timestamp default now(), - token_id VARCHAR(255), - token BLOB, - authentication_id VARCHAR(255) UNIQUE, - user_name VARCHAR(255), - client_id VARCHAR(255), - authentication BLOB, - refresh_token VARCHAR(255) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - -Drop table if exists oauth_refresh_token; -create table oauth_refresh_token ( - create_time timestamp default now(), - token_id VARCHAR(255), - token BLOB, - authentication BLOB -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - -Drop table if exists oauth_code; -create table oauth_code ( - create_time timestamp default now(), - code VARCHAR(255), - authentication BLOB -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - - --- Add indexes -create index token_id_index on oauth_access_token (token_id); -create index authentication_id_index on oauth_access_token (authentication_id); -create index user_name_index on oauth_access_token (user_name); -create index client_id_index on oauth_access_token (client_id); -create index refresh_token_index on oauth_access_token (refresh_token); - -create index token_id_index on oauth_refresh_token (token_id); - -create index code_index on oauth_code (code); +# Drop table if exists oauth_client_details; +# create table oauth_client_details ( +# client_id VARCHAR(255) PRIMARY KEY, +# resource_ids VARCHAR(255), +# client_secret VARCHAR(255), +# scope VARCHAR(255), +# authorized_grant_types VARCHAR(255), +# web_server_redirect_uri VARCHAR(255), +# authorities VARCHAR(255), +# access_token_validity INTEGER, +# refresh_token_validity INTEGER, +# additional_information TEXT, +# create_time timestamp default now(), +# archived tinyint(1) default '0', +# trusted tinyint(1) default '0', +# autoapprove VARCHAR (255) default 'false' +# ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +# +# +# Drop table if exists oauth_access_token; +# create table oauth_access_token ( +# create_time timestamp default now(), +# token_id VARCHAR(255), +# token BLOB, +# authentication_id VARCHAR(255) UNIQUE, +# user_name VARCHAR(255), +# client_id VARCHAR(255), +# authentication BLOB, +# refresh_token VARCHAR(255) +# ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +# +# +# Drop table if exists oauth_refresh_token; +# create table oauth_refresh_token ( +# create_time timestamp default now(), +# token_id VARCHAR(255), +# token BLOB, +# authentication BLOB +# ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +# +# +# Drop table if exists oauth_code; +# create table oauth_code ( +# create_time timestamp default now(), +# code VARCHAR(255), +# authentication BLOB +# ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +# +# +# +# -- Add indexes +# create index token_id_index on oauth_access_token (token_id); +# create index authentication_id_index on oauth_access_token (authentication_id); +# create index user_name_index on oauth_access_token (user_name); +# create index client_id_index on oauth_access_token (client_id); +# create index refresh_token_index on oauth_access_token (refresh_token); +# +# create index token_id_index on oauth_refresh_token (token_id); +# +# create index code_index on oauth_code (code); diff --git a/others/reference-v2.1.1.md b/others/reference-v2.1.1.md new file mode 100644 index 0000000..7344807 --- /dev/null +++ b/others/reference-v2.1.1.md @@ -0,0 +1,7 @@ + + +## 参考文章 +> 最后更新:2021-11-21 + +- https://blog.csdn.net/qq_16063307/article/details/113972486 +- https://mp.weixin.qq.com/s?__biz=MzAxODcyNjEzNQ==&mid=2247545942&idx=2&sn=5061bb4243a87e1aed45fa4850879953&chksm=9bd399ceaca410d8a297a83c3c6606ba9e427069f4d91193828e3bf364c62f45b0248606796f#rd \ No newline at end of file diff --git a/pom.xml b/pom.xml index e356f88..90666d5 100644 --- a/pom.xml +++ b/pom.xml @@ -23,8 +23,8 @@ UTF-8 1.8 - 2.3.8.RELEASE - 1.1.1.RELEASE + + false @@ -48,18 +48,25 @@ spring-boot-starter-jdbc - - - org.springframework.security.oauth - spring-security-oauth2 - ${spring.security.oauth.version} - + + + + + + - + + + + + + + + org.springframework.security - spring-security-jwt - ${spring.security.jwt.version} + spring-security-oauth2-authorization-server + 0.2.0 diff --git a/src/main/java/com/monkeyk/sos/config/JWTTokenStoreConfiguration.java b/src/main/java/com/monkeyk/sos/config/JWTTokenStoreConfiguration.java index 679c02b..d45db5a 100644 --- a/src/main/java/com/monkeyk/sos/config/JWTTokenStoreConfiguration.java +++ b/src/main/java/com/monkeyk/sos/config/JWTTokenStoreConfiguration.java @@ -1,18 +1,9 @@ package com.monkeyk.sos.config; -import com.monkeyk.sos.service.UserService; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.security.oauth2.provider.ClientDetailsService; -import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter; -import org.springframework.security.oauth2.provider.token.DefaultTokenServices; -import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; -import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; + /** * 2020/6/9 @@ -41,45 +32,45 @@ public class JWTTokenStoreConfiguration { private String jwtKey; - @Bean - public JwtAccessTokenConverter accessTokenConverter(UserService userService) { - JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter(); +// @Bean +// public JwtAccessTokenConverter accessTokenConverter(UserService userService) { +// JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter(); +// +// DefaultAccessTokenConverter tokenConverter = new DefaultAccessTokenConverter(); +// DefaultUserAuthenticationConverter userAuthenticationConverter = new DefaultUserAuthenticationConverter(); +// userAuthenticationConverter.setUserDetailsService(userService); +//// userAuthenticationConverter.setDefaultAuthorities(new String[]{"USER"}); +// tokenConverter.setUserTokenConverter(userAuthenticationConverter); +// +// tokenConverter.setIncludeGrantType(true); +//// tokenConverter.setScopeAttribute("_scope"); +// jwtAccessTokenConverter.setAccessTokenConverter(tokenConverter); +// +// jwtAccessTokenConverter.setSigningKey(this.jwtKey); +// return jwtAccessTokenConverter; +// } - DefaultAccessTokenConverter tokenConverter = new DefaultAccessTokenConverter(); - DefaultUserAuthenticationConverter userAuthenticationConverter = new DefaultUserAuthenticationConverter(); - userAuthenticationConverter.setUserDetailsService(userService); -// userAuthenticationConverter.setDefaultAuthorities(new String[]{"USER"}); - tokenConverter.setUserTokenConverter(userAuthenticationConverter); - - tokenConverter.setIncludeGrantType(true); -// tokenConverter.setScopeAttribute("_scope"); - jwtAccessTokenConverter.setAccessTokenConverter(tokenConverter); - - jwtAccessTokenConverter.setSigningKey(this.jwtKey); - return jwtAccessTokenConverter; - } - - /** - * JWT TokenStore - * - * @since 2.1.0 - */ - @Bean - public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) { - return new JwtTokenStore(jwtAccessTokenConverter); - } +// /** +// * JWT TokenStore +// * +// * @since 2.1.0 +// */ +// @Bean +// public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) { +// return new JwtTokenStore(jwtAccessTokenConverter); +// } - @Bean - @Primary - public DefaultTokenServices tokenServices(TokenStore tokenStore, JwtAccessTokenConverter tokenEnhancer, ClientDetailsService clientDetailsService) { - DefaultTokenServices tokenServices = new DefaultTokenServices(); - tokenServices.setTokenStore(tokenStore); - tokenServices.setClientDetailsService(clientDetailsService); - //support refresh token - tokenServices.setSupportRefreshToken(true); - tokenServices.setTokenEnhancer(tokenEnhancer); - return tokenServices; - } +// @Bean +// @Primary +// public DefaultTokenServices tokenServices(TokenStore tokenStore, JwtAccessTokenConverter tokenEnhancer, ClientDetailsService clientDetailsService) { +// DefaultTokenServices tokenServices = new DefaultTokenServices(); +// tokenServices.setTokenStore(tokenStore); +// tokenServices.setClientDetailsService(clientDetailsService); +// //support refresh token +// tokenServices.setSupportRefreshToken(true); +// tokenServices.setTokenEnhancer(tokenEnhancer); +// return tokenServices; +// } } diff --git a/src/main/java/com/monkeyk/sos/config/JdbcTokenStoreConfiguration.java b/src/main/java/com/monkeyk/sos/config/JdbcTokenStoreConfiguration.java index 0822a07..e8e02bf 100644 --- a/src/main/java/com/monkeyk/sos/config/JdbcTokenStoreConfiguration.java +++ b/src/main/java/com/monkeyk/sos/config/JdbcTokenStoreConfiguration.java @@ -1,15 +1,8 @@ package com.monkeyk.sos.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.security.oauth2.provider.ClientDetailsService; -import org.springframework.security.oauth2.provider.token.DefaultTokenServices; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; -import javax.sql.DataSource; /** * 2020/6/9 @@ -26,25 +19,25 @@ import javax.sql.DataSource; @ConditionalOnProperty(name = "sos.token.store", havingValue = "jdbc", matchIfMissing = true) public class JdbcTokenStoreConfiguration { - - /** - * JDBC TokenStore - */ - @Bean - public TokenStore tokenStore(DataSource dataSource) { - return new JdbcTokenStore(dataSource); - } - - - @Bean - @Primary - public DefaultTokenServices tokenServices(TokenStore tokenStore, ClientDetailsService clientDetailsService) { - DefaultTokenServices tokenServices = new DefaultTokenServices(); - tokenServices.setTokenStore(tokenStore); - tokenServices.setClientDetailsService(clientDetailsService); - //support refresh token - tokenServices.setSupportRefreshToken(true); - return tokenServices; - } +// +// /** +// * JDBC TokenStore +// */ +// @Bean +// public TokenStore tokenStore(DataSource dataSource) { +// return new JdbcTokenStore(dataSource); +// } +// +// +// @Bean +// @Primary +// public DefaultTokenServices tokenServices(TokenStore tokenStore, ClientDetailsService clientDetailsService) { +// DefaultTokenServices tokenServices = new DefaultTokenServices(); +// tokenServices.setTokenStore(tokenStore); +// tokenServices.setClientDetailsService(clientDetailsService); +// //support refresh token +// tokenServices.setSupportRefreshToken(true); +// return tokenServices; +// } } diff --git a/src/main/java/com/monkeyk/sos/config/OAuth2MethodSecurityConfiguration.java b/src/main/java/com/monkeyk/sos/config/OAuth2MethodSecurityConfiguration.java index fa6c8c2..fa37955 100644 --- a/src/main/java/com/monkeyk/sos/config/OAuth2MethodSecurityConfiguration.java +++ b/src/main/java/com/monkeyk/sos/config/OAuth2MethodSecurityConfiguration.java @@ -1,10 +1,7 @@ package com.monkeyk.sos.config; -import org.springframework.context.annotation.Configuration; import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; -import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler; /** * 2018/3/22 @@ -12,15 +9,17 @@ import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecur * 此配置用于启用 #oauth2 表达式,如:#oauth2.hasScope('read') * * @author Shengzhao Li + * @deprecated use spring-security-authorization-server replaced from v2.1.1 */ -@Configuration -@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true) +//@Configuration +//@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true) public class OAuth2MethodSecurityConfiguration extends GlobalMethodSecurityConfiguration { @Override protected MethodSecurityExpressionHandler createExpressionHandler() { - return new OAuth2MethodSecurityExpressionHandler(); +// return new OAuth2MethodSecurityExpressionHandler(); + return super.createExpressionHandler(); } } diff --git a/src/main/java/com/monkeyk/sos/config/OAuth2ServerConfiguration.java b/src/main/java/com/monkeyk/sos/config/OAuth2ServerConfiguration.java index 76e10c2..7a8e311 100644 --- a/src/main/java/com/monkeyk/sos/config/OAuth2ServerConfiguration.java +++ b/src/main/java/com/monkeyk/sos/config/OAuth2ServerConfiguration.java @@ -1,33 +1,25 @@ package com.monkeyk.sos.config; -import com.monkeyk.sos.domain.oauth.CustomJdbcClientDetailsService; -import com.monkeyk.sos.service.OauthService; -import com.monkeyk.sos.service.UserService; -import com.monkeyk.sos.web.oauth.OauthUserApprovalHandler; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; +import com.nimbusds.jose.JOSEException; +import com.nimbusds.jose.jwk.Curve; +import com.nimbusds.jose.jwk.JWK; +import com.nimbusds.jose.jwk.JWKSet; +import com.nimbusds.jose.jwk.gen.ECKeyGenerator; +import com.nimbusds.jose.jwk.source.ImmutableJWKSet; +import com.nimbusds.jose.jwk.source.JWKSource; +import com.nimbusds.jose.proc.SecurityContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; -import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; -import org.springframework.security.oauth2.provider.ClientDetailsService; -import org.springframework.security.oauth2.provider.OAuth2RequestFactory; -import org.springframework.security.oauth2.provider.approval.UserApprovalHandler; -import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices; -import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices; -import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory; -import org.springframework.security.oauth2.provider.token.DefaultTokenServices; -import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.context.annotation.Import; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration; +import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationConsentService; +import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationService; +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService; +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; +import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository; +import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; import javax.sql.DataSource; @@ -40,6 +32,8 @@ import javax.sql.DataSource; * @author Shengzhao Li */ @Configuration +// import from v2.1.1 +@Import(OAuth2AuthorizationServerConfiguration.class) public class OAuth2ServerConfiguration { @@ -48,173 +42,253 @@ public class OAuth2ServerConfiguration { /** - * // unity resource - * UNITY 资源的访问权限配置 + * JdbcTemplate config + * + * @param dataSource DataSource + * @return JdbcTemplate + * @since 2.1.1 */ - @Configuration - @EnableResourceServer - protected static class UnityResourceServerConfiguration extends ResourceServerConfigurerAdapter { - - @Override - public void configure(ResourceServerSecurityConfigurer resources) { - resources.resourceId(RESOURCE_ID).stateless(false); - } - - @Override - public void configure(HttpSecurity http) throws Exception { - http - // Since we want the protected resources to be accessible in the UI as well we need - // session creation to be allowed (it's disabled by default in 2.0.6) - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) - .and() - // 所有以 /unity/ 开头的 URL属于此资源 - .requestMatchers().antMatchers("/unity/**") - .and() - .authorizeRequests() - .antMatchers("/unity/**").access("#oauth2.hasScope('read') and hasRole('UNITY')"); - - } - + @Bean + public JdbcTemplate jdbcTemplate(DataSource dataSource) { + return new JdbcTemplate(dataSource); } /** - * // mobile resource - * MOBILE 资源的访问权限配置 + * RegisteredClientRepository config + *

    + * SQL: oauth2-registered-client-schema.sql + * + * @param jdbcTemplate JdbcTemplate + * @return RegisteredClientRepository + * @since 2.1.1 */ - @Configuration - @EnableResourceServer - protected static class MobileResourceServerConfiguration extends ResourceServerConfigurerAdapter { - - @Override - public void configure(ResourceServerSecurityConfigurer resources) { - resources.resourceId(RESOURCE_ID).stateless(false); - } - - @Override - public void configure(HttpSecurity http) throws Exception { - http - // Since we want the protected resources to be accessible in the UI as well we need - // session creation to be allowed (it's disabled by default in 2.0.6) - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) - .and() - // 所有以 /m/ 开头的 URL属于此资源 - .requestMatchers().antMatchers("/m/**") - .and() - .authorizeRequests() - .antMatchers("/m/**").access("#oauth2.hasScope('read') and hasRole('MOBILE')"); - - } - + @Bean + public RegisteredClientRepository registeredClientRepository(JdbcTemplate jdbcTemplate) { + return new JdbcRegisteredClientRepository(jdbcTemplate); } - @Configuration - @EnableAuthorizationServer - protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { + + /** + * OAuth2AuthorizationService config + *

    + * SQL: oauth2-authorization-schema.sql + * + * @param jdbcTemplate JdbcTemplate + * @param registeredClientRepository RegisteredClientRepository + * @return OAuth2AuthorizationService + * @since 2.1.1 + */ + @Bean + public OAuth2AuthorizationService authorizationService(JdbcTemplate jdbcTemplate, RegisteredClientRepository registeredClientRepository) { + return new JdbcOAuth2AuthorizationService(jdbcTemplate, registeredClientRepository); + } - @Autowired - private TokenStore tokenStore; - - @Autowired - private DefaultTokenServices tokenServices; + /** + * OAuth2AuthorizationConsentService config + *

    + * SQL: oauth2-authorization-consent-schema.sql + * + * @param jdbcTemplate JdbcTemplate + * @param registeredClientRepository RegisteredClientRepository + * @return OAuth2AuthorizationConsentService + * @since 2.1.1 + */ + @Bean + public OAuth2AuthorizationConsentService authorizationConsentService(JdbcTemplate jdbcTemplate, RegisteredClientRepository registeredClientRepository) { + return new JdbcOAuth2AuthorizationConsentService(jdbcTemplate, registeredClientRepository); + } - @Autowired - private ClientDetailsService clientDetailsService; - - - @Autowired - private OauthService oauthService; - - - @Autowired - private AuthorizationCodeServices authorizationCodeServices; - - - @Autowired - private UserService userDetailsService; - - - @Autowired - @Qualifier("authenticationManagerBean") - private AuthenticationManager authenticationManager; - - - @Override - public void configure(ClientDetailsServiceConfigurer clients) throws Exception { - - clients.withClientDetails(clientDetailsService); - } + /** + * JWT生成与校验使用的 JWK + *

    + * 使用算法:EC, P_256 + * + * @return JWKSource + * @throws JOSEException e + * @since 2.1.1 + */ + @Bean + public JWKSource jwkSource() throws JOSEException { + ECKeyGenerator keyGenerator = new ECKeyGenerator(Curve.P_256); + keyGenerator.keyID(RESOURCE_ID); + JWK jwk = keyGenerator.generate(); + System.out.println("\n Use auto-generated jwk: " + jwk.toJSONString()); + JWKSet jwkSet = new JWKSet(jwk); + return new ImmutableJWKSet<>(jwkSet); + } +// /** +// * // unity resource +// * UNITY 资源的访问权限配置 +// */ +// @Configuration +// @EnableResourceServer +// protected static class UnityResourceServerConfiguration extends ResourceServerConfigurerAdapter { +// +// @Override +// public void configure(ResourceServerSecurityConfigurer resources) { +// resources.resourceId(RESOURCE_ID).stateless(false); +// } +// +// @Override +// public void configure(HttpSecurity http) throws Exception { +// http +// // Since we want the protected resources to be accessible in the UI as well we need +// // session creation to be allowed (it's disabled by default in 2.0.6) +// .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) +// .and() +// // 所有以 /unity/ 开头的 URL属于此资源 +// .requestMatchers().antMatchers("/unity/**") +// .and() +// .authorizeRequests() +// .antMatchers("/unity/**").access("#oauth2.hasScope('read') and hasRole('UNITY')"); +// +// } +// +// } +// +// +// /** +// * // mobile resource +// * MOBILE 资源的访问权限配置 +// */ +// @Configuration +// @EnableResourceServer +// protected static class MobileResourceServerConfiguration extends ResourceServerConfigurerAdapter { +// +// @Override +// public void configure(ResourceServerSecurityConfigurer resources) { +// resources.resourceId(RESOURCE_ID).stateless(false); +// } +// +// @Override +// public void configure(HttpSecurity http) throws Exception { +// http +// // Since we want the protected resources to be accessible in the UI as well we need +// // session creation to be allowed (it's disabled by default in 2.0.6) +// .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) +// .and() +// // 所有以 /m/ 开头的 URL属于此资源 +// .requestMatchers().antMatchers("/m/**") +// .and() +// .authorizeRequests() +// .antMatchers("/m/**").access("#oauth2.hasScope('read') and hasRole('MOBILE')"); +// +// } +// +// } +// +// @Configuration +// @EnableAuthorizationServer +// protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { +// +// +// @Autowired +// private TokenStore tokenStore; +// +// @Autowired +// private DefaultTokenServices tokenServices; +// +// +// @Autowired +// private ClientDetailsService clientDetailsService; +// +// +// @Autowired +// private OauthService oauthService; +// +// +// @Autowired +// private AuthorizationCodeServices authorizationCodeServices; +// +// +// @Autowired +// private UserService userDetailsService; +// +// +// @Autowired +// @Qualifier("authenticationManagerBean") +// private AuthenticationManager authenticationManager; +// +// +// @Override +// public void configure(ClientDetailsServiceConfigurer clients) throws Exception { +// +// clients.withClientDetails(clientDetailsService); +// } +// +// +//// /* +//// * JDBC TokenStore +//// */ +//// @Bean +//// public TokenStore tokenStore(DataSource dataSource) { +//// return new JdbcTokenStore(dataSource); +//// } +// // /* -// * JDBC TokenStore +// * Redis TokenStore (有Redis场景时使用) // */ +//// @Bean +//// public TokenStore tokenStore(RedisConnectionFactory connectionFactory) { +//// final RedisTokenStore redisTokenStore = new RedisTokenStore(connectionFactory); +//// //prefix +//// redisTokenStore.setPrefix(RESOURCE_ID); +//// return redisTokenStore; +//// } +// +// // @Bean -// public TokenStore tokenStore(DataSource dataSource) { -// return new JdbcTokenStore(dataSource); +// public ClientDetailsService clientDetailsService(DataSource dataSource) { +// return new CustomJdbcClientDetailsService(dataSource); // } - - /* - * Redis TokenStore (有Redis场景时使用) - */ +// +// // @Bean -// public TokenStore tokenStore(RedisConnectionFactory connectionFactory) { -// final RedisTokenStore redisTokenStore = new RedisTokenStore(connectionFactory); -// //prefix -// redisTokenStore.setPrefix(RESOURCE_ID); -// return redisTokenStore; +// public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) { +// return new JdbcAuthorizationCodeServices(dataSource); // } - - - @Bean - public ClientDetailsService clientDetailsService(DataSource dataSource) { - return new CustomJdbcClientDetailsService(dataSource); - } - - - @Bean - public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) { - return new JdbcAuthorizationCodeServices(dataSource); - } - - - @Override - public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { - endpoints.tokenServices(tokenServices) - .tokenStore(tokenStore) - .authorizationCodeServices(authorizationCodeServices) - .userDetailsService(userDetailsService) - .userApprovalHandler(userApprovalHandler()) - .authenticationManager(authenticationManager); - } - - @Override - public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { - // real 值可自定义 - oauthServer.realm("spring-oauth-server") - // 支持 client_credentials 的配置 - .allowFormAuthenticationForClients(); - } - - @Bean - public OAuth2RequestFactory oAuth2RequestFactory() { - return new DefaultOAuth2RequestFactory(clientDetailsService); - } - - - @Bean - public UserApprovalHandler userApprovalHandler() { - OauthUserApprovalHandler userApprovalHandler = new OauthUserApprovalHandler(); - userApprovalHandler.setOauthService(oauthService); - userApprovalHandler.setTokenStore(tokenStore); - userApprovalHandler.setClientDetailsService(this.clientDetailsService); - userApprovalHandler.setRequestFactory(oAuth2RequestFactory()); - return userApprovalHandler; - } - - } +// +// +// @Override +// public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { +// endpoints.tokenServices(tokenServices) +// .tokenStore(tokenStore) +// .authorizationCodeServices(authorizationCodeServices) +// .userDetailsService(userDetailsService) +// .userApprovalHandler(userApprovalHandler()) +// .authenticationManager(authenticationManager); +// } +// +// @Override +// public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { +// // real 值可自定义 +// oauthServer.realm("spring-oauth-server") +// // 支持 client_credentials 的配置 +// .allowFormAuthenticationForClients(); +// } +// +// @Bean +// public OAuth2RequestFactory oAuth2RequestFactory() { +// return new DefaultOAuth2RequestFactory(clientDetailsService); +// } +// +// +// @Bean +// public UserApprovalHandler userApprovalHandler() { +// OauthUserApprovalHandler userApprovalHandler = new OauthUserApprovalHandler(); +// userApprovalHandler.setOauthService(oauthService); +// userApprovalHandler.setTokenStore(tokenStore); +// userApprovalHandler.setClientDetailsService(this.clientDetailsService); +// userApprovalHandler.setRequestFactory(oAuth2RequestFactory()); +// return userApprovalHandler; +// } +// +// } } diff --git a/src/main/java/com/monkeyk/sos/domain/oauth/CustomJdbcClientDetailsService.java b/src/main/java/com/monkeyk/sos/domain/oauth/CustomJdbcClientDetailsService.java index a0cbc8c..3aaf071 100644 --- a/src/main/java/com/monkeyk/sos/domain/oauth/CustomJdbcClientDetailsService.java +++ b/src/main/java/com/monkeyk/sos/domain/oauth/CustomJdbcClientDetailsService.java @@ -1,6 +1,6 @@ package com.monkeyk.sos.domain.oauth; -import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; +//import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; import javax.sql.DataSource; @@ -8,8 +8,10 @@ import javax.sql.DataSource; * Add archived = 0 condition * * @author Shengzhao Li + * @deprecated use spring-security-oauth2-authorization-server replaced from v2.1.1 */ -public class CustomJdbcClientDetailsService extends JdbcClientDetailsService { +//public class CustomJdbcClientDetailsService extends JdbcClientDetailsService { +public class CustomJdbcClientDetailsService { /** * 扩展的查询SQL, @@ -20,10 +22,10 @@ public class CustomJdbcClientDetailsService extends JdbcClientDetailsService { "from oauth_client_details where client_id = ? and archived = 0 "; - public CustomJdbcClientDetailsService(DataSource dataSource) { - super(dataSource); - setSelectClientDetailsSql(SELECT_CLIENT_DETAILS_SQL); - } +// public CustomJdbcClientDetailsService(DataSource dataSource) { +// super(dataSource); +// setSelectClientDetailsSql(SELECT_CLIENT_DETAILS_SQL); +// } } \ No newline at end of file diff --git a/src/main/java/com/monkeyk/sos/domain/shared/GuidGenerator.java b/src/main/java/com/monkeyk/sos/domain/shared/GuidGenerator.java index 6c561f0..f219c3c 100644 --- a/src/main/java/com/monkeyk/sos/domain/shared/GuidGenerator.java +++ b/src/main/java/com/monkeyk/sos/domain/shared/GuidGenerator.java @@ -1,6 +1,8 @@ package com.monkeyk.sos.domain.shared; -import org.springframework.security.oauth2.common.util.RandomValueStringGenerator; +//import org.springframework.security.oauth2.common.util.RandomValueStringGenerator; + +import org.apache.commons.lang.RandomStringUtils; import java.util.UUID; @@ -10,7 +12,7 @@ import java.util.UUID; public abstract class GuidGenerator { - private static RandomValueStringGenerator defaultClientSecretGenerator = new RandomValueStringGenerator(32); +// private static RandomValueStringGenerator defaultClientSecretGenerator = new RandomValueStringGenerator(32); /** @@ -24,7 +26,7 @@ public abstract class GuidGenerator { } public static String generateClientSecret() { - return defaultClientSecretGenerator.generate(); + return RandomStringUtils.random(32, true, true); } } \ No newline at end of file diff --git a/src/main/java/com/monkeyk/sos/service/business/ClientCredentialsInlineAccessTokenInvoker.java b/src/main/java/com/monkeyk/sos/service/business/ClientCredentialsInlineAccessTokenInvoker.java index 8f26763..9b96f0a 100644 --- a/src/main/java/com/monkeyk/sos/service/business/ClientCredentialsInlineAccessTokenInvoker.java +++ b/src/main/java/com/monkeyk/sos/service/business/ClientCredentialsInlineAccessTokenInvoker.java @@ -1,8 +1,8 @@ package com.monkeyk.sos.service.business; -import org.springframework.security.oauth2.provider.OAuth2RequestFactory; -import org.springframework.security.oauth2.provider.TokenGranter; -import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter; +//import org.springframework.security.oauth2.provider.OAuth2RequestFactory; +//import org.springframework.security.oauth2.provider.TokenGranter; +//import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter; /** * 2019/7/5 @@ -12,6 +12,7 @@ import org.springframework.security.oauth2.provider.client.ClientCredentialsToke * * @author Shengzhao Li * @since 2.0.1 + * @deprecated use spring-security-oauth2-authorization-server replaced from v2.1.1 */ public class ClientCredentialsInlineAccessTokenInvoker extends InlineAccessTokenInvoker { @@ -19,10 +20,10 @@ public class ClientCredentialsInlineAccessTokenInvoker extends InlineAccessToken public ClientCredentialsInlineAccessTokenInvoker() { } - @Override - protected TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory) { - return new ClientCredentialsTokenGranter(this.tokenServices, this.clientDetailsService, oAuth2RequestFactory); - } +// @Override +// protected TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory) { +// return new ClientCredentialsTokenGranter(this.tokenServices, this.clientDetailsService, oAuth2RequestFactory); +// } } diff --git a/src/main/java/com/monkeyk/sos/service/business/InlineAccessTokenInvoker.java b/src/main/java/com/monkeyk/sos/service/business/InlineAccessTokenInvoker.java index a79a624..cf74cf0 100644 --- a/src/main/java/com/monkeyk/sos/service/business/InlineAccessTokenInvoker.java +++ b/src/main/java/com/monkeyk/sos/service/business/InlineAccessTokenInvoker.java @@ -7,24 +7,19 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.provider.*; -import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory; -import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; import org.springframework.util.Assert; import java.util.Map; -import static org.springframework.security.oauth2.common.util.OAuth2Utils.CLIENT_ID; -import static org.springframework.security.oauth2.common.util.OAuth2Utils.GRANT_TYPE; -import static org.springframework.security.oauth2.common.util.OAuth2Utils.SCOPE; + /** * 2019/7/5 * * @author Shengzhao Li - * @see org.springframework.security.oauth2.provider.endpoint.TokenEndpoint +// * @see org.springframework.security.oauth2.provider.endpoint.TokenEndpoint * @since 2.0.1 + * @deprecated use spring-security-oauth2-authorization-server replaced from v2.1.1 */ public abstract class InlineAccessTokenInvoker implements InitializingBean { @@ -34,9 +29,9 @@ public abstract class InlineAccessTokenInvoker implements InitializingBean { protected transient AuthenticationManager authenticationManager = SOSContextHolder.getBean(AuthenticationManager.class); - protected transient AuthorizationServerTokenServices tokenServices = SOSContextHolder.getBean(AuthorizationServerTokenServices.class); - ; - protected transient ClientDetailsService clientDetailsService = SOSContextHolder.getBean(ClientDetailsService.class); +// protected transient AuthorizationServerTokenServices tokenServices = SOSContextHolder.getBean(AuthorizationServerTokenServices.class); +// +// protected transient ClientDetailsService clientDetailsService = SOSContextHolder.getBean(ClientDetailsService.class); public InlineAccessTokenInvoker() { @@ -62,26 +57,27 @@ public abstract class InlineAccessTokenInvoker implements InitializingBean { String clientId = validateParams(params); - final ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); - if (clientDetails == null) { - LOG.warn("Not found ClientDetails by clientId: {}", clientId); - return null; - } +// final ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); +// if (clientDetails == null) { +// LOG.warn("Not found ClientDetails by clientId: {}", clientId); +// return null; +// } +// +// OAuth2RequestFactory oAuth2RequestFactory = createOAuth2RequestFactory(); +// TokenGranter tokenGranter = getTokenGranter(oAuth2RequestFactory); +// LOG.debug("Use TokenGranter: {}", tokenGranter); +// +// TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(params, clientDetails); +// final OAuth2AccessToken oAuth2AccessToken = tokenGranter.grant(getGrantType(params), tokenRequest); - OAuth2RequestFactory oAuth2RequestFactory = createOAuth2RequestFactory(); - TokenGranter tokenGranter = getTokenGranter(oAuth2RequestFactory); - LOG.debug("Use TokenGranter: {}", tokenGranter); - - TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(params, clientDetails); - final OAuth2AccessToken oAuth2AccessToken = tokenGranter.grant(getGrantType(params), tokenRequest); - - if (oAuth2AccessToken == null) { - LOG.warn("TokenGranter: {} grant OAuth2AccessToken null", tokenGranter); - return null; - } - AccessTokenDto accessTokenDto = new AccessTokenDto(oAuth2AccessToken); - LOG.debug("Invoked accessTokenDto: {}", accessTokenDto); - return accessTokenDto; +// if (oAuth2AccessToken == null) { +// LOG.warn("TokenGranter: {} grant OAuth2AccessToken null", tokenGranter); +// return null; +// } +// AccessTokenDto accessTokenDto = new AccessTokenDto(oAuth2AccessToken); +// LOG.debug("Invoked accessTokenDto: {}", accessTokenDto); +// return accessTokenDto; + throw new UnsupportedOperationException("unsupport from v2.1.1"); } @@ -93,72 +89,73 @@ public abstract class InlineAccessTokenInvoker implements InitializingBean { */ protected String validateParams(Map params) { //validate client_id - String clientId = params.get(CLIENT_ID); - if (StringUtils.isBlank(clientId)) { - throw new IllegalStateException("Null or empty '" + CLIENT_ID + "' from params"); - } +// String clientId = params.get(CLIENT_ID); +// if (StringUtils.isBlank(clientId)) { +// throw new IllegalStateException("Null or empty '" + CLIENT_ID + "' from params"); +// } +// +// //validate grant_type +// final String grantType = params.get(GRANT_TYPE); +// if (StringUtils.isBlank(grantType)) { +// throw new IllegalStateException("Null or empty '" + GRANT_TYPE + "' from params"); +// } +// +// //validate scope +// final String scope = params.get(SCOPE); +// if (StringUtils.isBlank(scope)) { +// throw new IllegalStateException("Null or empty '" + SCOPE + "' from params"); +// } - //validate grant_type - final String grantType = params.get(GRANT_TYPE); - if (StringUtils.isBlank(grantType)) { - throw new IllegalStateException("Null or empty '" + GRANT_TYPE + "' from params"); - } - - //validate scope - final String scope = params.get(SCOPE); - if (StringUtils.isBlank(scope)) { - throw new IllegalStateException("Null or empty '" + SCOPE + "' from params"); - } - - return clientId; +// return clientId; + throw new UnsupportedOperationException("unsupport from v2.1.1"); } - /** - * Get grant_type from params - * - * @param params Map - * @return Grant Type - */ - protected String getGrantType(Map params) { - return params.get(GRANT_TYPE); - } +// /** +// * Get grant_type from params +// * +// * @param params Map +// * @return Grant Type +// */ +// protected String getGrantType(Map params) { +// return params.get(GRANT_TYPE); +// } +// +// +// /** +// * Get TokenGranter implement +// * +// * @return TokenGranter +// */ +// protected abstract TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory); +// /** +// * Create OAuth2RequestFactory +// * +// * @return OAuth2RequestFactory instance +// */ +// protected OAuth2RequestFactory createOAuth2RequestFactory() { +// return new DefaultOAuth2RequestFactory(this.clientDetailsService); +// } +// +// +// public void setAuthenticationManager(AuthenticationManager authenticationManager) { +// this.authenticationManager = authenticationManager; +// } - /** - * Get TokenGranter implement - * - * @return TokenGranter - */ - protected abstract TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory); - - /** - * Create OAuth2RequestFactory - * - * @return OAuth2RequestFactory instance - */ - protected OAuth2RequestFactory createOAuth2RequestFactory() { - return new DefaultOAuth2RequestFactory(this.clientDetailsService); - } - - - public void setAuthenticationManager(AuthenticationManager authenticationManager) { - this.authenticationManager = authenticationManager; - } - - public void setTokenServices(AuthorizationServerTokenServices tokenServices) { - this.tokenServices = tokenServices; - } - - public void setClientDetailsService(ClientDetailsService clientDetailsService) { - this.clientDetailsService = clientDetailsService; - } +// public void setTokenServices(AuthorizationServerTokenServices tokenServices) { +// this.tokenServices = tokenServices; +// } +// +// public void setClientDetailsService(ClientDetailsService clientDetailsService) { +// this.clientDetailsService = clientDetailsService; +// } @Override public void afterPropertiesSet() throws Exception { Assert.notNull(this.authenticationManager, "authenticationManager is null"); - Assert.notNull(this.tokenServices, "tokenServices is null"); +// Assert.notNull(this.tokenServices, "tokenServices is null"); - Assert.notNull(this.clientDetailsService, "clientDetailsService is null"); +// Assert.notNull(this.clientDetailsService, "clientDetailsService is null"); } } diff --git a/src/main/java/com/monkeyk/sos/service/business/PasswordInlineAccessTokenInvoker.java b/src/main/java/com/monkeyk/sos/service/business/PasswordInlineAccessTokenInvoker.java index aaf5ddf..e277591 100644 --- a/src/main/java/com/monkeyk/sos/service/business/PasswordInlineAccessTokenInvoker.java +++ b/src/main/java/com/monkeyk/sos/service/business/PasswordInlineAccessTokenInvoker.java @@ -1,8 +1,8 @@ package com.monkeyk.sos.service.business; -import org.springframework.security.oauth2.provider.OAuth2RequestFactory; -import org.springframework.security.oauth2.provider.TokenGranter; -import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter; +//import org.springframework.security.oauth2.provider.OAuth2RequestFactory; +//import org.springframework.security.oauth2.provider.TokenGranter; +//import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter; /** * 2019/7/5 @@ -12,17 +12,18 @@ import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswo * * @author Shengzhao Li * @since 2.0.1 + * @deprecated use spring-security-oauth2-authorization-server replaced from v2.1.1 */ public class PasswordInlineAccessTokenInvoker extends InlineAccessTokenInvoker { public PasswordInlineAccessTokenInvoker() { } - - @Override - protected TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory) { - return new ResourceOwnerPasswordTokenGranter(this.authenticationManager, this.tokenServices, this.clientDetailsService, oAuth2RequestFactory); - } +// +// @Override +// protected TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory) { +// return new ResourceOwnerPasswordTokenGranter(this.authenticationManager, this.tokenServices, this.clientDetailsService, oAuth2RequestFactory); +// } diff --git a/src/main/java/com/monkeyk/sos/service/business/RefreshTokenInlineAccessTokenInvoker.java b/src/main/java/com/monkeyk/sos/service/business/RefreshTokenInlineAccessTokenInvoker.java index 4b66c9d..18a1528 100644 --- a/src/main/java/com/monkeyk/sos/service/business/RefreshTokenInlineAccessTokenInvoker.java +++ b/src/main/java/com/monkeyk/sos/service/business/RefreshTokenInlineAccessTokenInvoker.java @@ -1,8 +1,8 @@ package com.monkeyk.sos.service.business; -import org.springframework.security.oauth2.provider.OAuth2RequestFactory; -import org.springframework.security.oauth2.provider.TokenGranter; -import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter; +//import org.springframework.security.oauth2.provider.OAuth2RequestFactory; +//import org.springframework.security.oauth2.provider.TokenGranter; +//import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter; /** * 2019/7/5 @@ -12,6 +12,7 @@ import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter; * * @author Shengzhao Li * @since 2.0.1 + * @deprecated use spring-security-oauth2-authorization-server replaced from v2.1.1 */ public class RefreshTokenInlineAccessTokenInvoker extends InlineAccessTokenInvoker { @@ -19,10 +20,10 @@ public class RefreshTokenInlineAccessTokenInvoker extends InlineAccessTokenInvok public RefreshTokenInlineAccessTokenInvoker() { } - @Override - protected TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory) { - return new RefreshTokenGranter(this.tokenServices, this.clientDetailsService, oAuth2RequestFactory); - } +// @Override +// protected TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory) { +// return new RefreshTokenGranter(this.tokenServices, this.clientDetailsService, oAuth2RequestFactory); +// } } diff --git a/src/main/java/com/monkeyk/sos/service/dto/AccessTokenDto.java b/src/main/java/com/monkeyk/sos/service/dto/AccessTokenDto.java index cb97b84..5d1f036 100644 --- a/src/main/java/com/monkeyk/sos/service/dto/AccessTokenDto.java +++ b/src/main/java/com/monkeyk/sos/service/dto/AccessTokenDto.java @@ -1,9 +1,11 @@ package com.monkeyk.sos.service.dto; import com.fasterxml.jackson.annotation.JsonProperty; -import org.apache.commons.lang.StringUtils; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.common.OAuth2RefreshToken; +//import org.apache.commons.lang.StringUtils; +//import org.springframework.security.oauth2.core.OAuth2AccessToken; +//import org.springframework.security.oauth2.core.OAuth2RefreshToken; +//import org.springframework.security.oauth2.common.OAuth2AccessToken; +//import org.springframework.security.oauth2.common.OAuth2RefreshToken; import java.io.Serializable; @@ -39,18 +41,18 @@ public class AccessTokenDto implements Serializable { } - public AccessTokenDto(OAuth2AccessToken token) { - this.accessToken = token.getValue(); - this.expiresIn = token.getExpiresIn(); - - this.scope = StringUtils.join(token.getScope(), ","); - this.tokenType = token.getTokenType(); - - final OAuth2RefreshToken oAuth2RefreshToken = token.getRefreshToken(); - if (oAuth2RefreshToken != null) { - this.refreshToken = oAuth2RefreshToken.getValue(); - } - } +// public AccessTokenDto(OAuth2AccessToken token) { +// this.accessToken = token.getValue(); +// this.expiresIn = token.getExpiresIn(); +// +// this.scope = StringUtils.join(token.getScope(), ","); +// this.tokenType = token.getTokenType(); +// +// final OAuth2RefreshToken oAuth2RefreshToken = token.getRefreshToken(); +// if (oAuth2RefreshToken != null) { +// this.refreshToken = oAuth2RefreshToken.getValue(); +// } +// } public String getAccessToken() { diff --git a/src/main/java/com/monkeyk/sos/service/impl/UserServiceImpl.java b/src/main/java/com/monkeyk/sos/service/impl/UserServiceImpl.java index 33ad8b3..5bd25e9 100644 --- a/src/main/java/com/monkeyk/sos/service/impl/UserServiceImpl.java +++ b/src/main/java/com/monkeyk/sos/service/impl/UserServiceImpl.java @@ -1,28 +1,25 @@ package com.monkeyk.sos.service.impl; -import com.monkeyk.sos.service.dto.UserDto; -import com.monkeyk.sos.service.dto.UserFormDto; -import com.monkeyk.sos.service.dto.UserJsonDto; -import com.monkeyk.sos.service.dto.UserOverviewDto; import com.monkeyk.sos.domain.shared.security.SOSUserDetails; import com.monkeyk.sos.domain.user.User; import com.monkeyk.sos.domain.user.UserRepository; import com.monkeyk.sos.service.UserService; +import com.monkeyk.sos.service.dto.UserDto; +import com.monkeyk.sos.service.dto.UserFormDto; +import com.monkeyk.sos.service.dto.UserJsonDto; +import com.monkeyk.sos.service.dto.UserOverviewDto; import com.monkeyk.sos.web.WebUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import java.util.Collection; import java.util.List; /** @@ -55,13 +52,19 @@ public class UserServiceImpl implements UserService { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final Object principal = authentication.getPrincipal(); - if (authentication instanceof OAuth2Authentication && + /* if (authentication instanceof OAuth2Authentication && (principal instanceof String || principal instanceof org.springframework.security.core.userdetails.User)) { return loadOauthUserJsonDto((OAuth2Authentication) authentication); - } else { + } else {*/ + if (principal instanceof SOSUserDetails) { final SOSUserDetails userDetails = (SOSUserDetails) principal; return new UserJsonDto(userRepository.findByGuid(userDetails.user().guid())); } +// } + if (LOG.isWarnEnabled()) { + LOG.warn("{}|Unknown principal: {}, please checking, return null", WebUtils.getIp(), principal); + } + return null; } @Override @@ -89,15 +92,15 @@ public class UserServiceImpl implements UserService { } - private UserJsonDto loadOauthUserJsonDto(OAuth2Authentication oAuth2Authentication) { - UserJsonDto userJsonDto = new UserJsonDto(); - userJsonDto.setUsername(oAuth2Authentication.getName()); - - final Collection authorities = oAuth2Authentication.getAuthorities(); - for (GrantedAuthority authority : authorities) { - userJsonDto.getPrivileges().add(authority.getAuthority()); - } - - return userJsonDto; - } +// private UserJsonDto loadOauthUserJsonDto(OAuth2Authentication oAuth2Authentication) { +// UserJsonDto userJsonDto = new UserJsonDto(); +// userJsonDto.setUsername(oAuth2Authentication.getName()); +// +// final Collection authorities = oAuth2Authentication.getAuthorities(); +// for (GrantedAuthority authority : authorities) { +// userJsonDto.getPrivileges().add(authority.getAuthority()); +// } +// +// return userJsonDto; +// } } \ No newline at end of file diff --git a/src/main/java/com/monkeyk/sos/web/context/SOSContextHolder.java b/src/main/java/com/monkeyk/sos/web/context/SOSContextHolder.java index 038550e..7b8d444 100644 --- a/src/main/java/com/monkeyk/sos/web/context/SOSContextHolder.java +++ b/src/main/java/com/monkeyk/sos/web/context/SOSContextHolder.java @@ -7,7 +7,6 @@ import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.util.Assert; /** @@ -82,10 +81,10 @@ public class SOSContextHolder implements BeanFactoryAware, InitializingBean { public void afterPropertiesSet() throws Exception { Assert.notNull(beanFactory, "beanFactory is null"); - if (LOG.isDebugEnabled()) { - TokenStore tokenStore = getBean(TokenStore.class); - LOG.debug("{} use tokenStore: {}", this.applicationName, tokenStore); - } +// if (LOG.isDebugEnabled()) { +// TokenStore tokenStore = getBean(TokenStore.class); +// LOG.debug("{} use tokenStore: {}", this.applicationName, tokenStore); +// } } } diff --git a/src/main/java/com/monkeyk/sos/web/controller/OAuthRestController.java b/src/main/java/com/monkeyk/sos/web/controller/OAuthRestController.java index 8a66d8a..7188330 100644 --- a/src/main/java/com/monkeyk/sos/web/controller/OAuthRestController.java +++ b/src/main/java/com/monkeyk/sos/web/controller/OAuthRestController.java @@ -16,34 +16,11 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import org.springframework.http.ResponseEntity; -import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.common.exceptions.*; -import org.springframework.security.oauth2.common.util.OAuth2Utils; -import org.springframework.security.oauth2.provider.*; -import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter; -import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices; -import org.springframework.security.oauth2.provider.code.AuthorizationCodeTokenGranter; -import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator; -import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator; -import org.springframework.security.oauth2.provider.implicit.ImplicitTokenGranter; -import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter; -import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter; -import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory; -import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestValidator; -import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; -import org.springframework.util.StringUtils; -import org.springframework.web.bind.annotation.*; - -import java.util.Collections; -import java.util.Map; /** * 2016/3/8 @@ -51,7 +28,8 @@ import java.util.Map; * Restful OAuth API * * @author Shengzhao Li - * @see org.springframework.security.oauth2.provider.endpoint.TokenEndpoint +// * @see org.springframework.security.oauth2.provider.endpoint.TokenEndpoint + * @deprecated use spring-security-oauth2-authorization-server replaced from v2.1.1 */ @Controller public class OAuthRestController implements InitializingBean, ApplicationContextAware { @@ -59,170 +37,170 @@ public class OAuthRestController implements InitializingBean, ApplicationContext private static final Logger LOG = LoggerFactory.getLogger(OAuthRestController.class); - @Autowired - private ClientDetailsService clientDetailsService; - - // consumerTokenServices,defaultAuthorizationServerTokenServices - @Autowired - @Qualifier("defaultAuthorizationServerTokenServices") - private AuthorizationServerTokenServices tokenServices; - @Autowired - private AuthorizationCodeServices authorizationCodeServices; - +// @Autowired +// private ClientDetailsService clientDetailsService; +// +// // consumerTokenServices,defaultAuthorizationServerTokenServices +// @Autowired +// @Qualifier("defaultAuthorizationServerTokenServices") +// private AuthorizationServerTokenServices tokenServices; +// @Autowired +// private AuthorizationCodeServices authorizationCodeServices; +// @Autowired private PasswordEncoder passwordEncoder; - - private AuthenticationManager authenticationManager; - - private OAuth2RequestFactory oAuth2RequestFactory; - - private OAuth2RequestValidator oAuth2RequestValidator = new DefaultOAuth2RequestValidator(); - private WebResponseExceptionTranslator providerExceptionHandler = new DefaultWebResponseExceptionTranslator(); - - - @RequestMapping(value = "/oauth/rest_token", method = RequestMethod.POST) - @ResponseBody - public OAuth2AccessToken postAccessToken(@RequestBody Map parameters) { - - - String clientId = getClientId(parameters); - ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId); - - //validate client_secret - String clientSecret = getClientSecret(parameters); - if (clientSecret == null || clientSecret.equals("")) { - throw new InvalidClientException("Bad client credentials"); - } else { - if (!this.passwordEncoder.matches(clientSecret, authenticatedClient.getClientSecret())) { - throw new InvalidClientException("Bad client credentials"); - } - } - - TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient); - - if (clientId != null && !clientId.equals("")) { - // Only validate the client details if a client authenticated during this - // request. - if (!clientId.equals(tokenRequest.getClientId())) { - // double check to make sure that the client ID in the token request is the same as that in the - // authenticated client - throw new InvalidClientException("Given client ID does not match authenticated client"); - } - } - - oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient); - - final String grantType = tokenRequest.getGrantType(); - if (!StringUtils.hasText(grantType)) { - throw new InvalidRequestException("Missing grant type"); - } - if (grantType.equals("implicit")) { - throw new InvalidGrantException("Implicit grant type not supported from token endpoint"); - } - - if (isAuthCodeRequest(parameters)) { - // The scope was requested or determined during the authorization step - if (!tokenRequest.getScope().isEmpty()) { - LOG.debug("Clearing scope of incoming token request"); - tokenRequest.setScope(Collections.emptySet()); - } - } - - - if (isRefreshTokenRequest(parameters)) { - // A refresh token has its own default scopes, so we should ignore any added by the factory here. - tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE))); - } - - OAuth2AccessToken token = getTokenGranter(grantType).grant(grantType, tokenRequest); - if (token == null) { - throw new UnsupportedGrantTypeException("Unsupported grant type: " + grantType); - } - - - return token; - - } - - protected TokenGranter getTokenGranter(String grantType) { - - if ("authorization_code".equals(grantType)) { - return new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetailsService, this.oAuth2RequestFactory); - } else if ("password".equals(grantType)) { - return new ResourceOwnerPasswordTokenGranter(getAuthenticationManager(), tokenServices, clientDetailsService, this.oAuth2RequestFactory); - } else if ("refresh_token".equals(grantType)) { - return new RefreshTokenGranter(tokenServices, clientDetailsService, this.oAuth2RequestFactory); - } else if ("client_credentials".equals(grantType)) { - return new ClientCredentialsTokenGranter(tokenServices, clientDetailsService, this.oAuth2RequestFactory); - } else if ("implicit".equals(grantType)) { - return new ImplicitTokenGranter(tokenServices, clientDetailsService, this.oAuth2RequestFactory); - } else { - throw new UnsupportedGrantTypeException("Unsupport grant_type: " + grantType); - } - } - - - @ExceptionHandler(Exception.class) - public ResponseEntity handleException(Exception e) throws Exception { - LOG.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage()); - return getExceptionTranslator().translate(e); - } - - @ExceptionHandler(ClientRegistrationException.class) - public ResponseEntity handleClientRegistrationException(Exception e) throws Exception { - LOG.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage()); - return getExceptionTranslator().translate(new BadClientCredentialsException()); - } - - @ExceptionHandler(OAuth2Exception.class) - public ResponseEntity handleException(OAuth2Exception e) throws Exception { - LOG.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage()); - return getExceptionTranslator().translate(e); - } - - - private boolean isRefreshTokenRequest(Map parameters) { - return "refresh_token".equals(parameters.get(OAuth2Utils.GRANT_TYPE)) && parameters.get("refresh_token") != null; - } - - private boolean isAuthCodeRequest(Map parameters) { - return "authorization_code".equals(parameters.get(OAuth2Utils.GRANT_TYPE)) && parameters.get("code") != null; - } - - - protected String getClientId(Map parameters) { - return parameters.get(OAuth2Utils.CLIENT_ID); - } - - protected String getClientSecret(Map parameters) { - return parameters.get("client_secret"); - } - - - private AuthenticationManager getAuthenticationManager() { - return this.authenticationManager; - } - +// +// private AuthenticationManager authenticationManager; +// +// private OAuth2RequestFactory oAuth2RequestFactory; +// +// private OAuth2RequestValidator oAuth2RequestValidator = new DefaultOAuth2RequestValidator(); +// private WebResponseExceptionTranslator providerExceptionHandler = new DefaultWebResponseExceptionTranslator(); +// +// +// @RequestMapping(value = "/oauth/rest_token", method = RequestMethod.POST) +// @ResponseBody +// public OAuth2AccessToken postAccessToken(@RequestBody Map parameters) { +// +// +// String clientId = getClientId(parameters); +// ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId); +// +// //validate client_secret +// String clientSecret = getClientSecret(parameters); +// if (clientSecret == null || clientSecret.equals("")) { +// throw new InvalidClientException("Bad client credentials"); +// } else { +// if (!this.passwordEncoder.matches(clientSecret, authenticatedClient.getClientSecret())) { +// throw new InvalidClientException("Bad client credentials"); +// } +// } +// +// TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient); +// +// if (clientId != null && !clientId.equals("")) { +// // Only validate the client details if a client authenticated during this +// // request. +// if (!clientId.equals(tokenRequest.getClientId())) { +// // double check to make sure that the client ID in the token request is the same as that in the +// // authenticated client +// throw new InvalidClientException("Given client ID does not match authenticated client"); +// } +// } +// +// oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient); +// +// final String grantType = tokenRequest.getGrantType(); +// if (!StringUtils.hasText(grantType)) { +// throw new InvalidRequestException("Missing grant type"); +// } +// if (grantType.equals("implicit")) { +// throw new InvalidGrantException("Implicit grant type not supported from token endpoint"); +// } +// +// if (isAuthCodeRequest(parameters)) { +// // The scope was requested or determined during the authorization step +// if (!tokenRequest.getScope().isEmpty()) { +// LOG.debug("Clearing scope of incoming token request"); +// tokenRequest.setScope(Collections.emptySet()); +// } +// } +// +// +// if (isRefreshTokenRequest(parameters)) { +// // A refresh token has its own default scopes, so we should ignore any added by the factory here. +// tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE))); +// } +// +// OAuth2AccessToken token = getTokenGranter(grantType).grant(grantType, tokenRequest); +// if (token == null) { +// throw new UnsupportedGrantTypeException("Unsupported grant type: " + grantType); +// } +// +// +// return token; +// +// } +// +// protected TokenGranter getTokenGranter(String grantType) { +// +// if ("authorization_code".equals(grantType)) { +// return new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetailsService, this.oAuth2RequestFactory); +// } else if ("password".equals(grantType)) { +// return new ResourceOwnerPasswordTokenGranter(getAuthenticationManager(), tokenServices, clientDetailsService, this.oAuth2RequestFactory); +// } else if ("refresh_token".equals(grantType)) { +// return new RefreshTokenGranter(tokenServices, clientDetailsService, this.oAuth2RequestFactory); +// } else if ("client_credentials".equals(grantType)) { +// return new ClientCredentialsTokenGranter(tokenServices, clientDetailsService, this.oAuth2RequestFactory); +// } else if ("implicit".equals(grantType)) { +// return new ImplicitTokenGranter(tokenServices, clientDetailsService, this.oAuth2RequestFactory); +// } else { +// throw new UnsupportedGrantTypeException("Unsupport grant_type: " + grantType); +// } +// } +// +// +// @ExceptionHandler(Exception.class) +// public ResponseEntity handleException(Exception e) throws Exception { +// LOG.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage()); +// return getExceptionTranslator().translate(e); +// } +// +// @ExceptionHandler(ClientRegistrationException.class) +// public ResponseEntity handleClientRegistrationException(Exception e) throws Exception { +// LOG.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage()); +// return getExceptionTranslator().translate(new BadClientCredentialsException()); +// } +// +// @ExceptionHandler(OAuth2Exception.class) +// public ResponseEntity handleException(OAuth2Exception e) throws Exception { +// LOG.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage()); +// return getExceptionTranslator().translate(e); +// } +// +// +// private boolean isRefreshTokenRequest(Map parameters) { +// return "refresh_token".equals(parameters.get(OAuth2Utils.GRANT_TYPE)) && parameters.get("refresh_token") != null; +// } +// +// private boolean isAuthCodeRequest(Map parameters) { +// return "authorization_code".equals(parameters.get(OAuth2Utils.GRANT_TYPE)) && parameters.get("code") != null; +// } +// +// +// protected String getClientId(Map parameters) { +// return parameters.get(OAuth2Utils.CLIENT_ID); +// } +// +// protected String getClientSecret(Map parameters) { +// return parameters.get("client_secret"); +// } +// +// +// private AuthenticationManager getAuthenticationManager() { +// return this.authenticationManager; +// } +// @Override public void afterPropertiesSet() throws Exception { - Assert.state(clientDetailsService != null, "ClientDetailsService must be provided"); - Assert.state(authenticationManager != null, "AuthenticationManager must be provided"); +// Assert.state(clientDetailsService != null, "ClientDetailsService must be provided"); +// Assert.state(authenticationManager != null, "AuthenticationManager must be provided"); Assert.notNull(this.passwordEncoder, "PasswordEncoder is null"); - oAuth2RequestFactory = new DefaultOAuth2RequestFactory(clientDetailsService); +// oAuth2RequestFactory = new DefaultOAuth2RequestFactory(clientDetailsService); } - protected WebResponseExceptionTranslator getExceptionTranslator() { - return providerExceptionHandler; - } - - +// protected WebResponseExceptionTranslator getExceptionTranslator() { +// return providerExceptionHandler; +// } +// +// @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - if (this.authenticationManager == null) { - this.authenticationManager = (AuthenticationManager) applicationContext.getBean("authenticationManagerBean"); - } +// if (this.authenticationManager == null) { +// this.authenticationManager = (AuthenticationManager) applicationContext.getBean("authenticationManagerBean"); +// } } } diff --git a/src/main/java/com/monkeyk/sos/web/oauth/OauthUserApprovalHandler.java b/src/main/java/com/monkeyk/sos/web/oauth/OauthUserApprovalHandler.java index 2b4e114..59bd7b5 100644 --- a/src/main/java/com/monkeyk/sos/web/oauth/OauthUserApprovalHandler.java +++ b/src/main/java/com/monkeyk/sos/web/oauth/OauthUserApprovalHandler.java @@ -1,34 +1,32 @@ package com.monkeyk.sos.web.oauth; -import com.monkeyk.sos.domain.oauth.OauthClientDetails; import com.monkeyk.sos.service.OauthService; -import org.springframework.security.core.Authentication; -import org.springframework.security.oauth2.provider.AuthorizationRequest; -import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler; /** * @author Shengzhao Li + * @deprecated use spring-security-oauth2-authorization-server replaced from v2.1.1 */ -public class OauthUserApprovalHandler extends TokenStoreUserApprovalHandler { +//public class OauthUserApprovalHandler extends TokenStoreUserApprovalHandler { +public class OauthUserApprovalHandler { private OauthService oauthService; public OauthUserApprovalHandler() { } - - public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { - if (super.isApproved(authorizationRequest, userAuthentication)) { - return true; - } - if (!userAuthentication.isAuthenticated()) { - return false; - } - - OauthClientDetails clientDetails = oauthService.loadOauthClientDetails(authorizationRequest.getClientId()); - return clientDetails != null && clientDetails.trusted(); - - } +// +// public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { +// if (super.isApproved(authorizationRequest, userAuthentication)) { +// return true; +// } +// if (!userAuthentication.isAuthenticated()) { +// return false; +// } +// +// OauthClientDetails clientDetails = oauthService.loadOauthClientDetails(authorizationRequest.getClientId()); +// return clientDetails != null && clientDetails.trusted(); +// +// } public void setOauthService(OauthService oauthService) { this.oauthService = oauthService; diff --git a/src/test/java/com/monkeyk/sos/config/JWTTokenStoreConfigurationTest.java b/src/test/java/com/monkeyk/sos/config/JWTTokenStoreConfigurationTest.java index 28341f7..4a08f71 100644 --- a/src/test/java/com/monkeyk/sos/config/JWTTokenStoreConfigurationTest.java +++ b/src/test/java/com/monkeyk/sos/config/JWTTokenStoreConfigurationTest.java @@ -2,8 +2,8 @@ package com.monkeyk.sos.config; import org.junit.jupiter.api.Test; -import org.springframework.security.oauth2.common.util.RandomValueStringGenerator; -import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; +//import org.springframework.security.oauth2.common.util.RandomValueStringGenerator; +//import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import java.util.Map; @@ -22,9 +22,9 @@ class JWTTokenStoreConfigurationTest { @Test void keyTest() throws Exception { - RandomValueStringGenerator randomValueStringGenerator = new RandomValueStringGenerator(32); - String verifierKey = randomValueStringGenerator.generate(); - assertNotNull(verifierKey); +// RandomValueStringGenerator randomValueStringGenerator = new RandomValueStringGenerator(32); +// String verifierKey = randomValueStringGenerator.generate(); +// assertNotNull(verifierKey); // System.out.println(verifierKey); } @@ -33,13 +33,13 @@ class JWTTokenStoreConfigurationTest { @Test void testJwtAccessTokenConverter() throws Exception { - JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter(); - jwtAccessTokenConverter.setSigningKey("IH6S2dhCEMwGr7uE4fBakSuDh9SoIrRa"); - jwtAccessTokenConverter.afterPropertiesSet(); - - assertFalse(jwtAccessTokenConverter.isPublic()); - Map key = jwtAccessTokenConverter.getKey(); - assertNotNull(key); +// JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter(); +// jwtAccessTokenConverter.setSigningKey("IH6S2dhCEMwGr7uE4fBakSuDh9SoIrRa"); +// jwtAccessTokenConverter.afterPropertiesSet(); +// +// assertFalse(jwtAccessTokenConverter.isPublic()); +// Map key = jwtAccessTokenConverter.getKey(); +// assertNotNull(key); } diff --git a/src/test/java/com/monkeyk/sos/service/business/ClientCredentialsInlineAccessTokenInvokerTest.java b/src/test/java/com/monkeyk/sos/service/business/ClientCredentialsInlineAccessTokenInvokerTest.java index 69d7645..626dcb8 100644 --- a/src/test/java/com/monkeyk/sos/service/business/ClientCredentialsInlineAccessTokenInvokerTest.java +++ b/src/test/java/com/monkeyk/sos/service/business/ClientCredentialsInlineAccessTokenInvokerTest.java @@ -3,7 +3,7 @@ package com.monkeyk.sos.service.business; import com.monkeyk.sos.service.dto.AccessTokenDto; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; -import org.springframework.security.oauth2.provider.NoSuchClientException; +//import org.springframework.security.oauth2.provider.NoSuchClientException; import java.util.HashMap; import java.util.Map; @@ -54,13 +54,13 @@ public class ClientCredentialsInlineAccessTokenInvokerTest extends AbstractInlin params.put("scope", "read"); - ClientCredentialsInlineAccessTokenInvoker accessTokenInvoker = new ClientCredentialsInlineAccessTokenInvoker(); - assertThrows(NoSuchClientException.class, () -> { - final AccessTokenDto accessTokenDto = accessTokenInvoker.invoke(params); - - assertNotNull(accessTokenDto); - assertNotNull(accessTokenDto.getAccessToken()); - }); +// ClientCredentialsInlineAccessTokenInvoker accessTokenInvoker = new ClientCredentialsInlineAccessTokenInvoker(); +// assertThrows(NoSuchClientException.class, () -> { +// final AccessTokenDto accessTokenDto = accessTokenInvoker.invoke(params); +// +// assertNotNull(accessTokenDto); +// assertNotNull(accessTokenDto.getAccessToken()); +// }); // System.out.println(accessTokenDto); diff --git a/src/test/java/com/monkeyk/sos/service/business/PasswordInlineAccessTokenInvokerTest.java b/src/test/java/com/monkeyk/sos/service/business/PasswordInlineAccessTokenInvokerTest.java index f5043ea..46bd424 100644 --- a/src/test/java/com/monkeyk/sos/service/business/PasswordInlineAccessTokenInvokerTest.java +++ b/src/test/java/com/monkeyk/sos/service/business/PasswordInlineAccessTokenInvokerTest.java @@ -2,7 +2,7 @@ package com.monkeyk.sos.service.business; import com.monkeyk.sos.service.dto.AccessTokenDto; import org.junit.jupiter.api.Test; -import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; +//import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; import java.util.HashMap; import java.util.Map; @@ -61,12 +61,12 @@ class PasswordInlineAccessTokenInvokerTest extends AbstractInlineAccessTokenInvo params.put("username", "useraaa"); params.put("password", "password"); - PasswordInlineAccessTokenInvoker accessTokenInvoker = new PasswordInlineAccessTokenInvoker(); - assertThrows(InvalidGrantException.class, () -> { - final AccessTokenDto tokenDto = accessTokenInvoker.invoke(params); - - assertNull(tokenDto); - }); +// PasswordInlineAccessTokenInvoker accessTokenInvoker = new PasswordInlineAccessTokenInvoker(); +// assertThrows(InvalidGrantException.class, () -> { +// final AccessTokenDto tokenDto = accessTokenInvoker.invoke(params); +// +// assertNull(tokenDto); +// }); // System.out.println(accessTokenDto); diff --git a/src/test/java/com/monkeyk/sos/service/business/RefreshTokenInlineAccessTokenInvokerTest.java b/src/test/java/com/monkeyk/sos/service/business/RefreshTokenInlineAccessTokenInvokerTest.java index a5ec8db..e3f5262 100644 --- a/src/test/java/com/monkeyk/sos/service/business/RefreshTokenInlineAccessTokenInvokerTest.java +++ b/src/test/java/com/monkeyk/sos/service/business/RefreshTokenInlineAccessTokenInvokerTest.java @@ -2,7 +2,7 @@ package com.monkeyk.sos.service.business; import com.monkeyk.sos.service.dto.AccessTokenDto; import org.junit.jupiter.api.Test; -import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; +//import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; import java.util.HashMap; import java.util.Map; @@ -96,18 +96,18 @@ class RefreshTokenInlineAccessTokenInvokerTest extends AbstractInlineAccessToken params2.put("refresh_token", tokenDto.getRefreshToken() + "sss"); - RefreshTokenInlineAccessTokenInvoker refreshTokenInlineAccessTokenInvoker = new RefreshTokenInlineAccessTokenInvoker(); - assertThrows(InvalidTokenException.class, () -> { - final AccessTokenDto accessTokenDto = refreshTokenInlineAccessTokenInvoker.invoke(params2); - - - assertNotNull(accessTokenDto); - assertNotNull(accessTokenDto.getAccessToken()); - - assertNotEquals(accessTokenDto.getAccessToken(), tokenDto.getAccessToken()); - assertNotEquals(accessTokenDto.getRefreshToken(), tokenDto.getRefreshToken()); - - }); +// RefreshTokenInlineAccessTokenInvoker refreshTokenInlineAccessTokenInvoker = new RefreshTokenInlineAccessTokenInvoker(); +// assertThrows(InvalidTokenException.class, () -> { +// final AccessTokenDto accessTokenDto = refreshTokenInlineAccessTokenInvoker.invoke(params2); +// +// +// assertNotNull(accessTokenDto); +// assertNotNull(accessTokenDto.getAccessToken()); +// +// assertNotEquals(accessTokenDto.getAccessToken(), tokenDto.getAccessToken()); +// assertNotEquals(accessTokenDto.getRefreshToken(), tokenDto.getRefreshToken()); +// +// }); }