소스 검색

验证和刷新token接口服务

gaodm 6 년 전
부모
커밋
eabbbf5f42

+ 15 - 3
uaa-service/src/main/java/com/diagbot/config/OAuth2Configurer.java

@@ -1,5 +1,6 @@
 package com.diagbot.config;
 
+import com.diagbot.service.UrlUserService;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Qualifier;
 import org.springframework.context.annotation.Bean;
@@ -10,6 +11,8 @@ 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.EnableAuthorizationServer;
 import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
+import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
+import org.springframework.security.oauth2.provider.ClientDetailsService;
 import org.springframework.security.oauth2.provider.token.TokenEnhancer;
 import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
 import org.springframework.security.oauth2.provider.token.TokenStore;
@@ -27,6 +30,8 @@ import java.util.Arrays;
 @Configuration
 @EnableAuthorizationServer
 public class OAuth2Configurer extends AuthorizationServerConfigurerAdapter {
+    @Autowired
+    private UrlUserService urlUserService;
     @Override
     public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
         clients.inMemory()
@@ -35,8 +40,8 @@ public class OAuth2Configurer extends AuthorizationServerConfigurerAdapter {
                 .scopes("service")
                 .autoApprove(true)
                 .authorizedGrantTypes("implicit", "refresh_token", "password", "authorization_code")
-                .accessTokenValiditySeconds(30 * 24 * 3600)
-                .refreshTokenValiditySeconds(30 * 24 * 3600);//todo gaodm 现改为365天,正式改为24小时过期
+                .accessTokenValiditySeconds(24 * 3600)
+                .refreshTokenValiditySeconds(30 * 24 * 3600);
     }
 
     /**
@@ -52,7 +57,7 @@ public class OAuth2Configurer extends AuthorizationServerConfigurerAdapter {
     @Override
     public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
         //指定认证管理器
-        endpoints.authenticationManager(authenticationManager);
+        endpoints.authenticationManager(authenticationManager).userDetailsService(urlUserService);
         //指定token存储位置
         endpoints.tokenStore(tokenStore());
         // 自定义token生成方式
@@ -61,6 +66,13 @@ public class OAuth2Configurer extends AuthorizationServerConfigurerAdapter {
         endpoints.tokenEnhancer(tokenEnhancerChain);
     }
 
+    @Override
+    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
+        security.tokenKeyAccess("permitAll()")
+                .checkTokenAccess("isAuthenticated()")
+                .allowFormAuthenticationForClients();
+    }
+
     @Autowired
     @Qualifier("authenticationManagerBean")
     private AuthenticationManager authenticationManager;

+ 8 - 2
user-service/src/main/java/com/diagbot/client/AuthServiceClient.java

@@ -3,6 +3,7 @@ package com.diagbot.client;
 import com.diagbot.client.hystrix.AuthServiceHystrix;
 import com.diagbot.entity.JWT;
 import org.springframework.cloud.openfeign.FeignClient;
+import org.springframework.security.oauth2.common.OAuth2AccessToken;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestHeader;
 import org.springframework.web.bind.annotation.RequestParam;
@@ -17,8 +18,13 @@ import org.springframework.web.bind.annotation.RequestParam;
 public interface AuthServiceClient {
 
     @PostMapping(value = "/oauth/token")
-    JWT getToken(@RequestHeader(value = "Authorization") String authorization, @RequestParam("grant_type") String type,
-                 @RequestParam("username") String username, @RequestParam("password") String password);
+    JWT getToken(@RequestHeader(value = "Authorization") String authorization, @RequestParam("grant_type") String type, @RequestParam("username") String username, @RequestParam("password") String password);
+
+    @PostMapping(value = "/oauth/token")
+    JWT refreshToken(@RequestHeader(value = "Authorization") String authorization, @RequestParam("grant_type") String type, @RequestParam("refresh_token") String refreshToken);
+
+    @PostMapping(value = "/oauth/check_token")
+    OAuth2AccessToken checkToken(@RequestHeader(value = "Authorization") String authorization, @RequestParam("token") String token);
 }
 
 

+ 13 - 0
user-service/src/main/java/com/diagbot/client/hystrix/AuthServiceHystrix.java

@@ -4,6 +4,7 @@ package com.diagbot.client.hystrix;
 import com.diagbot.client.AuthServiceClient;
 import com.diagbot.entity.JWT;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.security.oauth2.common.OAuth2AccessToken;
 import org.springframework.stereotype.Component;
 
 /**
@@ -19,4 +20,16 @@ public class AuthServiceHystrix implements AuthServiceClient {
         log.error("【hystrix】调用{}异常", "getToken");
         return null;
     }
+
+    @Override
+    public JWT refreshToken(String authorization, String type, String refreshToken) {
+        log.error("【hystrix】调用{}异常", "refreshToken");
+        return null;
+    }
+
+    @Override
+    public OAuth2AccessToken checkToken(String authorization, String token){
+        log.error("【hystrix】调用{}异常", "checkToken");
+        return null;
+    }
 }

+ 2 - 0
user-service/src/main/java/com/diagbot/config/ResourceServerConfigurer.java

@@ -26,6 +26,8 @@ public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {
                 .csrf().disable()
                 .authorizeRequests()
                 .regexMatchers(".*swagger.*", ".*v2.*", ".*webjars.*", "/user/getJwt.*", "/user/registry.*", "/user/test.*", "/druid.*", "/actuator.*", "/hystrix.*", "/hi.*", "/test.*").permitAll()
+                .antMatchers("/user/refreshJwt").permitAll()
+                .antMatchers("/user/checkToken").permitAll()
                 .antMatchers("/userver/getImgVerification").permitAll()
                 .antMatchers("/userver/verifyImgVerification").permitAll()
                 .antMatchers("/userver/getSmsWithRegister").permitAll()

+ 2 - 0
user-service/src/main/java/com/diagbot/config/security/UrlAccessDecisionManager.java

@@ -39,6 +39,8 @@ public class UrlAccessDecisionManager implements AccessDecisionManager {
                     || matchers("/hystrix/**", request)
                     || matchers("/hi/**", request)
                     || matchers("/test/**", request)
+                    || matchers("/user/refreshJwt", request)
+                    || matchers("/user/checkToken", request)
                     || matchers("/userver/getImgVerification", request)
                     || matchers("/userver/verifyImgVerification", request)
                     || matchers("/userver/getSmsWithRegister", request)

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

@@ -48,6 +48,7 @@ import com.diagbot.vo.UserSaveVO;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.security.crypto.factory.PasswordEncoderFactories;
 import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.oauth2.common.OAuth2AccessToken;
 import org.springframework.stereotype.Component;
 
 import java.io.Serializable;
@@ -243,7 +244,7 @@ public class UserFacade extends UserServiceImpl {
         List<MenuWrapper> menuList = menuFacade.getByRole(user.getId());
         Map<Long, List<MenuWrapper>> menuMap = EntityUtil.makeEntityListMap(menuList, "parentId");
         List<MenuWrapper> menuRes = menuMap.get(-1L);
-        for(MenuWrapper bean : menuRes) {
+        for (MenuWrapper bean : menuRes) {
             getSonMenu(bean, menuMap);
         }
         data.setMenuWrappers(menuRes);
@@ -258,7 +259,7 @@ public class UserFacade extends UserServiceImpl {
      * @param password 密码
      * @return jwt
      */
-    public JwtDTO  getJwt(String username, String password) {
+    public JwtDTO getJwt(String username, String password) {
         JwtDTO data = new JwtDTO();
         if (StringUtil.isBlank(username)) {
             throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
@@ -277,25 +278,71 @@ public class UserFacade extends UserServiceImpl {
             throw new CommonException(ServiceErrorCode.USER_PASSWORD_ERROR);
         }
         JWT jwt = authServiceClient.getToken("Basic dWFhLXNlcnZpY2U6MTIzNDU2", "password", username, password);
+        if (null == jwt) {
+            throw new CommonException(ServiceErrorCode.GET_TOKEN_FAIL);
+        }
         data.setAccessToken(jwt.getAccess_token());
         data.setRefreshToken(jwt.getRefresh_token());
         data.setType(user.getType());
         return data;
     }
 
+    /**
+     * 刷新jwt
+     *
+     * @param refreshToken
+     * @return jwt
+     */
+    public JwtDTO refreshJwt(String refreshToken) {
+        JwtDTO data = new JwtDTO();
+        if (StringUtil.isBlank(refreshToken)) {
+            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
+                    "刷新令牌不能为空!");
+        }
+
+        JWT jwt = authServiceClient.refreshToken("Basic dWFhLXNlcnZpY2U6MTIzNDU2", "refresh_token", refreshToken);
+        if (null == jwt) {
+            throw new CommonException(ServiceErrorCode.GET_TOKEN_FAIL);
+        }
+        data.setAccessToken(jwt.getAccess_token());
+        data.setRefreshToken(jwt.getRefresh_token());
+        return data;
+    }
+
+
+    /**
+     * 验证jwt
+     *
+     * @param token
+     * @return jwt
+     */
+    public OAuth2AccessToken checkToken(String token) {
+        if (StringUtil.isBlank(token)) {
+            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
+                    "令牌不能为空!");
+        }
+
+        OAuth2AccessToken jwt = authServiceClient.checkToken("Basic dWFhLXNlcnZpY2U6MTIzNDU2", token);
+        if (null == jwt) {
+            throw new CommonException(ServiceErrorCode.GET_TOKEN_FAIL);
+        }
+        return jwt;
+    }
+
 
     /**
      * 递归获取菜单结构
-     * @param menu 当前菜单
+     *
+     * @param menu    当前菜单
      * @param menuMap 菜单集
      * @return 菜单结构
      */
     public List<MenuWrapper> getSonMenu(MenuWrapper menu, Map<Long, List<MenuWrapper>> menuMap) {
         List<MenuWrapper> res = new ArrayList<>();
         List<MenuWrapper> list = menuMap.get(menu.getId());
-        if(ListUtil.isNotEmpty(list)) {
+        if (ListUtil.isNotEmpty(list)) {
             menu.setSubMenuList(list);
-            for(MenuWrapper bean : list) {
+            for (MenuWrapper bean : list) {
                 getSonMenu(bean, menuMap);
             }
         }
@@ -463,9 +510,9 @@ public class UserFacade extends UserServiceImpl {
         getConsoleUserInfoDTO.setOrganizationName(organization.getName());
         getConsoleUserInfoDTO.setUserStatus(AuthStatusEnum.getName(userAuthentication.getStatus()));
 
-//        getConsoleUserInfoDTO.setUser(user);
-//        getConsoleUserInfoDTO.setOrganization(organization);
-//        getConsoleUserInfoDTO.setUserAuthentication(userAuthentication);
+        //        getConsoleUserInfoDTO.setUser(user);
+        //        getConsoleUserInfoDTO.setOrganization(organization);
+        //        getConsoleUserInfoDTO.setUserAuthentication(userAuthentication);
 
         return getConsoleUserInfoDTO;
     }
@@ -702,6 +749,7 @@ public class UserFacade extends UserServiceImpl {
 
     /**
      * 删除用户信息和机构信息
+     *
      * @param baseIdVO 参数
      * @return 删除用户信息和机构信息
      */
@@ -716,46 +764,46 @@ public class UserFacade extends UserServiceImpl {
         }
         return RespDTO.onSuc(res);
     }
+
     /**
-     * 
      * @param page
      * @param orgName
      * @param autStatus
      * @return 分页查询用户信息和机构信息开通产品
      */
-    public RespDTO<IPage<UserInfoDTO>> getUserOrganProductAlls(Page page, String orgName, Integer autStatus){
-    	
-    	 UserInfoDTO userInfo = new UserInfoDTO();
-         userInfo.setOrgName(orgName);
-         userInfo.setAutStatus(autStatus);
-         IPage<UserInfoDTO> user = selectUserInfoListPage(page, userInfo);
-         List<UserInfoDTO> userData = user.getRecords();
-         List<Long> userIds = new ArrayList<>();
-         for (UserInfoDTO userInfoDTO: userData){
-        	 Long userInfoId = userInfoDTO.getUserId();
-        	 userIds.add(userInfoId);
-         }
-         RespDTO<List<UserAndProdutUDTO>> InformationData = diagbotmanService.getInformationAvailableAll(userIds);
-         
-         if(InformationData == null || !"0".equals(InformationData.code) ) {
-             throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
-                     "获取所有开通信息失败");
-         }
+    public RespDTO<IPage<UserInfoDTO>> getUserOrganProductAlls(Page page, String orgName, Integer autStatus) {
+
+        UserInfoDTO userInfo = new UserInfoDTO();
+        userInfo.setOrgName(orgName);
+        userInfo.setAutStatus(autStatus);
+        IPage<UserInfoDTO> user = selectUserInfoListPage(page, userInfo);
+        List<UserInfoDTO> userData = user.getRecords();
+        List<Long> userIds = new ArrayList<>();
+        for (UserInfoDTO userInfoDTO : userData) {
+            Long userInfoId = userInfoDTO.getUserId();
+            userIds.add(userInfoId);
+        }
+        RespDTO<List<UserAndProdutUDTO>> InformationData = diagbotmanService.getInformationAvailableAll(userIds);
+
+        if (InformationData == null || !"0".equals(InformationData.code)) {
+            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
+                    "获取所有开通信息失败");
+        }
         Map<Long, List<UserAndProdutUDTO>> map = new HashMap<>();
         //获取所有用户开通的产品信息
         List<UserAndProdutUDTO> dataList = InformationData.data;
-        map = EntityUtil.makeEntityListMap(dataList,"userId");
-        if(map.size()>0){
-            for (UserInfoDTO userInfoDTO: userData){
+        map = EntityUtil.makeEntityListMap(dataList, "userId");
+        if (map.size() > 0) {
+            for (UserInfoDTO userInfoDTO : userData) {
                 List<UserAndProdutUDTO> userAndProdutUDTO = map.get(userInfoDTO.getUserId());
-                if(ListUtil.isNotEmpty(userAndProdutUDTO)){
+                if (ListUtil.isNotEmpty(userAndProdutUDTO)) {
                     userInfoDTO.setUserAndProdutUDTO(userAndProdutUDTO);
                 }
             }
         }
-       
-        System.out.println("===================="+GsonUtil.toJson(userData));
+
+        System.out.println("====================" + GsonUtil.toJson(userData));
         user.setRecords(userData);
-    	return RespDTO.onSuc(user);
+        return RespDTO.onSuc(user);
     }
 }

+ 15 - 0
user-service/src/main/java/com/diagbot/vo/JwtVO.java

@@ -0,0 +1,15 @@
+package com.diagbot.vo;
+
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * @Description:
+ * @author: gaodm
+ * @time: 2018/9/29 9:22
+ */
+@Getter
+@Setter
+public class JwtVO {
+    private String token;
+}

+ 20 - 0
user-service/src/main/java/com/diagbot/web/UserController.java

@@ -13,6 +13,7 @@ import com.diagbot.facade.PermissionFacade;
 import com.diagbot.facade.UserFacade;
 import com.diagbot.vo.AppkeySecretVO;
 import com.diagbot.vo.BaseIdVO;
+import com.diagbot.vo.JwtVO;
 import com.diagbot.vo.ResetPasswordVO;
 import com.diagbot.vo.UserInfoByIdPageVO;
 import com.diagbot.vo.UserLoginVO;
@@ -21,6 +22,7 @@ import com.diagbot.vo.UsernameVO;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.oauth2.common.OAuth2AccessToken;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;
@@ -76,6 +78,24 @@ public class UserController {
         return RespDTO.onSuc(data);
     }
 
+    @ApiOperation(value = "刷新jwt[by:zhoutg]",
+            notes = "refreshToken:刷新令牌,必填<br>")
+    @PostMapping("/refreshJwt")
+    @SysLogger("refreshJwt")
+    public RespDTO<JwtDTO> refreshJwt(@RequestBody JwtVO jwtVO) {
+        JwtDTO data = userFacade.refreshJwt(jwtVO.getToken());
+        return RespDTO.onSuc(data);
+    }
+
+    @ApiOperation(value = "验证Token[by:zhoutg]",
+            notes = "checkToken:令牌,必填<br>")
+    @PostMapping("/checkToken")
+    @SysLogger("checkToken")
+    public RespDTO<OAuth2AccessToken> checkToken(@RequestBody JwtVO jwtVO) {
+        OAuth2AccessToken data = userFacade.checkToken(jwtVO.getToken());
+        return RespDTO.onSuc(data);
+    }
+
 
     @ApiOperation(value = "获取用户、机构、菜单信息[by:zhoutg]",
             notes = "")