升级spring security oauth2为 spring-security-oauth2-authorization-server

sas-2.1.1
shengzhaoli.shengz 2021-11-21 23:44:00 +08:00
parent 9e766e7250
commit 3ca53ad82b
23 changed files with 828 additions and 713 deletions

View File

@ -16,6 +16,7 @@ Base on Spring-Boot
<li>JDK (1.8.0_40)</li> <li>JDK (1.8.0_40)</li>
<li>Servlet (3.1.0)</li> <li>Servlet (3.1.0)</li>
<li>Spring Boot(2.4.2)</li> <li>Spring Boot(2.4.2)</li>
<li>spring-security-oauth2-authorization-server(0.2.0)</li>
</ol> </ol>
<h4>技术视频</h4> <h4>技术视频</h4>
<a href="http://list.youku.com/albumlist/show/id_51900110.html" target="_blank">http://list.youku.com/albumlist/show/id_51900110.html</a> <a href="http://list.youku.com/albumlist/show/id_51900110.html" target="_blank">http://list.youku.com/albumlist/show/id_51900110.html</a>
@ -172,6 +173,7 @@ Base on Spring-Boot
</p> </p>
<ol> <ol>
<li><p>升级spring-boot v2.4.2,改变可直接运行 SpringOauthServerApplication.java</p></li> <li><p>升级spring-boot v2.4.2,改变可直接运行 SpringOauthServerApplication.java</p></li>
<li><p>升级spring security oauth2为 spring-security-oauth2-authorization-server</p></li>
</ol> </ol>
<br/> <br/>
</li> </li>

View File

@ -2,65 +2,123 @@
-- Oauth sql -- MYSQL -- Oauth sql -- MYSQL
-- --
Drop table if exists oauth_client_details; -- oauth2_registered_client v2.1.1
create table oauth_client_details ( -- from oauth2-registered-client-schema.sql
client_id VARCHAR(255) PRIMARY KEY, CREATE TABLE oauth2_registered_client (
resource_ids VARCHAR(255), id varchar(100) NOT NULL,
client_secret VARCHAR(255), client_id varchar(100) NOT NULL,
scope VARCHAR(255), client_id_issued_at timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL,
authorized_grant_types VARCHAR(255), client_secret varchar(200) DEFAULT NULL,
web_server_redirect_uri VARCHAR(255), client_secret_expires_at timestamp DEFAULT NULL,
authorities VARCHAR(255), client_name varchar(200) NOT NULL,
access_token_validity INTEGER, client_authentication_methods varchar(1000) NOT NULL,
refresh_token_validity INTEGER, authorization_grant_types varchar(1000) NOT NULL,
additional_information TEXT, redirect_uris varchar(1000) DEFAULT NULL,
create_time timestamp default now(), scopes varchar(1000) NOT NULL,
archived tinyint(1) default '0', client_settings varchar(2000) NOT NULL,
trusted tinyint(1) default '0', token_settings varchar(2000) NOT NULL,
autoapprove VARCHAR (255) default 'false' PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; );
-- 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; # Drop table if exists oauth_client_details;
create table oauth_access_token ( # create table oauth_client_details (
create_time timestamp default now(), # client_id VARCHAR(255) PRIMARY KEY,
token_id VARCHAR(255), # resource_ids VARCHAR(255),
token BLOB, # client_secret VARCHAR(255),
authentication_id VARCHAR(255) UNIQUE, # scope VARCHAR(255),
user_name VARCHAR(255), # authorized_grant_types VARCHAR(255),
client_id VARCHAR(255), # web_server_redirect_uri VARCHAR(255),
authentication BLOB, # authorities VARCHAR(255),
refresh_token VARCHAR(255) # access_token_validity INTEGER,
) ENGINE=InnoDB DEFAULT CHARSET=utf8; # refresh_token_validity INTEGER,
# additional_information TEXT,
# create_time timestamp default now(),
Drop table if exists oauth_refresh_token; # archived tinyint(1) default '0',
create table oauth_refresh_token ( # trusted tinyint(1) default '0',
create_time timestamp default now(), # autoapprove VARCHAR (255) default 'false'
token_id VARCHAR(255), # ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
token BLOB, #
authentication BLOB #
) ENGINE=InnoDB DEFAULT CHARSET=utf8; # Drop table if exists oauth_access_token;
# create table oauth_access_token (
# create_time timestamp default now(),
Drop table if exists oauth_code; # token_id VARCHAR(255),
create table oauth_code ( # token BLOB,
create_time timestamp default now(), # authentication_id VARCHAR(255) UNIQUE,
code VARCHAR(255), # user_name VARCHAR(255),
authentication BLOB # client_id VARCHAR(255),
) ENGINE=InnoDB DEFAULT CHARSET=utf8; # authentication BLOB,
# refresh_token VARCHAR(255)
# ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#
-- Add indexes #
create index token_id_index on oauth_access_token (token_id); # Drop table if exists oauth_refresh_token;
create index authentication_id_index on oauth_access_token (authentication_id); # create table oauth_refresh_token (
create index user_name_index on oauth_access_token (user_name); # create_time timestamp default now(),
create index client_id_index on oauth_access_token (client_id); # token_id VARCHAR(255),
create index refresh_token_index on oauth_access_token (refresh_token); # token BLOB,
# authentication BLOB
create index token_id_index on oauth_refresh_token (token_id); # ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#
create index code_index on oauth_code (code); #
# 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);

View File

@ -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

29
pom.xml
View File

@ -23,8 +23,8 @@
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring.security.oauth.version>2.3.8.RELEASE</spring.security.oauth.version> <!--<spring.security.oauth.version>2.3.8.RELEASE</spring.security.oauth.version>-->
<spring.security.jwt.version>1.1.1.RELEASE</spring.security.jwt.version> <!--<spring.security.jwt.version>1.1.1.RELEASE</spring.security.jwt.version>-->
<test.skip>false</test.skip> <test.skip>false</test.skip>
</properties> </properties>
@ -48,18 +48,25 @@
<artifactId>spring-boot-starter-jdbc</artifactId> <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency> </dependency>
<!-- OAuth2--> <!--&lt;!&ndash; OAuth2&ndash;&gt;-->
<dependency> <!--<dependency>-->
<groupId>org.springframework.security.oauth</groupId> <!--<groupId>org.springframework.security.oauth</groupId>-->
<artifactId>spring-security-oauth2</artifactId> <!--<artifactId>spring-security-oauth2</artifactId>-->
<version>${spring.security.oauth.version}</version> <!--<version>${spring.security.oauth.version}</version>-->
</dependency> <!--</dependency>-->
<!-- JWT --> <!--&lt;!&ndash; JWT &ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>org.springframework.security</groupId>-->
<!--<artifactId>spring-security-jwt</artifactId>-->
<!--<version>${spring.security.jwt.version}</version>-->
<!--</dependency>-->
<!-- spring-authorization-server v2.1.1 -->
<dependency> <dependency>
<groupId>org.springframework.security</groupId> <groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId> <artifactId>spring-security-oauth2-authorization-server</artifactId>
<version>${spring.security.jwt.version}</version> <version>0.2.0</version>
</dependency> </dependency>

View File

@ -1,18 +1,9 @@
package com.monkeyk.sos.config; package com.monkeyk.sos.config;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; 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 * 2020/6/9
@ -41,45 +32,45 @@ public class JWTTokenStoreConfiguration {
private String jwtKey; private String jwtKey;
@Bean // @Bean
public JwtAccessTokenConverter accessTokenConverter(UserService userService) { // public JwtAccessTokenConverter accessTokenConverter(UserService userService) {
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter(); // 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(); // * JWT TokenStore
userAuthenticationConverter.setUserDetailsService(userService); // *
// userAuthenticationConverter.setDefaultAuthorities(new String[]{"USER"}); // * @since 2.1.0
tokenConverter.setUserTokenConverter(userAuthenticationConverter); // */
// @Bean
tokenConverter.setIncludeGrantType(true); // public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
// tokenConverter.setScopeAttribute("_scope"); // return new JwtTokenStore(jwtAccessTokenConverter);
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);
}
@Bean // @Bean
@Primary // @Primary
public DefaultTokenServices tokenServices(TokenStore tokenStore, JwtAccessTokenConverter tokenEnhancer, ClientDetailsService clientDetailsService) { // public DefaultTokenServices tokenServices(TokenStore tokenStore, JwtAccessTokenConverter tokenEnhancer, ClientDetailsService clientDetailsService) {
DefaultTokenServices tokenServices = new DefaultTokenServices(); // DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore); // tokenServices.setTokenStore(tokenStore);
tokenServices.setClientDetailsService(clientDetailsService); // tokenServices.setClientDetailsService(clientDetailsService);
//support refresh token // //support refresh token
tokenServices.setSupportRefreshToken(true); // tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenEnhancer(tokenEnhancer); // tokenServices.setTokenEnhancer(tokenEnhancer);
return tokenServices; // return tokenServices;
} // }
} }

View File

@ -1,15 +1,8 @@
package com.monkeyk.sos.config; package com.monkeyk.sos.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; 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 * 2020/6/9
@ -26,25 +19,25 @@ import javax.sql.DataSource;
@ConditionalOnProperty(name = "sos.token.store", havingValue = "jdbc", matchIfMissing = true) @ConditionalOnProperty(name = "sos.token.store", havingValue = "jdbc", matchIfMissing = true)
public class JdbcTokenStoreConfiguration { public class JdbcTokenStoreConfiguration {
//
/** // /**
* JDBC TokenStore // * JDBC TokenStore
*/ // */
@Bean // @Bean
public TokenStore tokenStore(DataSource dataSource) { // public TokenStore tokenStore(DataSource dataSource) {
return new JdbcTokenStore(dataSource); // return new JdbcTokenStore(dataSource);
} // }
//
//
@Bean // @Bean
@Primary // @Primary
public DefaultTokenServices tokenServices(TokenStore tokenStore, ClientDetailsService clientDetailsService) { // public DefaultTokenServices tokenServices(TokenStore tokenStore, ClientDetailsService clientDetailsService) {
DefaultTokenServices tokenServices = new DefaultTokenServices(); // DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore); // tokenServices.setTokenStore(tokenStore);
tokenServices.setClientDetailsService(clientDetailsService); // tokenServices.setClientDetailsService(clientDetailsService);
//support refresh token // //support refresh token
tokenServices.setSupportRefreshToken(true); // tokenServices.setSupportRefreshToken(true);
return tokenServices; // return tokenServices;
} // }
} }

View File

@ -1,10 +1,7 @@
package com.monkeyk.sos.config; package com.monkeyk.sos.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; 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.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler;
/** /**
* 2018/3/22 * 2018/3/22
@ -12,15 +9,17 @@ import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecur
* #oauth2 #oauth2.hasScope('read') * #oauth2 #oauth2.hasScope('read')
* *
* @author Shengzhao Li * @author Shengzhao Li
* @deprecated use spring-security-authorization-server replaced from v2.1.1
*/ */
@Configuration //@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true) //@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class OAuth2MethodSecurityConfiguration extends GlobalMethodSecurityConfiguration { public class OAuth2MethodSecurityConfiguration extends GlobalMethodSecurityConfiguration {
@Override @Override
protected MethodSecurityExpressionHandler createExpressionHandler() { protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler(); // return new OAuth2MethodSecurityExpressionHandler();
return super.createExpressionHandler();
} }
} }

View File

@ -1,33 +1,25 @@
package com.monkeyk.sos.config; package com.monkeyk.sos.config;
import com.monkeyk.sos.domain.oauth.CustomJdbcClientDetailsService; import com.nimbusds.jose.JOSEException;
import com.monkeyk.sos.service.OauthService; import com.nimbusds.jose.jwk.Curve;
import com.monkeyk.sos.service.UserService; import com.nimbusds.jose.jwk.JWK;
import com.monkeyk.sos.web.oauth.OauthUserApprovalHandler; import com.nimbusds.jose.jwk.JWKSet;
import org.springframework.beans.factory.annotation.Autowired; import com.nimbusds.jose.jwk.gen.ECKeyGenerator;
import org.springframework.beans.factory.annotation.Qualifier; 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.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.context.annotation.Import;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationService;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
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 javax.sql.DataSource; import javax.sql.DataSource;
@ -40,6 +32,8 @@ import javax.sql.DataSource;
* @author Shengzhao Li * @author Shengzhao Li
*/ */
@Configuration @Configuration
// import from v2.1.1
@Import(OAuth2AuthorizationServerConfiguration.class)
public class OAuth2ServerConfiguration { public class OAuth2ServerConfiguration {
@ -48,173 +42,253 @@ public class OAuth2ServerConfiguration {
/** /**
* // unity resource * JdbcTemplate config
* UNITY 访 *
* @param dataSource DataSource
* @return JdbcTemplate
* @since 2.1.1
*/ */
@Configuration @Bean
@EnableResourceServer public JdbcTemplate jdbcTemplate(DataSource dataSource) {
protected static class UnityResourceServerConfiguration extends ResourceServerConfigurerAdapter { return new JdbcTemplate(dataSource);
@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 * RegisteredClientRepository config
* MOBILE 访 * <p>
* SQL: oauth2-registered-client-schema.sql
*
* @param jdbcTemplate JdbcTemplate
* @return RegisteredClientRepository
* @since 2.1.1
*/ */
@Configuration @Bean
@EnableResourceServer public RegisteredClientRepository registeredClientRepository(JdbcTemplate jdbcTemplate) {
protected static class MobileResourceServerConfiguration extends ResourceServerConfigurerAdapter { return new JdbcRegisteredClientRepository(jdbcTemplate);
@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 { * OAuth2AuthorizationService config
* <p>
* 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; * OAuth2AuthorizationConsentService config
* <p>
@Autowired * SQL: oauth2-authorization-consent-schema.sql
private DefaultTokenServices tokenServices; *
* @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; * JWT使 JWK
* <p>
* 使EC, P_256
@Autowired *
private OauthService oauthService; * @return JWKSource
* @throws JOSEException e
* @since 2.1.1
@Autowired */
private AuthorizationCodeServices authorizationCodeServices; @Bean
public JWKSource<SecurityContext> jwkSource() throws JOSEException {
ECKeyGenerator keyGenerator = new ECKeyGenerator(Curve.P_256);
@Autowired keyGenerator.keyID(RESOURCE_ID);
private UserService userDetailsService; JWK jwk = keyGenerator.generate();
System.out.println("\n Use auto-generated jwk: " + jwk.toJSONString());
JWKSet jwkSet = new JWKSet(jwk);
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsService);
}
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 // @Bean
// public TokenStore tokenStore(DataSource dataSource) { // public ClientDetailsService clientDetailsService(DataSource dataSource) {
// return new JdbcTokenStore(dataSource); // return new CustomJdbcClientDetailsService(dataSource);
// } // }
//
/* //
* Redis TokenStore (Redis使)
*/
// @Bean // @Bean
// public TokenStore tokenStore(RedisConnectionFactory connectionFactory) { // public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) {
// final RedisTokenStore redisTokenStore = new RedisTokenStore(connectionFactory); // return new JdbcAuthorizationCodeServices(dataSource);
// //prefix
// redisTokenStore.setPrefix(RESOURCE_ID);
// return redisTokenStore;
// } // }
//
//
@Bean // @Override
public ClientDetailsService clientDetailsService(DataSource dataSource) { // public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
return new CustomJdbcClientDetailsService(dataSource); // endpoints.tokenServices(tokenServices)
} // .tokenStore(tokenStore)
// .authorizationCodeServices(authorizationCodeServices)
// .userDetailsService(userDetailsService)
@Bean // .userApprovalHandler(userApprovalHandler())
public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) { // .authenticationManager(authenticationManager);
return new JdbcAuthorizationCodeServices(dataSource); // }
} //
// @Override
// public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
@Override // // real 值可自定义
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { // oauthServer.realm("spring-oauth-server")
endpoints.tokenServices(tokenServices) // // 支持 client_credentials 的配置
.tokenStore(tokenStore) // .allowFormAuthenticationForClients();
.authorizationCodeServices(authorizationCodeServices) // }
.userDetailsService(userDetailsService) //
.userApprovalHandler(userApprovalHandler()) // @Bean
.authenticationManager(authenticationManager); // public OAuth2RequestFactory oAuth2RequestFactory() {
} // return new DefaultOAuth2RequestFactory(clientDetailsService);
// }
@Override //
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { //
// real 值可自定义 // @Bean
oauthServer.realm("spring-oauth-server") // public UserApprovalHandler userApprovalHandler() {
// 支持 client_credentials 的配置 // OauthUserApprovalHandler userApprovalHandler = new OauthUserApprovalHandler();
.allowFormAuthenticationForClients(); // userApprovalHandler.setOauthService(oauthService);
} // userApprovalHandler.setTokenStore(tokenStore);
// userApprovalHandler.setClientDetailsService(this.clientDetailsService);
@Bean // userApprovalHandler.setRequestFactory(oAuth2RequestFactory());
public OAuth2RequestFactory oAuth2RequestFactory() { // return userApprovalHandler;
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;
}
}
} }

View File

@ -1,6 +1,6 @@
package com.monkeyk.sos.domain.oauth; 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; import javax.sql.DataSource;
@ -8,8 +8,10 @@ import javax.sql.DataSource;
* Add <i>archived = 0</i> condition * Add <i>archived = 0</i> condition
* *
* @author Shengzhao Li * @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 * SQL
@ -20,10 +22,10 @@ public class CustomJdbcClientDetailsService extends JdbcClientDetailsService {
"from oauth_client_details where client_id = ? and archived = 0 "; "from oauth_client_details where client_id = ? and archived = 0 ";
public CustomJdbcClientDetailsService(DataSource dataSource) { // public CustomJdbcClientDetailsService(DataSource dataSource) {
super(dataSource); // super(dataSource);
setSelectClientDetailsSql(SELECT_CLIENT_DETAILS_SQL); // setSelectClientDetailsSql(SELECT_CLIENT_DETAILS_SQL);
} // }
} }

View File

@ -1,6 +1,8 @@
package com.monkeyk.sos.domain.shared; 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; import java.util.UUID;
@ -10,7 +12,7 @@ import java.util.UUID;
public abstract class GuidGenerator { 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() { public static String generateClientSecret() {
return defaultClientSecretGenerator.generate(); return RandomStringUtils.random(32, true, true);
} }
} }

View File

@ -1,8 +1,8 @@
package com.monkeyk.sos.service.business; package com.monkeyk.sos.service.business;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory; //import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenGranter; //import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter; //import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter;
/** /**
* 2019/7/5 * 2019/7/5
@ -12,6 +12,7 @@ import org.springframework.security.oauth2.provider.client.ClientCredentialsToke
* *
* @author Shengzhao Li * @author Shengzhao Li
* @since 2.0.1 * @since 2.0.1
* @deprecated use spring-security-oauth2-authorization-server replaced from v2.1.1
*/ */
public class ClientCredentialsInlineAccessTokenInvoker extends InlineAccessTokenInvoker { public class ClientCredentialsInlineAccessTokenInvoker extends InlineAccessTokenInvoker {
@ -19,10 +20,10 @@ public class ClientCredentialsInlineAccessTokenInvoker extends InlineAccessToken
public ClientCredentialsInlineAccessTokenInvoker() { public ClientCredentialsInlineAccessTokenInvoker() {
} }
@Override // @Override
protected TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory) { // protected TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory) {
return new ClientCredentialsTokenGranter(this.tokenServices, this.clientDetailsService, oAuth2RequestFactory); // return new ClientCredentialsTokenGranter(this.tokenServices, this.clientDetailsService, oAuth2RequestFactory);
} // }
} }

View File

@ -7,24 +7,19 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.authentication.AuthenticationManager; 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 org.springframework.util.Assert;
import java.util.Map; 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 * 2019/7/5
* *
* @author Shengzhao Li * @author Shengzhao Li
* @see org.springframework.security.oauth2.provider.endpoint.TokenEndpoint // * @see org.springframework.security.oauth2.provider.endpoint.TokenEndpoint
* @since 2.0.1 * @since 2.0.1
* @deprecated use spring-security-oauth2-authorization-server replaced from v2.1.1
*/ */
public abstract class InlineAccessTokenInvoker implements InitializingBean { 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 AuthenticationManager authenticationManager = SOSContextHolder.getBean(AuthenticationManager.class);
protected transient AuthorizationServerTokenServices tokenServices = SOSContextHolder.getBean(AuthorizationServerTokenServices.class); // protected transient AuthorizationServerTokenServices tokenServices = SOSContextHolder.getBean(AuthorizationServerTokenServices.class);
; //
protected transient ClientDetailsService clientDetailsService = SOSContextHolder.getBean(ClientDetailsService.class); // protected transient ClientDetailsService clientDetailsService = SOSContextHolder.getBean(ClientDetailsService.class);
public InlineAccessTokenInvoker() { public InlineAccessTokenInvoker() {
@ -62,26 +57,27 @@ public abstract class InlineAccessTokenInvoker implements InitializingBean {
String clientId = validateParams(params); String clientId = validateParams(params);
final ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId); // final ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
if (clientDetails == null) { // if (clientDetails == null) {
LOG.warn("Not found ClientDetails by clientId: {}", clientId); // LOG.warn("Not found ClientDetails by clientId: {}", clientId);
return null; // 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(); // if (oAuth2AccessToken == null) {
TokenGranter tokenGranter = getTokenGranter(oAuth2RequestFactory); // LOG.warn("TokenGranter: {} grant OAuth2AccessToken null", tokenGranter);
LOG.debug("Use TokenGranter: {}", tokenGranter); // return null;
// }
TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(params, clientDetails); // AccessTokenDto accessTokenDto = new AccessTokenDto(oAuth2AccessToken);
final OAuth2AccessToken oAuth2AccessToken = tokenGranter.grant(getGrantType(params), tokenRequest); // LOG.debug("Invoked accessTokenDto: {}", accessTokenDto);
// return accessTokenDto;
if (oAuth2AccessToken == null) { throw new UnsupportedOperationException("unsupport from v2.1.1");
LOG.warn("TokenGranter: {} grant OAuth2AccessToken null", tokenGranter);
return null;
}
AccessTokenDto accessTokenDto = new AccessTokenDto(oAuth2AccessToken);
LOG.debug("Invoked accessTokenDto: {}", accessTokenDto);
return accessTokenDto;
} }
@ -93,72 +89,73 @@ public abstract class InlineAccessTokenInvoker implements InitializingBean {
*/ */
protected String validateParams(Map<String, String> params) { protected String validateParams(Map<String, String> params) {
//validate client_id //validate client_id
String clientId = params.get(CLIENT_ID); // String clientId = params.get(CLIENT_ID);
if (StringUtils.isBlank(clientId)) { // if (StringUtils.isBlank(clientId)) {
throw new IllegalStateException("Null or empty '" + CLIENT_ID + "' from params"); // 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 // return clientId;
final String grantType = params.get(GRANT_TYPE); throw new UnsupportedOperationException("unsupport from v2.1.1");
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;
} }
/** // /**
* Get grant_type from params // * Get grant_type from params
* // *
* @param params Map // * @param params Map
* @return Grant Type // * @return Grant Type
*/ // */
protected String getGrantType(Map<String, String> params) { // protected String getGrantType(Map<String, String> params) {
return params.get(GRANT_TYPE); // 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;
// }
/** // public void setTokenServices(AuthorizationServerTokenServices tokenServices) {
* Get TokenGranter implement // this.tokenServices = tokenServices;
* // }
* @return TokenGranter //
*/ // public void setClientDetailsService(ClientDetailsService clientDetailsService) {
protected abstract TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory); // this.clientDetailsService = clientDetailsService;
// }
/**
* 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;
}
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
Assert.notNull(this.authenticationManager, "authenticationManager is null"); 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");
} }
} }

View File

@ -1,8 +1,8 @@
package com.monkeyk.sos.service.business; package com.monkeyk.sos.service.business;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory; //import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenGranter; //import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter; //import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
/** /**
* 2019/7/5 * 2019/7/5
@ -12,17 +12,18 @@ import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswo
* *
* @author Shengzhao Li * @author Shengzhao Li
* @since 2.0.1 * @since 2.0.1
* @deprecated use spring-security-oauth2-authorization-server replaced from v2.1.1
*/ */
public class PasswordInlineAccessTokenInvoker extends InlineAccessTokenInvoker { public class PasswordInlineAccessTokenInvoker extends InlineAccessTokenInvoker {
public PasswordInlineAccessTokenInvoker() { public PasswordInlineAccessTokenInvoker() {
} }
//
@Override // @Override
protected TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory) { // protected TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory) {
return new ResourceOwnerPasswordTokenGranter(this.authenticationManager, this.tokenServices, this.clientDetailsService, oAuth2RequestFactory); // return new ResourceOwnerPasswordTokenGranter(this.authenticationManager, this.tokenServices, this.clientDetailsService, oAuth2RequestFactory);
} // }

View File

@ -1,8 +1,8 @@
package com.monkeyk.sos.service.business; package com.monkeyk.sos.service.business;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory; //import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenGranter; //import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter; //import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter;
/** /**
* 2019/7/5 * 2019/7/5
@ -12,6 +12,7 @@ import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter;
* *
* @author Shengzhao Li * @author Shengzhao Li
* @since 2.0.1 * @since 2.0.1
* @deprecated use spring-security-oauth2-authorization-server replaced from v2.1.1
*/ */
public class RefreshTokenInlineAccessTokenInvoker extends InlineAccessTokenInvoker { public class RefreshTokenInlineAccessTokenInvoker extends InlineAccessTokenInvoker {
@ -19,10 +20,10 @@ public class RefreshTokenInlineAccessTokenInvoker extends InlineAccessTokenInvok
public RefreshTokenInlineAccessTokenInvoker() { public RefreshTokenInlineAccessTokenInvoker() {
} }
@Override // @Override
protected TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory) { // protected TokenGranter getTokenGranter(OAuth2RequestFactory oAuth2RequestFactory) {
return new RefreshTokenGranter(this.tokenServices, this.clientDetailsService, oAuth2RequestFactory); // return new RefreshTokenGranter(this.tokenServices, this.clientDetailsService, oAuth2RequestFactory);
} // }
} }

View File

@ -1,9 +1,11 @@
package com.monkeyk.sos.service.dto; package com.monkeyk.sos.service.dto;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang.StringUtils; //import org.apache.commons.lang.StringUtils;
import org.springframework.security.oauth2.common.OAuth2AccessToken; //import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken; //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; import java.io.Serializable;
@ -39,18 +41,18 @@ public class AccessTokenDto implements Serializable {
} }
public AccessTokenDto(OAuth2AccessToken token) { // public AccessTokenDto(OAuth2AccessToken token) {
this.accessToken = token.getValue(); // this.accessToken = token.getValue();
this.expiresIn = token.getExpiresIn(); // this.expiresIn = token.getExpiresIn();
//
this.scope = StringUtils.join(token.getScope(), ","); // this.scope = StringUtils.join(token.getScope(), ",");
this.tokenType = token.getTokenType(); // this.tokenType = token.getTokenType();
//
final OAuth2RefreshToken oAuth2RefreshToken = token.getRefreshToken(); // final OAuth2RefreshToken oAuth2RefreshToken = token.getRefreshToken();
if (oAuth2RefreshToken != null) { // if (oAuth2RefreshToken != null) {
this.refreshToken = oAuth2RefreshToken.getValue(); // this.refreshToken = oAuth2RefreshToken.getValue();
} // }
} // }
public String getAccessToken() { public String getAccessToken() {

View File

@ -1,28 +1,25 @@
package com.monkeyk.sos.service.impl; 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.shared.security.SOSUserDetails;
import com.monkeyk.sos.domain.user.User; import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.domain.user.UserRepository; import com.monkeyk.sos.domain.user.UserRepository;
import com.monkeyk.sos.service.UserService; 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 com.monkeyk.sos.web.WebUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.List; import java.util.List;
/** /**
@ -55,13 +52,19 @@ public class UserServiceImpl implements UserService {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
final Object principal = authentication.getPrincipal(); final Object principal = authentication.getPrincipal();
if (authentication instanceof OAuth2Authentication && /* if (authentication instanceof OAuth2Authentication &&
(principal instanceof String || principal instanceof org.springframework.security.core.userdetails.User)) { (principal instanceof String || principal instanceof org.springframework.security.core.userdetails.User)) {
return loadOauthUserJsonDto((OAuth2Authentication) authentication); return loadOauthUserJsonDto((OAuth2Authentication) authentication);
} else { } else {*/
if (principal instanceof SOSUserDetails) {
final SOSUserDetails userDetails = (SOSUserDetails) principal; final SOSUserDetails userDetails = (SOSUserDetails) principal;
return new UserJsonDto(userRepository.findByGuid(userDetails.user().guid())); 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 @Override
@ -89,15 +92,15 @@ public class UserServiceImpl implements UserService {
} }
private UserJsonDto loadOauthUserJsonDto(OAuth2Authentication oAuth2Authentication) { // private UserJsonDto loadOauthUserJsonDto(OAuth2Authentication oAuth2Authentication) {
UserJsonDto userJsonDto = new UserJsonDto(); // UserJsonDto userJsonDto = new UserJsonDto();
userJsonDto.setUsername(oAuth2Authentication.getName()); // userJsonDto.setUsername(oAuth2Authentication.getName());
//
final Collection<GrantedAuthority> authorities = oAuth2Authentication.getAuthorities(); // final Collection<GrantedAuthority> authorities = oAuth2Authentication.getAuthorities();
for (GrantedAuthority authority : authorities) { // for (GrantedAuthority authority : authorities) {
userJsonDto.getPrivileges().add(authority.getAuthority()); // userJsonDto.getPrivileges().add(authority.getAuthority());
} // }
//
return userJsonDto; // return userJsonDto;
} // }
} }

View File

@ -7,7 +7,6 @@ import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
@ -82,10 +81,10 @@ public class SOSContextHolder implements BeanFactoryAware, InitializingBean {
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
Assert.notNull(beanFactory, "beanFactory is null"); Assert.notNull(beanFactory, "beanFactory is null");
if (LOG.isDebugEnabled()) { // if (LOG.isDebugEnabled()) {
TokenStore tokenStore = getBean(TokenStore.class); // TokenStore tokenStore = getBean(TokenStore.class);
LOG.debug("{} use tokenStore: {}", this.applicationName, tokenStore); // LOG.debug("{} use tokenStore: {}", this.applicationName, tokenStore);
} // }
} }
} }

View File

@ -16,34 +16,11 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; 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.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.stereotype.Controller;
import org.springframework.util.Assert; 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 * 2016/3/8
@ -51,7 +28,8 @@ import java.util.Map;
* Restful OAuth API * Restful OAuth API
* *
* @author Shengzhao Li * @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 @Controller
public class OAuthRestController implements InitializingBean, ApplicationContextAware { 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); private static final Logger LOG = LoggerFactory.getLogger(OAuthRestController.class);
@Autowired // @Autowired
private ClientDetailsService clientDetailsService; // private ClientDetailsService clientDetailsService;
//
// consumerTokenServices,defaultAuthorizationServerTokenServices // // consumerTokenServices,defaultAuthorizationServerTokenServices
@Autowired // @Autowired
@Qualifier("defaultAuthorizationServerTokenServices") // @Qualifier("defaultAuthorizationServerTokenServices")
private AuthorizationServerTokenServices tokenServices; // private AuthorizationServerTokenServices tokenServices;
@Autowired // @Autowired
private AuthorizationCodeServices authorizationCodeServices; // private AuthorizationCodeServices authorizationCodeServices;
//
@Autowired @Autowired
private PasswordEncoder passwordEncoder; private PasswordEncoder passwordEncoder;
//
private AuthenticationManager authenticationManager; // private AuthenticationManager authenticationManager;
//
private OAuth2RequestFactory oAuth2RequestFactory; // private OAuth2RequestFactory oAuth2RequestFactory;
//
private OAuth2RequestValidator oAuth2RequestValidator = new DefaultOAuth2RequestValidator(); // private OAuth2RequestValidator oAuth2RequestValidator = new DefaultOAuth2RequestValidator();
private WebResponseExceptionTranslator providerExceptionHandler = new DefaultWebResponseExceptionTranslator(); // private WebResponseExceptionTranslator providerExceptionHandler = new DefaultWebResponseExceptionTranslator();
//
//
@RequestMapping(value = "/oauth/rest_token", method = RequestMethod.POST) // @RequestMapping(value = "/oauth/rest_token", method = RequestMethod.POST)
@ResponseBody // @ResponseBody
public OAuth2AccessToken postAccessToken(@RequestBody Map<String, String> parameters) { // public OAuth2AccessToken postAccessToken(@RequestBody Map<String, String> parameters) {
//
//
String clientId = getClientId(parameters); // String clientId = getClientId(parameters);
ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId); // ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId);
//
//validate client_secret // //validate client_secret
String clientSecret = getClientSecret(parameters); // String clientSecret = getClientSecret(parameters);
if (clientSecret == null || clientSecret.equals("")) { // if (clientSecret == null || clientSecret.equals("")) {
throw new InvalidClientException("Bad client credentials"); // throw new InvalidClientException("Bad client credentials");
} else { // } else {
if (!this.passwordEncoder.matches(clientSecret, authenticatedClient.getClientSecret())) { // if (!this.passwordEncoder.matches(clientSecret, authenticatedClient.getClientSecret())) {
throw new InvalidClientException("Bad client credentials"); // throw new InvalidClientException("Bad client credentials");
} // }
} // }
//
TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient); // TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);
//
if (clientId != null && !clientId.equals("")) { // if (clientId != null && !clientId.equals("")) {
// Only validate the client details if a client authenticated during this // // Only validate the client details if a client authenticated during this
// request. // // request.
if (!clientId.equals(tokenRequest.getClientId())) { // 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 // // double check to make sure that the client ID in the token request is the same as that in the
// authenticated client // // authenticated client
throw new InvalidClientException("Given client ID does not match authenticated client"); // throw new InvalidClientException("Given client ID does not match authenticated client");
} // }
} // }
//
oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient); // oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
//
final String grantType = tokenRequest.getGrantType(); // final String grantType = tokenRequest.getGrantType();
if (!StringUtils.hasText(grantType)) { // if (!StringUtils.hasText(grantType)) {
throw new InvalidRequestException("Missing grant type"); // throw new InvalidRequestException("Missing grant type");
} // }
if (grantType.equals("implicit")) { // if (grantType.equals("implicit")) {
throw new InvalidGrantException("Implicit grant type not supported from token endpoint"); // throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
} // }
//
if (isAuthCodeRequest(parameters)) { // if (isAuthCodeRequest(parameters)) {
// The scope was requested or determined during the authorization step // // The scope was requested or determined during the authorization step
if (!tokenRequest.getScope().isEmpty()) { // if (!tokenRequest.getScope().isEmpty()) {
LOG.debug("Clearing scope of incoming token request"); // LOG.debug("Clearing scope of incoming token request");
tokenRequest.setScope(Collections.<String>emptySet()); // tokenRequest.setScope(Collections.<String>emptySet());
} // }
} // }
//
//
if (isRefreshTokenRequest(parameters)) { // if (isRefreshTokenRequest(parameters)) {
// A refresh token has its own default scopes, so we should ignore any added by the factory here. // // 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))); // tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
} // }
//
OAuth2AccessToken token = getTokenGranter(grantType).grant(grantType, tokenRequest); // OAuth2AccessToken token = getTokenGranter(grantType).grant(grantType, tokenRequest);
if (token == null) { // if (token == null) {
throw new UnsupportedGrantTypeException("Unsupported grant type: " + grantType); // throw new UnsupportedGrantTypeException("Unsupported grant type: " + grantType);
} // }
//
//
return token; // return token;
//
} // }
//
protected TokenGranter getTokenGranter(String grantType) { // protected TokenGranter getTokenGranter(String grantType) {
//
if ("authorization_code".equals(grantType)) { // if ("authorization_code".equals(grantType)) {
return new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetailsService, this.oAuth2RequestFactory); // return new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetailsService, this.oAuth2RequestFactory);
} else if ("password".equals(grantType)) { // } else if ("password".equals(grantType)) {
return new ResourceOwnerPasswordTokenGranter(getAuthenticationManager(), tokenServices, clientDetailsService, this.oAuth2RequestFactory); // return new ResourceOwnerPasswordTokenGranter(getAuthenticationManager(), tokenServices, clientDetailsService, this.oAuth2RequestFactory);
} else if ("refresh_token".equals(grantType)) { // } else if ("refresh_token".equals(grantType)) {
return new RefreshTokenGranter(tokenServices, clientDetailsService, this.oAuth2RequestFactory); // return new RefreshTokenGranter(tokenServices, clientDetailsService, this.oAuth2RequestFactory);
} else if ("client_credentials".equals(grantType)) { // } else if ("client_credentials".equals(grantType)) {
return new ClientCredentialsTokenGranter(tokenServices, clientDetailsService, this.oAuth2RequestFactory); // return new ClientCredentialsTokenGranter(tokenServices, clientDetailsService, this.oAuth2RequestFactory);
} else if ("implicit".equals(grantType)) { // } else if ("implicit".equals(grantType)) {
return new ImplicitTokenGranter(tokenServices, clientDetailsService, this.oAuth2RequestFactory); // return new ImplicitTokenGranter(tokenServices, clientDetailsService, this.oAuth2RequestFactory);
} else { // } else {
throw new UnsupportedGrantTypeException("Unsupport grant_type: " + grantType); // throw new UnsupportedGrantTypeException("Unsupport grant_type: " + grantType);
} // }
} // }
//
//
@ExceptionHandler(Exception.class) // @ExceptionHandler(Exception.class)
public ResponseEntity<OAuth2Exception> handleException(Exception e) throws Exception { // public ResponseEntity<OAuth2Exception> handleException(Exception e) throws Exception {
LOG.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage()); // LOG.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage());
return getExceptionTranslator().translate(e); // return getExceptionTranslator().translate(e);
} // }
//
@ExceptionHandler(ClientRegistrationException.class) // @ExceptionHandler(ClientRegistrationException.class)
public ResponseEntity<OAuth2Exception> handleClientRegistrationException(Exception e) throws Exception { // public ResponseEntity<OAuth2Exception> handleClientRegistrationException(Exception e) throws Exception {
LOG.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage()); // LOG.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage());
return getExceptionTranslator().translate(new BadClientCredentialsException()); // return getExceptionTranslator().translate(new BadClientCredentialsException());
} // }
//
@ExceptionHandler(OAuth2Exception.class) // @ExceptionHandler(OAuth2Exception.class)
public ResponseEntity<OAuth2Exception> handleException(OAuth2Exception e) throws Exception { // public ResponseEntity<OAuth2Exception> handleException(OAuth2Exception e) throws Exception {
LOG.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage()); // LOG.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage());
return getExceptionTranslator().translate(e); // return getExceptionTranslator().translate(e);
} // }
//
//
private boolean isRefreshTokenRequest(Map<String, String> parameters) { // private boolean isRefreshTokenRequest(Map<String, String> parameters) {
return "refresh_token".equals(parameters.get(OAuth2Utils.GRANT_TYPE)) && parameters.get("refresh_token") != null; // return "refresh_token".equals(parameters.get(OAuth2Utils.GRANT_TYPE)) && parameters.get("refresh_token") != null;
} // }
//
private boolean isAuthCodeRequest(Map<String, String> parameters) { // private boolean isAuthCodeRequest(Map<String, String> parameters) {
return "authorization_code".equals(parameters.get(OAuth2Utils.GRANT_TYPE)) && parameters.get("code") != null; // return "authorization_code".equals(parameters.get(OAuth2Utils.GRANT_TYPE)) && parameters.get("code") != null;
} // }
//
//
protected String getClientId(Map<String, String> parameters) { // protected String getClientId(Map<String, String> parameters) {
return parameters.get(OAuth2Utils.CLIENT_ID); // return parameters.get(OAuth2Utils.CLIENT_ID);
} // }
//
protected String getClientSecret(Map<String, String> parameters) { // protected String getClientSecret(Map<String, String> parameters) {
return parameters.get("client_secret"); // return parameters.get("client_secret");
} // }
//
//
private AuthenticationManager getAuthenticationManager() { // private AuthenticationManager getAuthenticationManager() {
return this.authenticationManager; // return this.authenticationManager;
} // }
//
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
Assert.state(clientDetailsService != null, "ClientDetailsService must be provided"); // Assert.state(clientDetailsService != null, "ClientDetailsService must be provided");
Assert.state(authenticationManager != null, "AuthenticationManager must be provided"); // Assert.state(authenticationManager != null, "AuthenticationManager must be provided");
Assert.notNull(this.passwordEncoder, "PasswordEncoder is null"); Assert.notNull(this.passwordEncoder, "PasswordEncoder is null");
oAuth2RequestFactory = new DefaultOAuth2RequestFactory(clientDetailsService); // oAuth2RequestFactory = new DefaultOAuth2RequestFactory(clientDetailsService);
} }
protected WebResponseExceptionTranslator getExceptionTranslator() { // protected WebResponseExceptionTranslator getExceptionTranslator() {
return providerExceptionHandler; // return providerExceptionHandler;
} // }
//
//
@Override @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (this.authenticationManager == null) { // if (this.authenticationManager == null) {
this.authenticationManager = (AuthenticationManager) applicationContext.getBean("authenticationManagerBean"); // this.authenticationManager = (AuthenticationManager) applicationContext.getBean("authenticationManagerBean");
} // }
} }
} }

View File

@ -1,34 +1,32 @@
package com.monkeyk.sos.web.oauth; package com.monkeyk.sos.web.oauth;
import com.monkeyk.sos.domain.oauth.OauthClientDetails;
import com.monkeyk.sos.service.OauthService; 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 * @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; private OauthService oauthService;
public OauthUserApprovalHandler() { public OauthUserApprovalHandler() {
} }
//
public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { // public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
if (super.isApproved(authorizationRequest, userAuthentication)) { // if (super.isApproved(authorizationRequest, userAuthentication)) {
return true; // return true;
} // }
if (!userAuthentication.isAuthenticated()) { // if (!userAuthentication.isAuthenticated()) {
return false; // return false;
} // }
//
OauthClientDetails clientDetails = oauthService.loadOauthClientDetails(authorizationRequest.getClientId()); // OauthClientDetails clientDetails = oauthService.loadOauthClientDetails(authorizationRequest.getClientId());
return clientDetails != null && clientDetails.trusted(); // return clientDetails != null && clientDetails.trusted();
//
} // }
public void setOauthService(OauthService oauthService) { public void setOauthService(OauthService oauthService) {
this.oauthService = oauthService; this.oauthService = oauthService;

View File

@ -2,8 +2,8 @@ package com.monkeyk.sos.config;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.common.util.RandomValueStringGenerator; //import org.springframework.security.oauth2.common.util.RandomValueStringGenerator;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; //import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import java.util.Map; import java.util.Map;
@ -22,9 +22,9 @@ class JWTTokenStoreConfigurationTest {
@Test @Test
void keyTest() throws Exception { void keyTest() throws Exception {
RandomValueStringGenerator randomValueStringGenerator = new RandomValueStringGenerator(32); // RandomValueStringGenerator randomValueStringGenerator = new RandomValueStringGenerator(32);
String verifierKey = randomValueStringGenerator.generate(); // String verifierKey = randomValueStringGenerator.generate();
assertNotNull(verifierKey); // assertNotNull(verifierKey);
// System.out.println(verifierKey); // System.out.println(verifierKey);
} }
@ -33,13 +33,13 @@ class JWTTokenStoreConfigurationTest {
@Test @Test
void testJwtAccessTokenConverter() throws Exception { void testJwtAccessTokenConverter() throws Exception {
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter(); // JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
jwtAccessTokenConverter.setSigningKey("IH6S2dhCEMwGr7uE4fBakSuDh9SoIrRa"); // jwtAccessTokenConverter.setSigningKey("IH6S2dhCEMwGr7uE4fBakSuDh9SoIrRa");
jwtAccessTokenConverter.afterPropertiesSet(); // jwtAccessTokenConverter.afterPropertiesSet();
//
assertFalse(jwtAccessTokenConverter.isPublic()); // assertFalse(jwtAccessTokenConverter.isPublic());
Map<String, String> key = jwtAccessTokenConverter.getKey(); // Map<String, String> key = jwtAccessTokenConverter.getKey();
assertNotNull(key); // assertNotNull(key);
} }

View File

@ -3,7 +3,7 @@ package com.monkeyk.sos.service.business;
import com.monkeyk.sos.service.dto.AccessTokenDto; import com.monkeyk.sos.service.dto.AccessTokenDto;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable; 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.HashMap;
import java.util.Map; import java.util.Map;
@ -54,13 +54,13 @@ public class ClientCredentialsInlineAccessTokenInvokerTest extends AbstractInlin
params.put("scope", "read"); params.put("scope", "read");
ClientCredentialsInlineAccessTokenInvoker accessTokenInvoker = new ClientCredentialsInlineAccessTokenInvoker(); // ClientCredentialsInlineAccessTokenInvoker accessTokenInvoker = new ClientCredentialsInlineAccessTokenInvoker();
assertThrows(NoSuchClientException.class, () -> { // assertThrows(NoSuchClientException.class, () -> {
final AccessTokenDto accessTokenDto = accessTokenInvoker.invoke(params); // final AccessTokenDto accessTokenDto = accessTokenInvoker.invoke(params);
//
assertNotNull(accessTokenDto); // assertNotNull(accessTokenDto);
assertNotNull(accessTokenDto.getAccessToken()); // assertNotNull(accessTokenDto.getAccessToken());
}); // });
// System.out.println(accessTokenDto); // System.out.println(accessTokenDto);

View File

@ -2,7 +2,7 @@ package com.monkeyk.sos.service.business;
import com.monkeyk.sos.service.dto.AccessTokenDto; import com.monkeyk.sos.service.dto.AccessTokenDto;
import org.junit.jupiter.api.Test; 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.HashMap;
import java.util.Map; import java.util.Map;
@ -61,12 +61,12 @@ class PasswordInlineAccessTokenInvokerTest extends AbstractInlineAccessTokenInvo
params.put("username", "useraaa"); params.put("username", "useraaa");
params.put("password", "password"); params.put("password", "password");
PasswordInlineAccessTokenInvoker accessTokenInvoker = new PasswordInlineAccessTokenInvoker(); // PasswordInlineAccessTokenInvoker accessTokenInvoker = new PasswordInlineAccessTokenInvoker();
assertThrows(InvalidGrantException.class, () -> { // assertThrows(InvalidGrantException.class, () -> {
final AccessTokenDto tokenDto = accessTokenInvoker.invoke(params); // final AccessTokenDto tokenDto = accessTokenInvoker.invoke(params);
//
assertNull(tokenDto); // assertNull(tokenDto);
}); // });
// System.out.println(accessTokenDto); // System.out.println(accessTokenDto);

View File

@ -2,7 +2,7 @@ package com.monkeyk.sos.service.business;
import com.monkeyk.sos.service.dto.AccessTokenDto; import com.monkeyk.sos.service.dto.AccessTokenDto;
import org.junit.jupiter.api.Test; 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.HashMap;
import java.util.Map; import java.util.Map;
@ -96,18 +96,18 @@ class RefreshTokenInlineAccessTokenInvokerTest extends AbstractInlineAccessToken
params2.put("refresh_token", tokenDto.getRefreshToken() + "sss"); params2.put("refresh_token", tokenDto.getRefreshToken() + "sss");
RefreshTokenInlineAccessTokenInvoker refreshTokenInlineAccessTokenInvoker = new RefreshTokenInlineAccessTokenInvoker(); // RefreshTokenInlineAccessTokenInvoker refreshTokenInlineAccessTokenInvoker = new RefreshTokenInlineAccessTokenInvoker();
assertThrows(InvalidTokenException.class, () -> { // assertThrows(InvalidTokenException.class, () -> {
final AccessTokenDto accessTokenDto = refreshTokenInlineAccessTokenInvoker.invoke(params2); // final AccessTokenDto accessTokenDto = refreshTokenInlineAccessTokenInvoker.invoke(params2);
//
//
assertNotNull(accessTokenDto); // assertNotNull(accessTokenDto);
assertNotNull(accessTokenDto.getAccessToken()); // assertNotNull(accessTokenDto.getAccessToken());
//
assertNotEquals(accessTokenDto.getAccessToken(), tokenDto.getAccessToken()); // assertNotEquals(accessTokenDto.getAccessToken(), tokenDto.getAccessToken());
assertNotEquals(accessTokenDto.getRefreshToken(), tokenDto.getRefreshToken()); // assertNotEquals(accessTokenDto.getRefreshToken(), tokenDto.getRefreshToken());
//
}); // });
} }