🐛 fix 升级 springboot 2.6.x,鉴权异常时错误消息乱码的问题

This commit is contained in:
b2baccline
2021-12-10 19:58:51 +08:00
parent 9b4c0dc23f
commit f7037e0cb0
3 changed files with 14 additions and 3 deletions

View File

@@ -12,6 +12,7 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* @author Hccake
@@ -24,7 +25,11 @@ public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
AuthenticationException e) throws IOException, ServletException {
httpServletResponse.setHeader("Content-Type", MediaType.APPLICATION_JSON.toString());
String utf8 = StandardCharsets.UTF_8.toString();
httpServletResponse.setHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE);
httpServletResponse.setHeader("Accept-Charset", utf8);
httpServletResponse.setCharacterEncoding(utf8);
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
R<Object> r = R.failed(SystemResultCode.UNAUTHORIZED, e.getMessage());
httpServletResponse.getWriter().write(JsonUtils.toJson(r));

View File

@@ -15,6 +15,9 @@ import org.springframework.security.oauth2.provider.error.WebResponseExceptionTr
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
/**
* @author Hccake
* @version 1.0
@@ -74,7 +77,8 @@ public class CustomWebResponseExceptionTranslator implements WebResponseExceptio
HttpHeaders headers = new HttpHeaders();
headers.set("Cache-Control", "no-store");
headers.set("Pragma", "no-cache");
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8));
if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
}

View File

@@ -53,6 +53,7 @@ import org.springframework.web.client.RestTemplate;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
@@ -126,7 +127,8 @@ public class RemoteOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
private HttpHeaders requestHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8));
return headers;
}