AjaxAwareAuthenticationFailureHandler(ObjectMapper)   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
1
package unicon.matthews.security.auth.ajax;
2
3
import java.io.IOException;
4
5
import javax.servlet.ServletException;
6
import javax.servlet.http.HttpServletRequest;
7
import javax.servlet.http.HttpServletResponse;
8
9
import org.springframework.beans.factory.annotation.Autowired;
10
import org.springframework.http.HttpStatus;
11
import org.springframework.http.MediaType;
12
import org.springframework.security.authentication.BadCredentialsException;
13
import org.springframework.security.core.AuthenticationException;
14
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
15
import org.springframework.stereotype.Component;
16
17
import unicon.matthews.common.ErrorCode;
18
import unicon.matthews.common.ErrorResponse;
19
import unicon.matthews.security.exception.AuthMethodNotSupportedException;
20
import unicon.matthews.security.exception.JwtExpiredTokenException;
21
22
import com.fasterxml.jackson.databind.ObjectMapper;
23
24
/**
25
 * 
26
 * @author vladimir.stankovic
27
 *
28
 * Aug 3, 2016
29
 */
30
@Component
31
public class AjaxAwareAuthenticationFailureHandler implements AuthenticationFailureHandler {
32
    private final ObjectMapper mapper;
33
    
34
    @Autowired
35
    public AjaxAwareAuthenticationFailureHandler(ObjectMapper mapper) {
36
        this.mapper = mapper;
37
    }	
38
    
39
	@Override
40
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
41
			AuthenticationException e) throws IOException, ServletException {
42
		
43
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
44
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
45
		
46
		if (e instanceof BadCredentialsException) {
47
			mapper.writeValue(response.getWriter(), ErrorResponse.of("Invalid username or password", ErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED));
48
		} else if (e instanceof JwtExpiredTokenException) {
49
			mapper.writeValue(response.getWriter(), ErrorResponse.of("Token has expired", ErrorCode.JWT_TOKEN_EXPIRED, HttpStatus.UNAUTHORIZED));
50
		} else if (e instanceof AuthMethodNotSupportedException) {
51
		    mapper.writeValue(response.getWriter(), ErrorResponse.of(e.getMessage(), ErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED));
52
		}
53
54
		mapper.writeValue(response.getWriter(), ErrorResponse.of("Authentication failed", ErrorCode.AUTHENTICATION, HttpStatus.UNAUTHORIZED));
55
	}
56
}
57