From 158d293dcae241cdb1b89db5dfcf3514ca23b443 Mon Sep 17 00:00:00 2001 From: wenc000 <450292408@qq.com> Date: Mon, 19 Aug 2019 15:50:12 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9Erefresh=5Ftoken=EF=BC=8C?= =?UTF-8?q?=E8=B0=83=E6=95=B4=E8=B5=84=E6=BA=90=E8=B0=83=E7=94=A8=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controller/apis/auth/AuthController.java | 15 ++++ .../controller/apis/menu/MenuController.java | 2 +- .../controller/apis/user/UserController.java | 6 +- .../department/IDepartmentService.java | 2 +- .../impl/DepartmentServiceImpl.java | 9 ++- .../oauth/service/menu/IMenuService.java | 2 +- .../service/menu/impl/MenuServiceImpl.java | 9 ++- .../oauth/service/user/IUserService.java | 6 +- .../service/user/impl/UserServiceImpl.java | 27 ++++--- .../common/plugin/utils/RestTemplateUtil.java | 45 ++++++++++- .../properties/OauthClientProperties.java | 81 +++++++++++++++++++ .../common/utils/authority/AuthorityUtil.java | 10 ++- 12 files changed, 186 insertions(+), 28 deletions(-) create mode 100644 cloud-common/src/main/java/com/cm/common/config/properties/OauthClientProperties.java diff --git a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/controller/apis/auth/AuthController.java b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/controller/apis/auth/AuthController.java index 63db1e0..4e4f433 100644 --- a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/controller/apis/auth/AuthController.java +++ b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/controller/apis/auth/AuthController.java @@ -2,15 +2,19 @@ package com.cm.common.plugin.oauth.controller.apis.auth; import com.cm.common.base.AbstractController; import com.cm.common.constants.ISystemConstant; +import com.cm.common.result.SuccessResult; import com.cm.common.result.SuccessResultData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.oauth2.client.OAuth2ClientContext; +import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.Date; + /** * @ClassName: AuthController * @Description: 授权认证 @@ -37,4 +41,15 @@ public class AuthController extends AbstractController { return new SuccessResultData<>(oAuth2AccessToken.getValue()); } + /** + * 获取当前refreshtoken + * + * @return + */ + @GetMapping("getrefreshtoken") + public SuccessResultData getRefreshToken() { + OAuth2AccessToken oAuth2AccessToken = oAuth2ClientContext.getAccessToken(); + return new SuccessResultData<>(oAuth2AccessToken.getRefreshToken().getValue()); + } + } diff --git a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/controller/apis/menu/MenuController.java b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/controller/apis/menu/MenuController.java index d8fd6bc..613006e 100644 --- a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/controller/apis/menu/MenuController.java +++ b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/controller/apis/menu/MenuController.java @@ -28,7 +28,7 @@ public class MenuController extends AbstractController { private IMenuService menuService; @GetMapping("listmenu") - public JSONArray listMenu() throws AccessTokenException { + public JSONArray listMenu() throws AccessTokenException, SearchException { Map params = requestParams(); return menuService.listMenu(params); } diff --git a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/controller/apis/user/UserController.java b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/controller/apis/user/UserController.java index 8d3204c..5717a5d 100644 --- a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/controller/apis/user/UserController.java +++ b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/controller/apis/user/UserController.java @@ -36,7 +36,7 @@ public class UserController extends AbstractController { * @throws SearchException */ @GetMapping("listdepartmentusers/{departmentId}") - public JSONArray listDepartmentUsers(@PathVariable("departmentId") String departmentId) throws AccessTokenException { + public JSONArray listDepartmentUsers(@PathVariable("departmentId") String departmentId) throws AccessTokenException, SearchException { Map params = getParams(); params.put("departmentId", departmentId); return userService.listDepartmentUsers(params); @@ -50,7 +50,7 @@ public class UserController extends AbstractController { * @throws AccessTokenException */ @GetMapping("listuserbyids/{userIds}") - public JSONArray listUserByIds(@PathVariable("userIds") String userIds) throws AccessTokenException { + public JSONArray listUserByIds(@PathVariable("userIds") String userIds) throws AccessTokenException, SearchException { Map params = getParams(); params.put("userIds", userIds); return userService.listUserByIds(params); @@ -62,7 +62,7 @@ public class UserController extends AbstractController { * @return */ @GetMapping("listallusers") - public JSONArray listAllUsers() throws AccessTokenException { + public JSONArray listAllUsers() throws AccessTokenException, SearchException { Map params = getParams(); return userService.listAllUsers(params); } diff --git a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/department/IDepartmentService.java b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/department/IDepartmentService.java index d50e27f..f3b1368 100644 --- a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/department/IDepartmentService.java +++ b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/department/IDepartmentService.java @@ -25,6 +25,6 @@ public interface IDepartmentService { * @return * @throws SearchException */ - JSONArray listDepartments(Map params) throws AccessTokenException, AccessTokenException; + JSONArray listDepartments(Map params) throws AccessTokenException, AccessTokenException, SearchException; } diff --git a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/department/impl/DepartmentServiceImpl.java b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/department/impl/DepartmentServiceImpl.java index 6b1b22a..3205d6d 100644 --- a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/department/impl/DepartmentServiceImpl.java +++ b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/department/impl/DepartmentServiceImpl.java @@ -33,10 +33,13 @@ public class DepartmentServiceImpl extends AbstractService implements IDepartmen private ApiPathProperties apiPathProperties; @Override - public JSONArray listDepartments(Map params) throws AccessTokenException { + public JSONArray listDepartments(Map params) throws AccessTokenException, SearchException { String result = restTemplateUtil.doPostForm(String.format(IApiConsts.LIST_DEPARTMENT, apiPathProperties.getUserCenter(), params.get("parentId").toString()), params); - if (StringUtils.isBlank(result)) { - throw new AccessTokenException("获取组织部门列表失败"); + if(result == null) { + throw new AccessTokenException("认证失败"); + } + if(result.isEmpty()) { + throw new SearchException("获取组织部门列表失败"); } return JSONArray.parseArray(result); } diff --git a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/menu/IMenuService.java b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/menu/IMenuService.java index 3990e50..fbaacc0 100644 --- a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/menu/IMenuService.java +++ b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/menu/IMenuService.java @@ -22,6 +22,6 @@ public interface IMenuService { * @param params * @return */ - JSONArray listMenu(Map params) throws AccessTokenException, AccessTokenException; + JSONArray listMenu(Map params) throws AccessTokenException, AccessTokenException, SearchException; } diff --git a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/menu/impl/MenuServiceImpl.java b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/menu/impl/MenuServiceImpl.java index 13a1825..27009b3 100644 --- a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/menu/impl/MenuServiceImpl.java +++ b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/menu/impl/MenuServiceImpl.java @@ -34,10 +34,13 @@ public class MenuServiceImpl extends AbstractService implements IMenuService { private ApiPathProperties apiPathProperties; @Override - public JSONArray listMenu(Map params) throws AccessTokenException { + public JSONArray listMenu(Map params) throws AccessTokenException, SearchException { String result = restTemplateUtil.doPostForm(String.format(IApiConsts.LIST_MENU, apiPathProperties.getUserCenter(), oAuth2ClientProperties.getClientId()), params); - if (StringUtils.isBlank(result)) { - throw new AccessTokenException("获取列表失败"); + if (result == null) { + throw new AccessTokenException("认证失败"); + } + if (result.isEmpty()) { + throw new SearchException("获取列表失败"); } JSONObject resultObj = JSONObject.parseObject(result); return resultObj.getJSONArray("data"); diff --git a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/user/IUserService.java b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/user/IUserService.java index 2f5e383..7b1eb70 100644 --- a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/user/IUserService.java +++ b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/user/IUserService.java @@ -24,7 +24,7 @@ public interface IUserService { * @return * @throws SearchException */ - JSONArray listDepartmentUsers(Map params) throws AccessTokenException; + JSONArray listDepartmentUsers(Map params) throws AccessTokenException, SearchException; /** * 通过id列表获取用户ID @@ -33,7 +33,7 @@ public interface IUserService { * @return * @throws SearchException */ - JSONArray listUserByIds(Map params) throws AccessTokenException; + JSONArray listUserByIds(Map params) throws AccessTokenException, SearchException; /** * 全部用户 @@ -42,5 +42,5 @@ public interface IUserService { * @return * @throws SearchException */ - JSONArray listAllUsers(Map params) throws AccessTokenException; + JSONArray listAllUsers(Map params) throws AccessTokenException, SearchException; } diff --git a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/user/impl/UserServiceImpl.java b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/user/impl/UserServiceImpl.java index e1e3d8d..7d4cfbb 100644 --- a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/user/impl/UserServiceImpl.java +++ b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/oauth/service/user/impl/UserServiceImpl.java @@ -34,28 +34,37 @@ public class UserServiceImpl extends AbstractService implements IUserService { private ApiPathProperties apiPathProperties; @Override - public JSONArray listDepartmentUsers(Map params) throws AccessTokenException { + public JSONArray listDepartmentUsers(Map params) throws AccessTokenException, SearchException { String result = restTemplateUtil.doPostForm(String.format(IApiConsts.LIST_DEPARTMENT_USER, apiPathProperties.getUserCenter(), params.get("departmentId").toString()), params); - if (StringUtils.isBlank(result)) { - throw new AccessTokenException("获取人员列表失败"); + if (result == null) { + throw new AccessTokenException("认证失败"); + } + if (result.isEmpty()) { + throw new SearchException("获取人员列表失败"); } return JSONArray.parseArray(result); } @Override - public JSONArray listUserByIds(Map params) throws AccessTokenException { + public JSONArray listUserByIds(Map params) throws AccessTokenException, SearchException { String result = restTemplateUtil.doPostForm(String.format(IApiConsts.LIST_USER_BY_ID, apiPathProperties.getUserCenter()), params); - if (StringUtils.isBlank(result)) { - throw new AccessTokenException("获取人员列表失败"); + if (result == null) { + throw new AccessTokenException("认证失败"); + } + if (result.isEmpty()) { + throw new SearchException("获取人员列表失败"); } return JSONArray.parseArray(result); } @Override - public JSONArray listAllUsers(Map params) throws AccessTokenException { + public JSONArray listAllUsers(Map params) throws AccessTokenException, SearchException { String result = restTemplateUtil.doPostForm(String.format(IApiConsts.LIST_ALL_USER, apiPathProperties.getUserCenter()), params); - if (StringUtils.isBlank(result)) { - throw new AccessTokenException("获取全部人员列表失败"); + if (result == null) { + throw new AccessTokenException("认证失败"); + } + if (result.isEmpty()) { + throw new SearchException("获取全部人员列表失败"); } return JSONArray.parseArray(result); } diff --git a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/utils/RestTemplateUtil.java b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/utils/RestTemplateUtil.java index a85d89c..e4d12ed 100644 --- a/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/utils/RestTemplateUtil.java +++ b/cloud-common-plugin-oauth/src/main/java/com/cm/common/plugin/utils/RestTemplateUtil.java @@ -1,13 +1,19 @@ package com.cm.common.plugin.utils; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.cm.common.config.properties.ApiPathProperties; +import com.cm.common.config.properties.OauthClientProperties; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties; import org.springframework.http.*; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.security.oauth2.client.OAuth2ClientContext; +import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; @@ -26,10 +32,12 @@ import java.util.Map; @Component public class RestTemplateUtil { + private static Logger LOG = LoggerFactory.getLogger(RestTemplateUtil.class); @Autowired @Qualifier("oauth2ClientContext") private OAuth2ClientContext oAuth2ClientContext; - private static Logger LOG = LoggerFactory.getLogger(RestTemplateUtil.class); + @Autowired + private OauthClientProperties oauthClientProperties; /** * 执行GET请求 @@ -39,6 +47,7 @@ public class RestTemplateUtil { * @return */ public String doGetForm(String url, Map params) { + refreshToken(); String accessToken = getAccessToken(); if (StringUtils.isBlank(accessToken)) { return null; @@ -61,6 +70,7 @@ public class RestTemplateUtil { * @return */ public String doPostForm(String url, Map params) { + refreshToken(); String accessToken = getAccessToken(); if (StringUtils.isBlank(accessToken)) { return null; @@ -114,8 +124,10 @@ public class RestTemplateUtil { LOG.debug(">>>> 请求状态:" + responseEntity.getStatusCodeValue()); if (HttpStatus.OK.value() == responseEntity.getStatusCodeValue()) { return responseEntity.getBody(); + } else if (HttpStatus.UNAUTHORIZED.value() == responseEntity.getStatusCodeValue()) { + return null; } - return null; + return ""; } /** @@ -130,6 +142,35 @@ public class RestTemplateUtil { return new RestTemplate(simpleClientHttpRequestFactory); } + /** + * 刷新token + * + * @return + */ + private void refreshToken() { + if (oAuth2ClientContext.getAccessToken().getExpiresIn() < 1800) { + LOG.debug("accessToken时间小于1800s,刷新token"); + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED); + MultiValueMap queryParams = new LinkedMultiValueMap<>(); + queryParams.add("grant_type", "refresh_token"); + queryParams.add("refresh_token", oAuth2ClientContext.getAccessToken().getRefreshToken().getValue()); + queryParams.add("client_id", oauthClientProperties.getClientId()); + queryParams.add("client_secret", oauthClientProperties.getClientSecret()); + HttpEntity> httpEntity = new HttpEntity<>(queryParams, httpHeaders); + RestTemplate restTemplate = getRestTemplate(); + try { + String result = getResponse(restTemplate.postForEntity(oauthClientProperties.getAccessTokenUri(), httpEntity, String.class)); + if (!StringUtils.isBlank(result)) { + Map tokenMap = JSON.parseObject(result, Map.class); + oAuth2ClientContext.setAccessToken(DefaultOAuth2AccessToken.valueOf(tokenMap)); + } + } catch (Exception e) { + LOG.error(e.getMessage(), e); + } + } + } + /** * 获取accessToken * diff --git a/cloud-common/src/main/java/com/cm/common/config/properties/OauthClientProperties.java b/cloud-common/src/main/java/com/cm/common/config/properties/OauthClientProperties.java new file mode 100644 index 0000000..ce6ebb2 --- /dev/null +++ b/cloud-common/src/main/java/com/cm/common/config/properties/OauthClientProperties.java @@ -0,0 +1,81 @@ +package com.cm.common.config.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * When you feel like quitting. Think about why you started + * 当你想要放弃的时候,想想当初你为何开始 + * + * @ClassName: OauthClientProperties + * @Description: oauth客户端 + * @Author: WangGeng + * @Date: 2019-08-19 15:24 + * @Version: 1.0 + **/ +@Component +@ConfigurationProperties(prefix = "security.oauth2.client") +public class OauthClientProperties { + private String clientId; + private String clientSecret; + private String userAuthorizationUri; + private String accessTokenUri; + private String grantType; + + public String getClientId() { + return clientId == null ? "" : clientId.trim(); + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getClientSecret() { + return clientSecret == null ? "" : clientSecret.trim(); + } + + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + public String getUserAuthorizationUri() { + return userAuthorizationUri == null ? "" : userAuthorizationUri.trim(); + } + + public void setUserAuthorizationUri(String userAuthorizationUri) { + this.userAuthorizationUri = userAuthorizationUri; + } + + public String getAccessTokenUri() { + return accessTokenUri == null ? "" : accessTokenUri.trim(); + } + + public void setAccessTokenUri(String accessTokenUri) { + this.accessTokenUri = accessTokenUri; + } + + public String getGrantType() { + return grantType == null ? "" : grantType.trim(); + } + + public void setGrantType(String grantType) { + this.grantType = grantType; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("{"); + sb.append("\"clientId\":") + .append("\"").append(clientId).append("\""); + sb.append(",\"clientSecret\":") + .append("\"").append(clientSecret).append("\""); + sb.append(",\"userAuthorizationUri\":") + .append("\"").append(userAuthorizationUri).append("\""); + sb.append(",\"accessTokenUri\":") + .append("\"").append(accessTokenUri).append("\""); + sb.append(",\"grantType\":") + .append("\"").append(grantType).append("\""); + sb.append('}'); + return sb.toString(); + } +} diff --git a/cloud-common/src/main/java/com/cm/common/utils/authority/AuthorityUtil.java b/cloud-common/src/main/java/com/cm/common/utils/authority/AuthorityUtil.java index 3fd358d..da242f0 100644 --- a/cloud-common/src/main/java/com/cm/common/utils/authority/AuthorityUtil.java +++ b/cloud-common/src/main/java/com/cm/common/utils/authority/AuthorityUtil.java @@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSON; import com.cm.common.pojo.bos.RoleGrantedAuthority; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.authority.SimpleGrantedAuthority; import java.util.Collection; import java.util.HashSet; @@ -29,8 +30,13 @@ public class AuthorityUtil extends AuthorityUtils { Set set = new HashSet<>(userAuthorities.size()); for (GrantedAuthority authority : userAuthorities) { - RoleGrantedAuthority roleGrantedAuthority = (RoleGrantedAuthority) authority; - set.add(JSON.toJSONString(roleGrantedAuthority).replace(",", "_wg_")); + if (authority instanceof SimpleGrantedAuthority) { + set.add(authority.getAuthority()); + } + if (authority instanceof RoleGrantedAuthority) { + RoleGrantedAuthority roleGrantedAuthority = (RoleGrantedAuthority) authority; + set.add(JSON.toJSONString(roleGrantedAuthority).replace(",", "_wg_")); + } } return set;