-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathBasicAuthInterceptor.java
45 lines (35 loc) · 1.67 KB
/
BasicAuthInterceptor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package nextstep.security.authentication;
import static nextstep.security.util.SecurityConstants.SPRING_SECURITY_CONTEXT_KEY;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nextstep.security.exception.AuthenticationException;
import nextstep.security.userdetail.UserDetail;
import nextstep.security.userdetail.UserDetailService;
import nextstep.security.util.TokenDecoder;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.HandlerInterceptor;
public class BasicAuthInterceptor implements HandlerInterceptor {
private final TokenDecoder tokenDecoder;
private final UserDetailService userDetailService;
public BasicAuthInterceptor(TokenDecoder tokenDecoder, UserDetailService userDetailService) {
this.tokenDecoder = tokenDecoder;
this.userDetailService = userDetailService;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
try {
String token = request.getHeader(HttpHeaders.AUTHORIZATION);
UserDetail decodedUserInfo = tokenDecoder.decodeToken(token);
UserDetail userDetail = userDetailService.getUserDetail(decodedUserInfo.getUsername());
if (!userDetail.verifyPassword(decodedUserInfo.getPassword())) {
throw new AuthenticationException();
}
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, userDetail);
return true;
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
}
}