Răsfoiți Sursa

优化登陆失败输出日志和返回友好提示

mac 2 ani în urmă
părinte
comite
d3335379cf

+ 64 - 50
kxs-common/kxs-common-security/src/main/java/com/kxs/common/security/support/handler/SkyAuthenticationFailureEventHandler.java

@@ -10,6 +10,7 @@ import com.kxs.common.core.util.SpringContextHolder;
 import com.kxs.common.log.event.SysLogEvent;
 import com.kxs.common.log.util.LogTypeEnum;
 import com.kxs.common.log.util.SysLogUtils;
+import com.kxs.common.security.util.OAuth2EndpointUtils;
 import com.kxs.system.api.model.SysLog;
 import jakarta.servlet.http.HttpServletRequest;
 import jakarta.servlet.http.HttpServletResponse;
@@ -23,6 +24,7 @@ import org.springframework.security.core.AuthenticationException;
 import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
 import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
 import org.springframework.security.web.authentication.AuthenticationFailureHandler;
+import org.springframework.util.MultiValueMap;
 
 import java.io.IOException;
 
@@ -33,61 +35,73 @@ import java.io.IOException;
 @Slf4j
 public class SkyAuthenticationFailureEventHandler implements AuthenticationFailureHandler {
 
-	private final MappingJackson2HttpMessageConverter errorHttpResponseConverter = new MappingJackson2HttpMessageConverter();
+    private final MappingJackson2HttpMessageConverter errorHttpResponseConverter = new MappingJackson2HttpMessageConverter();
 
-	/**
-	 * Called when an authentication attempt fails.
-	 * @param request the request during which the authentication attempt occurred.
-	 * @param response the response.
-	 * @param exception the exception which was thrown to reject the authentication
-	 * request.
-	 */
-	@Override
-	@SneakyThrows
-	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
-			AuthenticationException exception) {
-		String username = request.getParameter(OAuth2ParameterNames.USERNAME);
+    /**
+     * Called when an authentication attempt fails.
+     *
+     * @param request   the request during which the authentication attempt occurred.
+     * @param response  the response.
+     * @param exception the exception which was thrown to reject the authentication
+     *                  request.
+     */
+    @Override
+    @SneakyThrows
+    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
+                                        AuthenticationException exception) {
+        String username = null;
+        if (request.getAttribute(OAuth2ParameterNames.USERNAME) != null) {
+            username = request.getAttribute(OAuth2ParameterNames.USERNAME).toString();
+        }
 
-		log.info("用户:{} 登录失败,异常:{}", username, exception.getLocalizedMessage());
-		SysLog logVo = SysLogUtils.getSysLog();
-		logVo.setTitle("登录失败");
-		logVo.setLogType(LogTypeEnum.ERROR.getType());
-		logVo.setException(exception.getLocalizedMessage());
-		// 发送异步日志事件
-		String startTimeStr = request.getHeader(CommonConstants.REQUEST_START_TIME);
-		if (CharSequenceUtil.isNotBlank(startTimeStr)) {
-			Long startTime = Long.parseLong(startTimeStr);
-			Long endTime = System.currentTimeMillis();
-			logVo.setTime(endTime - startTime);
-		}
-		logVo.setCreateBy(username);
-		SpringContextHolder.publishEvent(new SysLogEvent(logVo));
-		// 写出错误信息
-		sendErrorResponse(request, response, exception);
-	}
+        String errorMessage;
+        if (exception instanceof OAuth2AuthenticationException authorizationException) {
+            errorMessage = CharSequenceUtil.isBlank(authorizationException.getError().getDescription())
+                    ? authorizationException.getError().getErrorCode()
+                    : authorizationException.getError().getDescription();
+        } else {
+            errorMessage = exception.getLocalizedMessage();
+        }
 
-	private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response,
-			AuthenticationException exception) throws IOException {
-		ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
-		httpResponse.setStatusCode(HttpStatus.OK);
-		String errorMessage;
+        log.info("用户:{} 登录失败,异常:{}", username, errorMessage);
+        SysLog logVo = SysLogUtils.getSysLog();
+        logVo.setTitle("登录失败");
+        logVo.setLogType(LogTypeEnum.ERROR.getType());
+        logVo.setException(exception.getLocalizedMessage());
+        // 发送异步日志事件
+        String startTimeStr = request.getHeader(CommonConstants.REQUEST_START_TIME);
+        if (CharSequenceUtil.isNotBlank(startTimeStr)) {
+            Long startTime = Long.parseLong(startTimeStr);
+            Long endTime = System.currentTimeMillis();
+            logVo.setTime(endTime - startTime);
+        }
+        logVo.setCreateBy(username);
+        SpringContextHolder.publishEvent(new SysLogEvent(logVo));
+        // 写出错误信息
+        sendErrorResponse(request, response, exception);
+    }
 
-		if (exception instanceof OAuth2AuthenticationException authorizationException) {
-			errorMessage = CharSequenceUtil.isBlank(authorizationException.getError().getDescription())
-					? authorizationException.getError().getErrorCode()
-					: authorizationException.getError().getDescription();
-		}
-		else {
-			errorMessage = exception.getLocalizedMessage();
-		}
+    private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response,
+                                   AuthenticationException exception) throws IOException {
+        ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
+        httpResponse.setStatusCode(HttpStatus.OK);
+        String errorMessage;
 
-		// 手机号登录
-		String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
-		if (SecurityConstants.MOBILE.equals(grantType)) {
-			errorMessage = ErrorTypeEnum.PHONE_NOT_FOUND.getDescription();
-		}
+        if (exception instanceof OAuth2AuthenticationException authorizationException) {
+            errorMessage = CharSequenceUtil.isBlank(authorizationException.getError().getDescription())
+                    ? authorizationException.getError().getErrorCode()
+                    : authorizationException.getError().getDescription();
+        } else {
+            errorMessage = exception.getLocalizedMessage();
+        }
 
-		this.errorHttpResponseConverter.write(R.failed(errorMessage), MediaType.APPLICATION_JSON, httpResponse);
-	}
+        // 手机号登录
+        String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
+        if (SecurityConstants.MOBILE.equals(grantType)) {
+            errorMessage = ErrorTypeEnum.PHONE_NOT_FOUND.getDescription();
+        }
+
+        this.errorHttpResponseConverter.write(R.failed(errorMessage), MediaType.APPLICATION_JSON, httpResponse);
+    }
 
 }

+ 5 - 3
kxs-common/kxs-common-security/src/main/java/com/kxs/common/security/util/OAuth2EndpointUtils.java

@@ -10,6 +10,7 @@ import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
 import org.springframework.security.oauth2.core.OAuth2Error;
 import org.springframework.security.oauth2.core.OAuth2RefreshToken;
 import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
+import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
 import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
 import org.springframework.util.LinkedMultiValueMap;
 import org.springframework.util.MultiValueMap;
@@ -51,10 +52,11 @@ public class OAuth2EndpointUtils {
                     parameters.add(key, value);
                 });
 			}
-
+			//写入登陆名到参数内,方便后续获取
+			request.setAttribute(OAuth2ParameterNames.USERNAME, parameters.getFirst(OAuth2ParameterNames.USERNAME));
 			return parameters;
-		}catch (IOException e){
-			throw new OAuth2AuthenticationException("获取参数异常");
+		}catch (Exception e){
+			throw new OAuth2AuthenticationException("登陆参数异常");
 		}
 	}