无法在 SecurityErrorHandler 中获取 UserDetails
Can not get UserDetails in SecurityErrorHandler
当我有 SessionAuthenticationException 时,我想从 HttpServletRequest 获取 UserDetails
- 意味着该会话已经存在供当前使用,但得到 null
我的哈德勒是
public class SecurityErrorHandler extends SimpleUrlAuthenticationFailureHandler {
private static final String FORCE_PARAMETER_NAME = "force";
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception)
throws IOException, ServletException {
//if session already exist
if (exception.getClass().isAssignableFrom(SessionAuthenticationException.class)) {
logger.debug("Session already exist");
Principal userPrincipal = request.getUserPrincipal();
}
}
}
谁能帮帮我?
- 没有简单的方法。您需要从
Authorization
header 中获取
String authHeader = request.getHeader("Authorization");
byte[] base64Token =
header.trim().substring(6).getBytes(StandardCharsets.UTF_8);
byte[] decoded = java.util.Base64.getDecoder().decode(base64Token);
String token = new String(decoded, StandardCharsets.UTF_8);
int delim = token.indexOf(":");
String userName = token.substring(0, delim);
- 上面的代码可能看起来很老套,但它实际上是 spring security
BasicAuthenticationConverter
所做的。 https://github.com/spring-projects/spring-security/blob/master/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java#L94
当我有 SessionAuthenticationException 时,我想从 HttpServletRequest 获取 UserDetails
- 意味着该会话已经存在供当前使用,但得到 null
我的哈德勒是
public class SecurityErrorHandler extends SimpleUrlAuthenticationFailureHandler {
private static final String FORCE_PARAMETER_NAME = "force";
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception)
throws IOException, ServletException {
//if session already exist
if (exception.getClass().isAssignableFrom(SessionAuthenticationException.class)) {
logger.debug("Session already exist");
Principal userPrincipal = request.getUserPrincipal();
}
}
}
谁能帮帮我?
- 没有简单的方法。您需要从
Authorization
header 中获取
String authHeader = request.getHeader("Authorization");
byte[] base64Token =
header.trim().substring(6).getBytes(StandardCharsets.UTF_8);
byte[] decoded = java.util.Base64.getDecoder().decode(base64Token);
String token = new String(decoded, StandardCharsets.UTF_8);
int delim = token.indexOf(":");
String userName = token.substring(0, delim);
- 上面的代码可能看起来很老套,但它实际上是 spring security
BasicAuthenticationConverter
所做的。 https://github.com/spring-projects/spring-security/blob/master/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java#L94