fix #I545XE

This commit is contained in:
zhult13
2022-05-15 21:57:53 +08:00
parent f64d74802f
commit 1e8ccfe202
5 changed files with 70 additions and 1 deletions
@@ -0,0 +1,34 @@
package com.central.oauth2.common.config;
import com.central.oauth2.common.util.AuthUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.websocket.server.ServerEndpointConfig;
/**
* webSocket鉴权配置
*
* @author zlt
* @version 1.0
* @date 2022/5/8
* <p>
* Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
public class WcAuthConfigurator extends ServerEndpointConfig.Configurator {
@Override
public boolean checkOrigin(String originHeaderValue) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
try {
//检查token有效性
AuthUtils.checkAccessToken(servletRequestAttributes.getRequest());
} catch (Exception e) {
log.error("WebSocket-auth-error", e);
return false;
}
return super.checkOrigin(originHeaderValue);
}
}
@@ -3,11 +3,15 @@ package com.central.oauth2.common.util;
import com.central.common.constant.CommonConstant;
import com.central.common.constant.SecurityConstants;
import com.central.common.model.SysUser;
import com.central.common.utils.SpringUtil;
import com.central.oauth2.common.token.CustomWebAuthenticationDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
@@ -66,6 +70,29 @@ public class AuthUtils {
return null;
}
/**
* 校验accessToken
*/
public static void checkAccessToken(HttpServletRequest request) {
String accessToken = extractHeaderToken(request);
checkAccessToken(accessToken);
}
public static void checkAccessToken(String accessTokenValue) {
TokenStore tokenStore = SpringUtil.getBean(TokenStore.class);
OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue);
if (accessToken == null || accessToken.getValue() == null) {
throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
} else if (accessToken.isExpired()) {
tokenStore.removeAccessToken(accessToken);
throw new InvalidTokenException("Access token expired: " + accessTokenValue);
}
OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
if (result == null) {
throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
}
}
/**
* *从header 请求中的clientId:clientSecret
*/