• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

REST API로 로그인 설정 시 remember-me 문제

21.02.21 19:57 작성 조회수 469

0

안녕하세요, 기선님. 항상 강좌 잘 듣고 있습니다! 다름이 아니라, 제가 이 강좌를 바탕으로 현재 프로젝트를 진행중인데 프론트엔드는 Vue.js로 진행하므로 rest api를 사용하고 있습니다. 현재 postman으로도 테스트중인데 alwaysRemember 값을 true로 설정해도 remember-me 쿠키가 들어오지 않더라구요 ㅜㅜ 하지만 네이버 oauth2 로그인을 하면 또 멀쩡하게 들어옵니다.. 현재 일반 로그인에서는 리다이렉션을 막아뒀는데 혹시 그것과 관련이 있을까요? 며칠동안 이것저것 찾아보다 도저히 답이 안나와서 이렇게 질문 남깁니다..

코드도 첨부하겠습니다

@Component
public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
response.setStatus(HttpServletResponse.SC_OK);
}

}
@Slf4j
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

private boolean postOnly = true;
private HashMap<String, String> jsonRequest;

@Override
protected String obtainPassword(HttpServletRequest request) {
String passwordParameter = super.getPasswordParameter();
if(request.getHeader("Content-Type").equals(ContentType.APPLICATION_JSON.getMimeType())) {
return jsonRequest.get(passwordParameter);
}
return request.getParameter(passwordParameter);
}

@Override
protected String obtainUsername(HttpServletRequest request) {
String usernameParameter = super.getUsernameParameter();
if(request.getHeader("Content-Type").equals(ContentType.APPLICATION_JSON.getMimeType())) {
return jsonRequest.get(usernameParameter);
}
return request.getParameter(usernameParameter);
}


@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response){

if(postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported : " + request.getMethod());
}

if(request.getHeader("Content-Type").equals(ContentType.APPLICATION_JSON.getMimeType())) {
ObjectMapper objectMapper = new ObjectMapper();
try {
this.jsonRequest = (HashMap<String, String>) objectMapper.readValue(request.getReader().lines().collect(Collectors.joining()),
new TypeReference<Map<String, String>>() {
});
} catch (IOException e) {
e.printStackTrace();
throw new AuthenticationServiceException("Request Content-Type(application/json) Parsing Error");
}
}

String username = obtainUsername(request);
String password = obtainPassword(request);
//String rememberMe = request.getParameter("remember-me");

if(username == null) username = "";
if(password == null) username = "";
username = username.trim();

UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

setDetails(request, authRequest);

return this.getAuthenticationManager().authenticate(authRequest);
}

@Override
public void setPostOnly(boolean postOnly) {
this.postOnly = postOnly;
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {

http.oauth2Login()
.userInfoEndpoint()
.userService(customOAuth2UserService);
http.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint); // 인증 실패시 401
http.formLogin().disable();
http.logout()
.logoutSuccessUrl("/");

// 로그인 유지
String rememberKey = "remember_me";
http.rememberMe()
.key(rememberKey)
.rememberMeParameter(rememberKey)
.rememberMeCookieName(rememberKey)
.userDetailsService(memberService)
.alwaysRemember(true)
.tokenRepository(tokenRepository());

http.csrf().disable();
http.cors();


// Json
http.addFilterBefore(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);



}

// Json
@Bean
public CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
try {
filter.setFilterProcessesUrl("/login");
filter.setAuthenticationManager(this.authenticationManagerBean());
filter.setUsernameParameter("email");
filter.setPasswordParameter("password");
filter.setAuthenticationSuccessHandler(authSuccessHandler);
//filter.setAuthenticationFailureHandler(authFailureHandler);
} catch (Exception e) {
e.printStackTrace();
}

return filter;
}


@Bean
public PersistentTokenRepository tokenRepository() {
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
return jdbcTokenRepository;
}

답변 1

답변을 작성해보세요.

0

글쎼요. 설정을 보니 CustomAuthenticationFilter를 사용하고 계신데요 그 필터를 빼고 다시 해보시면 어떤가요? 디버깅을 하면서 왜 remember-me 쿠키를 만들지 않는지 살펴봐야 할 것 같습니다.