Last active
January 12, 2023 07:58
-
-
Save tansuaksan/a00b4bd8eae7e395006a982c00f3560d to your computer and use it in GitHub Desktop.
Custom Authentication Via JSON login request in Spring Security
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Slf4j | |
public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter { | |
@Override | |
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) | |
throws AuthenticationException { | |
if (!request.getMethod().equals("POST")) { | |
throw new AuthenticationServiceException( | |
"Authentication method not supported: " + request.getMethod()); | |
} | |
if (request.getHeader("Content-Type").equals(MediaType.APPLICATION_JSON.toString())) { | |
LoginRequest loginRequest = this.getLoginRequest(request); | |
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(loginRequest.getUsername() | |
, loginRequest.getPassword()); | |
setDetails(request, authRequest); | |
return this.getAuthenticationManager().authenticate(authRequest); | |
} | |
return super.attemptAuthentication(request, response); | |
} | |
private LoginRequest getLoginRequest(HttpServletRequest request) { | |
BufferedReader reader = null; | |
LoginRequest loginRequest = null; | |
try { | |
reader = request.getReader(); | |
Gson gson = new Gson(); | |
loginRequest = gson.fromJson(reader, LoginRequest.class); | |
} catch (IOException ex) { | |
log.error("CustomUsernamePasswordAuthenticationFilter#getLoginRequest", ex); | |
} finally { | |
try { | |
reader.close(); | |
} catch (IOException ex) { | |
log.error("CustomUsernamePasswordAuthenticationFilter#getLoginRequest", ex); | |
} | |
} | |
if (loginRequest == null) { | |
loginRequest = new LoginRequest(); | |
} | |
return loginRequest; | |
} | |
@Data | |
private static class LoginRequest { | |
String username; | |
String password; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment