Skip to content

Instantly share code, notes, and snippets.

@jhiemer
Created December 8, 2023 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhiemer/30b8271cbb34382db267e81980532850 to your computer and use it in GitHub Desktop.
Save jhiemer/30b8271cbb34382db267e81980532850 to your computer and use it in GitHub Desktop.
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String username = null,
password = null;
if (request.getMethod().equals(HttpMethod.OPTIONS.toString())) {
response.setStatus(HttpStatus.OK.value());
return null;
} else if (request.getMethod().equals("POST")) {
if (verifyHeaderContentType(request) || request.getHeader("Accept") != null)
response.addHeader("Content-Type", request.getHeader("Accept"));
if (verifyHeaderContentType(request)) {
try {
loginBean = requestToLoginBean(request);
} catch (IOException e) {
response.setStatus(HttpStatus.BAD_REQUEST.value());
}
}
username = obtainUsername(request);
password = obtainPassword(request);
UsernamePasswordValidationErrors errors = new UsernamePasswordValidationErrors("user");
if (username == null || username == "")
ValidationUtils.rejectBlank(errors, "username", "Field may not be empty");
if (password == null || password == "")
ValidationUtils.rejectBlank(errors, "password", "Field may not be empty");
if (errors.hasErrors()) {
response.setStatus(HttpStatus.BAD_REQUEST.value());
try {
response.getWriter()
.append(convertObjectToJson(ValidationUtils.resolveResponse("user", errors)))
.flush();
return null;
} catch (IOException e) {
throw new AuthenticationServiceException("Error generating BAD_REQUEST response", e.getCause());
}
}
username = username.toLowerCase().trim();
password = password.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
username, password);
setDetails(request, authRequest);
Authentication authentication = this.getAuthenticationManager().authenticate(authRequest);
if (authentication.isAuthenticated())
updateLastLogin(username);
return authentication;
} else {
throw new AuthenticationServiceException(
"HTTP method not supported: " + request.getMethod());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment