in plugin-rest/spring-security-rest/src/main/groovy/grails/plugin/springsecurity/rest/RestAuthenticationFilter.groovy [73:138]
void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = request as HttpServletRequest
HttpServletResponse httpServletResponse = response as HttpServletResponse
//Only apply filter to the configured URL
if (requestMatcher.matches(httpServletRequest)) {
log.debug "Applying authentication filter to this request"
//Only POST is supported
if (httpServletRequest.method != 'POST') {
log.debug "${httpServletRequest.method} HTTP method is not supported. Setting status to ${HttpServletResponse.SC_METHOD_NOT_ALLOWED}"
httpServletResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED)
return
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication()
Authentication authenticationResult
UsernamePasswordAuthenticationToken authenticationRequest = credentialsExtractor.extractCredentials(httpServletRequest)
boolean authenticationRequestIsCorrect = (authenticationRequest?.principal && authenticationRequest?.credentials)
if(authenticationRequestIsCorrect){
authenticationRequest.details = authenticationDetailsSource.buildDetails(httpServletRequest)
try {
log.debug "Trying to authenticate the request"
authenticationResult = authenticationManager.authenticate(authenticationRequest)
if (authenticationResult.authenticated) {
log.debug "Request authenticated. Storing the authentication result in the security context"
log.debug "Authentication result: ${authenticationResult}"
AccessToken accessToken = tokenGenerator.generateAccessToken(authenticationResult.principal as UserDetails)
log.debug "Generated token: ${accessToken}"
tokenStorageService.storeToken(accessToken)
authenticationEventPublisher.publishTokenCreation(accessToken)
authenticationSuccessHandler.onAuthenticationSuccess(httpServletRequest, httpServletResponse, accessToken)
SecurityContextHolder.context.setAuthentication(accessToken)
} else {
log.debug "Not authenticated. Rest authentication token not generated."
}
} catch (AuthenticationException ae) {
log.debug "Authentication failed: ${ae.message}"
authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, ae)
}
}else{
log.debug "Username and/or password parameters are missing."
if(!authentication){
log.debug "Setting status to ${HttpServletResponse.SC_BAD_REQUEST}"
httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST)
return
}else{
log.debug "Using authentication already in security context."
authenticationResult = authentication
}
}
} else {
chain.doFilter(request, response)
}
}