refactor:oauth2功能重构

This commit is contained in:
haoxr 2020-09-18 18:03:00 +08:00
parent ab9fdf9a1b
commit 85bb9a2373
5 changed files with 44 additions and 87 deletions

View File

@ -1,27 +0,0 @@
package com.youlai.auth.component;
import com.youlai.auth.domain.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* JWT内容增强器
*/
@Component
public class JwtTokenEnhancer implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
User user =(User)authentication.getPrincipal();
Map<String,Object> map=new HashMap<>();
map.put("id", user.getId());
map.put("client_id", user.getClientId());
((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(map);
return accessToken;
}
}

View File

@ -1,7 +1,8 @@
package com.youlai.auth.config; package com.youlai.auth.config;
import com.youlai.auth.component.JwtTokenEnhancer; import com.youlai.auth.domain.User;
import com.youlai.auth.service.JdbcClientDetailsServiceImpl; import com.youlai.auth.service.JdbcClientDetailsServiceImpl;
import com.youlai.auth.service.UserDetailsServiceImpl;
import com.youlai.common.core.constant.AuthConstants; import com.youlai.common.core.constant.AuthConstants;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -10,7 +11,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 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.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
@ -26,7 +27,9 @@ import org.springframework.security.oauth2.provider.token.store.redis.RedisToken
import javax.sql.DataSource; import javax.sql.DataSource;
import java.security.KeyPair; import java.security.KeyPair;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* 认证服务器 * 认证服务器
@ -35,53 +38,38 @@ import java.util.List;
@EnableAuthorizationServer @EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired @Autowired
private PasswordEncoder passwordEncoder; private DataSource dataSource;
@Autowired @Autowired
private AuthenticationManager authenticationManager; private AuthenticationManager authenticationManager;
@Autowired @Autowired
private JwtTokenEnhancer jwtTokenEnhancer; private UserDetailsServiceImpl userDetailsService;
@Autowired @Autowired
private RedisConnectionFactory redisConnectionFactory; private RedisConnectionFactory redisConnectionFactory;
@Autowired
private DataSource dataSource;
/** /**
* 配置客户端详情 * 配置客户端详情
*
* @param clients
* @throws Exception
*/ */
@Override @Override
@SneakyThrows @SneakyThrows
public void configure(ClientDetailsServiceConfigurer clients) throws Exception { public void configure(ClientDetailsServiceConfigurer clients) {
/*clients.inMemory() JdbcClientDetailsServiceImpl jdbcClientDetailsService = new JdbcClientDetailsServiceImpl(dataSource);
.withClient("client") jdbcClientDetailsService.setFindClientDetailsSql(AuthConstants.FIND_CLIENT_DETAILS_SQL);
.secret(passwordEncoder.encode("123456")) jdbcClientDetailsService.setSelectClientDetailsSql(AuthConstants.SELECT_CLIENT_DETAILS_SQL);
.scopes("all")
.authorizedGrantTypes("password", "refresh_token")
.accessTokenValiditySeconds(3600)
.refreshTokenValiditySeconds(86400);*/
JdbcClientDetailsServiceImpl jdbcClientDetailsService=new JdbcClientDetailsServiceImpl(dataSource);
jdbcClientDetailsService.setFindClientDetailsSql(AuthConstants.CLIENT_DETAILS_FIND_SQL);
jdbcClientDetailsService.setSelectClientDetailsSql(AuthConstants.CLIENT_DETAILS_SELECT_SQL);
clients.withClientDetails(jdbcClientDetailsService); clients.withClientDetails(jdbcClientDetailsService);
} }
/** /**
* 配置令牌端点的安全约束 * 配置令牌端点的安全约束
*/ */
@Override @Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) { public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
// 配置JWT的内容增强器
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
List<TokenEnhancer> tokenEnhancers = new ArrayList<>(); List<TokenEnhancer> tokenEnhancers = new ArrayList<>();
tokenEnhancers.add(jwtTokenEnhancer); tokenEnhancers.add(tokenEnhancer());
tokenEnhancers.add(jwtAccessTokenConverter()); tokenEnhancers.add(jwtAccessTokenConverter());
tokenEnhancerChain.setTokenEnhancers(tokenEnhancers); tokenEnhancerChain.setTokenEnhancers(tokenEnhancers);
@ -89,17 +77,10 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
.accessTokenConverter(jwtAccessTokenConverter()) .accessTokenConverter(jwtAccessTokenConverter())
.tokenEnhancer(tokenEnhancerChain) .tokenEnhancer(tokenEnhancerChain)
.tokenStore(tokenStore()) .tokenStore(tokenStore())
; .userDetailsService(userDetailsService);
} }
@Bean
public TokenStore tokenStore() {
RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
tokenStore.setPrefix(AuthConstants.OAUTH2_TOKEN_PREFIX);
return tokenStore;
}
/** /**
* 允许表单认证 * 允许表单认证
@ -129,4 +110,29 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
KeyPair keyPair = factory.getKeyPair("youlai", "123456".toCharArray()); KeyPair keyPair = factory.getKeyPair("youlai", "123456".toCharArray());
return keyPair; return keyPair;
} }
@Bean
public TokenStore tokenStore() {
RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
tokenStore.setPrefix(AuthConstants.OAUTH2_TOKEN_PREFIX);
return tokenStore;
}
/**
* JWT内容增强
*/
@Bean
public TokenEnhancer tokenEnhancer() {
return (accessToken, authentication) -> {
Map<String, Object> map = new HashMap<>(2);
User user = (User) authentication.getUserAuthentication().getPrincipal();
map.put(AuthConstants.JWT_USER_ID_KEY, user.getId());
map.put(AuthConstants.JWT_CLIENT_ID_KEY, user.getClientId());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
return accessToken;
};
}
} }

View File

@ -1,17 +1,12 @@
package com.youlai.auth.config; package com.youlai.auth.config;
import com.youlai.auth.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest; import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
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.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
@ -19,9 +14,6 @@ import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity @EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() http.authorizeRequests()
@ -31,27 +23,13 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.anyRequest().permitAll(); .anyRequest().permitAll();
} }
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean @Bean
public AuthenticationManager authenticationManagerBean() throws Exception { public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean(); return super.authenticationManagerBean();
} }
@Override
protected void configure(AuthenticationManagerBuilder auth){
auth.authenticationProvider(daoAuthenticationProvider());
}
@Bean @Bean
public DaoAuthenticationProvider daoAuthenticationProvider() { public PasswordEncoder passwordEncoder() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); return PasswordEncoderFactories.createDelegatingPasswordEncoder();
provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(passwordEncoder());
provider.setHideUserNotFoundExceptions(false);
return provider;
} }
} }

View File

@ -14,7 +14,7 @@ import java.util.Map;
*/ */
@RestController @RestController
@AllArgsConstructor @AllArgsConstructor
public class KeyPairController { public class PublicKeyController {
private KeyPair keyPair; private KeyPair keyPair;