近期在项目需求上需要用到不同的用户类型,并且不同的用户,check_token 返回的信息也需要不一样
在这里例子发上来,希望能够帮到别人,同时也给自己留个记录
首先,先添加依赖
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
1.8
Hoxton.SR8
org.springframework.boot
spring-boot-starter-security
org.springframework.cloud
spring-cloud-starter-oauth2
org.apache.tomcat.embed
tomcat-embed-core
9.0.45
provided
使用mysql来保存客户端信息,加入mysql依赖
org.springframework
spring-jdbc
com.alibaba
druid-spring-boot-starter
1.1.13
mysql
mysql-connector-java
application.properties
server.port=8080
#datasource config
spring.datasource.url=jdbc:mysql://localhost:3306/oauth_test?useUnicode=true&characterEncoding=utf8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=
这里主要是为了让后续流程可以获取到userType的值
public class CustomUser extends User {
private String userType;
public CustomUser(String username, String password, String userType, Collection extends GrantedAuthority> authorities) {
super(username, password, authorities);
this.userType = userType;
}
public String getUserType() {
return userType;
}
public CustomUser withUserType(String userType) {
this.userType = userType;
return this;
}
}
public class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) {
return new User(username, null, null);
}
public UserDetails loadUserByUsername(String username, String userType) {
// TODO: 2021/5/12 由于合理只是测试,所以无论传入什么用户名,只要密码是123456,都能过
//獲取該用戶的密碼(测试密码)
String password = "$2a$10$u2.TGFJuzx13g1lDXoy.KeUQU8s6/HoqTaHCqWMV8/eeyLUEyYs9W";
//獲取該用戶的權限資料(测试权限资料)
List authorityStrList = new ArrayList<>();
authorityStrList.add("authorityTest");
List authorities =new ArrayList<>();
Optional.ofNullable(authorityStrList).orElse(new ArrayList<>()).forEach(authorityStr->{
authorities.add(new SimpleGrantedAuthority(authorityStr));
});
return new CustomUser(username, password, userType, authorities);
}
}
当授权类型为授权码模式时,需要使用。
public class CustomWebAuthenticationDetails extends WebAuthenticationDetails {
private final String userType;
public CustomWebAuthenticationDetails(HttpServletRequest request) {
super(request);
userType = request.getParameter("userType");
}
public String getUserType() {
return userType;
}
}
由于需要在授权的过程中使用我们新添加的方法UserDetails loadUserByUsername(String username, String userType),所以需要自定义AbstractUserDetailsAuthenticationProvider ,并重写UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
public class CustomUserDetailsAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
private PasswordEncoder passwordEncoder;
private volatile String userNotFoundEncodedPassword;
private CustomUserDetailsService userDetailsService;
private UserDetailsPasswordService userDetailsPasswordService;
public CustomUserDetailsAuthenticationProvider() {
setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
}
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
if (authentication.getCredentials() == null) {
logger.debug("Authentication failed: no credentials provided");
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
String presentedPassword = authentication.getCredentials().toString();
if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
logger.debug("Authentication failed: password does not match stored value");
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
}
protected void doAfterPropertiesSet() {
Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");
}
protected final UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
prepareTimingAttackProtection();
try {
String userType = "";
//獲取用戶類型
if (authentication.getDetails() instanceof LinkedHashMap) {
//
Map map = (Map) authentication.getDetails();
userType = map.get("userType");
} else if (authentication.getDetails() instanceof WebAuthenticationDetails) {
//grant_type=code时
CustomWebAuthenticationDetails webAuthenticationDetails = (CustomWebAuthenticationDetails) authentication.getDetails();
userType = webAuthenticationDetails.getUserType();
}
UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username, userType);
if (loadedUser == null) {
throw new InternalAuthenticationServiceException(
"UserDetailsService returned null, which is an interface contract violation");
}
return loadedUser;
} catch (UsernameNotFoundException ex) {
mitigateAgainstTimingAttack(authentication);
throw ex;
} catch (InternalAuthenticationServiceException ex) {
throw ex;
} catch (Exception ex) {
throw new InternalAuthenticationServiceException(ex.getMessage(), ex);
}
}
@Override
protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
boolean upgradeEncoding = this.userDetailsPasswordService != null
&& this.passwordEncoder.upgradeEncoding(user.getPassword());
if (upgradeEncoding) {
String presentedPassword = authentication.getCredentials().toString();
String newPassword = this.passwordEncoder.encode(presentedPassword);
user = this.userDetailsPasswordService.updatePassword(user, newPassword);
}
return super.createSuccessAuthentication(principal, authentication, user);
}
private void prepareTimingAttackProtection() {
if (this.userNotFoundEncodedPassword == null) {
this.userNotFoundEncodedPassword = this.passwordEncoder.encode(USER_NOT_FOUND_PASSWORD);
}
}
private void mitigateAgainstTimingAttack(UsernamePasswordAuthenticationToken authentication) {
if (authentication.getCredentials() != null) {
String presentedPassword = authentication.getCredentials().toString();
this.passwordEncoder.matches(presentedPassword, this.userNotFoundEncodedPassword);
}
}
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
this.passwordEncoder = passwordEncoder;
this.userNotFoundEncodedPassword = null;
}
protected PasswordEncoder getPasswordEncoder() {
return passwordEncoder;
}
public void setUserDetailsService(CustomUserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
protected CustomUserDetailsService getUserDetailsService() {
return userDetailsService;
}
public void setUserDetailsPasswordService(
UserDetailsPasswordService userDetailsPasswordService) {
this.userDetailsPasswordService = userDetailsPasswordService;
}
}
这里例子使用InMemoryTokenStore
public interface CustomTokenStore extends TokenStore {
Map readUserInfo(String tokenValue);
}
public class CustomInMemoryTokenStore extends InMemoryTokenStore implements CustomTokenStore {
private final ConcurrentHashMap> userInfoStore = new ConcurrentHashMap();
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
super.storeAccessToken(token, authentication);
CustomUser map = (CustomUser) authentication.getUserAuthentication().getPrincipal();
String userType = map.getUserType();
String username = map.getUsername();
Map userInfo = new HashMap<>();
userInfo.put("userDetails", "testUserDetailInfo");
userInfoStore.put(token.getValue(), userInfo);
}
@Override
public Map readUserInfo(String token) {
return this.userInfoStore.get(token);
}
@Override
public void removeAccessToken(OAuth2AccessToken accessToken) {
super.removeAccessToken(accessToken);
userInfoStore.remove(accessToken.getValue());
}
@Override
public void removeAccessToken(String tokenValue) {
super.removeAccessToken(tokenValue);
userInfoStore.remove(tokenValue);
}
}
public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {
private CustomTokenStore customTokenStore;
public CustomAccessTokenConverter(CustomTokenStore customTokenStore) {
this.customTokenStore = customTokenStore;
}
/**
* 將額外信息(用戶信息)添加到token中
*
* @return
*/
@Override
public Map convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
DefaultOAuth2AccessToken defaultOAuth2AccessToken = new DefaultOAuth2AccessToken(token);
defaultOAuth2AccessToken.setAdditionalInformation(customTokenStore.readUserInfo(token.getValue()));
Map response = super.convertAccessToken(defaultOAuth2AccessToken, authentication);
return response;
}
}
@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private DataSource dataSource;
@Autowired
private CustomTokenStore customTokenStore;
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.realm("oauth2-resources").tokenKeyAccess("permitAll()").checkTokenAccess("permitAll()")
.allowFormAuthenticationForClients();
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.authenticationManager(authenticationManager)
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
.accessTokenConverter(new CustomAccessTokenConverter(customTokenStore))
.tokenStore(customTokenStore);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
}
@Component
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationProvider authenticationProvider;
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.requestMatchers().antMatchers("/oauth/**", "/login/**", "/logout/**")
.and().authorizeRequests().antMatchers("/oauth/**").authenticated()
.and().formLogin().permitAll();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(authenticationProvider);
}
@Override
protected CustomUserDetailsService userDetailsService() {
return customUserDetailsService;
}
}
@Configuration
public class CustomServiceConfiguration {
@Bean
public CustomTokenStore customInMemoryTokenStore(DataSource dataSource) {
return new CustomInMemoryTokenStore();
}
@Bean
public AuthenticationProvider customAuthenticationProvider(CustomUserDetailsService customUserDetailsService) {
CustomUserDetailsAuthenticationProvider tmacsUserDetailsAuthenticationProvider = new CustomUserDetailsAuthenticationProvider();
tmacsUserDetailsAuthenticationProvider.setUserDetailsService(customUserDetailsService);
tmacsUserDetailsAuthenticationProvider.setHideUserNotFoundExceptions(false);
tmacsUserDetailsAuthenticationProvider.setPasswordEncoder(this.passwordEncoder());
return tmacsUserDetailsAuthenticationProvider;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public CustomUserDetailsService customUserDetailsService() {
return new CustomUserDetailsService();
}
}
http://127.0.0.1:8080/oauth/token?client_id=demoApp&client_secret=123456&username=test&password=123456&grant_type=password&userType=1
Response Body
{
"access_token": "9eb80e8d-50db-450e-a980-4887b5cb15a6",
"token_type": "bearer",
"refresh_token": "21dc5b10-261b-4fa8-9bb4-c43c9d9338bc",
"expires_in": 3571,
"scope": "all"
}
http://127.0.0.1:8080/oauth/check_token?token=9eb80e8d-50db-450e-a980-4887b5cb15a6
{
"aud": [
"oauth2-resource"
],
"user_name": "test",
"scope": [
"all"
],
"active": true,
"exp": 1620786779,
"userDetails": "testUserDetailInfo",
"authorities": [
"authorityTest"
],
"client_id": "demoApp"
}
相关源码可参照《spring oauth 多用户类型登录 例子》