비동기 인증 - Rest 인증 상태 영속하기
RestAuthenticationFilter
public class RestAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private final ObjectMapper objectMapper = new ObjectMapper();
public RestAuthenticationFilter(HttpSecurity http) {
super(new AntPathRequestMatcher("/api/login", "POST"));
setSecurityContextRepository(getSecurityContextRepository(http)); //추가
}
//추가
private SecurityContextRepository getSecurityContextRepository(HttpSecurity http) {
SecurityContextRepository scr = http.getSharedObject(SecurityContextRepository.class);
if (scr == null) {
scr = new DelegatingSecurityContextRepository(
new RequestAttributeSecurityContextRepository(),
new HttpSessionSecurityContextRepository()
);
}
return scr;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
if (!HttpMethod.POST.name().equals(request.getMethod()) || !WebUtil.isAjax(request)) {
throw new IllegalArgumentException("Authentication method is not supported");
}
AccountDto accountDto = objectMapper.readValue(request.getReader(), AccountDto.class);
if (!StringUtils.hasText(accountDto.getUsername()) || !StringUtils.hasText(accountDto.getPassword())) {
throw new AuthenticationServiceException("Username or Password is not provided");
}
RestAuthenticationToken authenticationToken = new RestAuthenticationToken(accountDto.getUsername(), accountDto.getPassword());
return getAuthenticationManager().authenticate(authenticationToken);
}
}마지막 업데이트