Issue
i want to get UserDetails
from HttpServletRequest when I have SessionAuthenticationException - mean that session already exist for current use, but get null
My Hadnler is
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();
}
}
}
Can anyone help me?
Solution
- There is no easy way. You need to get it from
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);
- The above code can look hacky but it is actually what spring security
BasicAuthenticationConverter
does. https://github.com/spring-projects/spring-security/blob/master/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java#L94
Answered By - Kavithakaran Kanapathippillai
Answer Checked By - Marie Seifert (JavaFixing Admin)