Browse Source

token里面加入user_id,资源服务器解析

gaodm 6 years ago
parent
commit
1aa46a6a0e

+ 31 - 0
uaa-service/src/main/java/com/diagbot/config/CustomTokenEnhancer.java

@@ -0,0 +1,31 @@
+package com.diagbot.config;
+
+import com.diagbot.entity.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 java.util.HashMap;
+import java.util.Map;
+
+
+/**
+ *
+ * token生成携带的信息
+ *
+ */
+public class CustomTokenEnhancer implements TokenEnhancer {
+
+	@Override
+	public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
+		final Map<String, Object> additionalInfo = new HashMap<>();
+		User user = (User) authentication.getUserAuthentication().getPrincipal();
+		additionalInfo.put("user_id", user.getId());
+//		additionalInfo.put("username", user.getUsername());
+//		additionalInfo.put("authorities", user.getAuthorities());
+		((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
+		return accessToken;
+	}
+
+}

+ 22 - 1
uaa-service/src/main/java/com/diagbot/config/OAuth2Config.java

@@ -10,11 +10,15 @@ import org.springframework.security.oauth2.config.annotation.configurers.ClientD
 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;
 import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
 import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
+import org.springframework.security.oauth2.provider.token.TokenEnhancer;
+import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
 import org.springframework.security.oauth2.provider.token.TokenStore;
 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.JwtAccessTokenConverter;
 import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
 import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
 import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
 import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
 
 
+import java.util.Arrays;
+
 /**
 /**
  * @Description: OAuth2授权认证配置类
  * @Description: OAuth2授权认证配置类
  * @author: gaodm
  * @author: gaodm
@@ -34,9 +38,26 @@ public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
                 .accessTokenValiditySeconds(24*3600);//24小时过期
                 .accessTokenValiditySeconds(24*3600);//24小时过期
     }
     }
 
 
+    /**
+     * 注入自定义token生成方式
+     *
+     * @return
+     */
+    @Bean
+    public TokenEnhancer customerEnhancer() {
+        return new CustomTokenEnhancer();
+    }
+
     @Override
     @Override
     public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
     public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
-        endpoints.tokenStore(tokenStore()).tokenEnhancer(jwtTokenEnhancer()).authenticationManager(authenticationManager);
+        //指定认证管理器
+        endpoints.authenticationManager(authenticationManager);
+        //指定token存储位置
+        endpoints.tokenStore(tokenStore());
+        // 自定义token生成方式
+        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
+        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(customerEnhancer(), jwtTokenEnhancer()));
+        endpoints.tokenEnhancer(tokenEnhancerChain);
     }
     }
 
 
     @Autowired
     @Autowired

+ 19 - 0
user-service/src/main/java/com/diagbot/config/CustomAccessTokenConverter.java

@@ -0,0 +1,19 @@
+package com.diagbot.config;
+
+import org.springframework.security.oauth2.provider.OAuth2Authentication;
+import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
+import org.springframework.stereotype.Component;
+
+import java.util.Map;
+
+@Component
+public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {
+
+    @Override
+    public OAuth2Authentication extractAuthentication(Map<String, ?> claims) {
+        OAuth2Authentication authentication = super.extractAuthentication(claims);
+        authentication.setDetails(claims);
+        return authentication;
+    }
+
+}

+ 3 - 2
user-service/src/main/java/com/diagbot/config/JwtConfiguration.java

@@ -21,14 +21,14 @@ import java.io.IOException;
 @Configuration
 @Configuration
 public class JwtConfiguration {
 public class JwtConfiguration {
     @Autowired
     @Autowired
-    JwtAccessTokenConverter jwtAccessTokenConverter;
+    private CustomAccessTokenConverter customAccessTokenConverter;
 
 
     @Bean
     @Bean
     @Qualifier("tokenStore")
     @Qualifier("tokenStore")
     public TokenStore tokenStore() {
     public TokenStore tokenStore() {
 
 
         System.out.println("Created JwtTokenStore");
         System.out.println("Created JwtTokenStore");
-        return new JwtTokenStore(jwtAccessTokenConverter);
+        return new JwtTokenStore(jwtTokenEnhancer());
     }
     }
 
 
     @Bean
     @Bean
@@ -42,6 +42,7 @@ public class JwtConfiguration {
             throw new RuntimeException(e);
             throw new RuntimeException(e);
         }
         }
         converter.setVerifierKey(publicKey);
         converter.setVerifierKey(publicKey);
+        converter.setAccessTokenConverter(customAccessTokenConverter);
         return converter;
         return converter;
     }
     }
 }
 }

+ 2 - 2
user-service/src/main/java/com/diagbot/facade/UserFacade.java

@@ -74,7 +74,7 @@ public class UserFacade extends UserServiceImpl {
         String entryPassword= passwordEncoder.encode(user.getPassword());
         String entryPassword= passwordEncoder.encode(user.getPassword());
         user.setPassword(entryPassword);
         user.setPassword(entryPassword);
         user.setGmtCreate(new Date());
         user.setGmtCreate(new Date());
-        user.setCreator(this.getUserInfo(UserUtils.getCurrentPrinciple()).getId().toString());
+        user.setCreator(UserUtils.getCurrentPrincipleID());
         super.save(user);
         super.save(user);
         return user;
         return user;
     }
     }
@@ -85,7 +85,7 @@ public class UserFacade extends UserServiceImpl {
         String entryPassword= passwordEncoder.encode(user.getPassword());
         String entryPassword= passwordEncoder.encode(user.getPassword());
         user.setPassword(entryPassword);
         user.setPassword(entryPassword);
         user.setGmtModified(new Date());
         user.setGmtModified(new Date());
-        user.setModifier(this.getUserInfo(UserUtils.getCurrentPrinciple()).getId().toString());
+        user.setModifier(UserUtils.getCurrentPrincipleID());
         super.updateById(user);
         super.updateById(user);
         return user;
         return user;
     }
     }

+ 0 - 3
user-service/src/main/java/com/diagbot/service/impl/UserServiceImpl.java

@@ -5,10 +5,7 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.diagbot.entity.User;
 import com.diagbot.entity.User;
 import com.diagbot.mapper.UserMapper;
 import com.diagbot.mapper.UserMapper;
 import com.diagbot.service.UserService;
 import com.diagbot.service.UserService;
-import org.apache.ibatis.annotations.Param;
-import org.springframework.cache.annotation.Cacheable;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
 
 
 import java.util.List;
 import java.util.List;
 import java.util.Map;
 import java.util.Map;

+ 12 - 0
user-service/src/main/java/com/diagbot/util/UserUtils.java

@@ -4,8 +4,10 @@ package com.diagbot.util;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.authority.SimpleGrantedAuthority;
 import org.springframework.security.core.authority.SimpleGrantedAuthority;
 import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
 
 
 import java.util.List;
 import java.util.List;
+import java.util.Map;
 
 
 /**
 /**
  * @Description: 用户工具类
  * @Description: 用户工具类
@@ -32,6 +34,16 @@ public class UserUtils {
         return (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
         return (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
     }
     }
 
 
+    /**
+     * 获取当前请求的用户ID
+     * @return
+     */
+    public static String getCurrentPrincipleID() {
+        OAuth2AuthenticationDetails oauthDetails = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
+        Map<String, Object> details = (Map<String, Object>) oauthDetails.getDecodedDetails();
+        return details.get("user_id").toString();
+    }
+
     /**
     /**
      * 判读当前token用户是否为接口所需的参数username
      * 判读当前token用户是否为接口所需的参数username
      *
      *