Skip to content

Instantly share code, notes, and snippets.

@tansuaksan
Last active January 12, 2023 07:58
Show Gist options
  • Save tansuaksan/a00b4bd8eae7e395006a982c00f3560d to your computer and use it in GitHub Desktop.
Save tansuaksan/a00b4bd8eae7e395006a982c00f3560d to your computer and use it in GitHub Desktop.
Custom Authentication Via JSON login request in Spring Security
@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