inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

스프링 시큐리티

7) 로그아웃 및 인증에 따른 화면 보안 처리

logout 요청이 강의내용처럼 GetMapping을 타지 않는것 같네요

1326

나지수

작성한 질문수 1

3

/logout 요청이 GetMapping을 안타고 시큐리티 기본?을 타는거 같습니다. SecuritConfig.java에서 http.logout() 주석처리 되어있고 로그아웃시 /login?logout으로 이동하는데 어떤부분이 문제인가요??

java Spring Security spring-boot

답변 6

2

정수원

시큐리티 소스를 보니 LogoutConfigurer 클래스에서 아래와 같이 처리가 되고 있었습니다.

private RequestMatcher getLogoutRequestMatcher(H http) {
if (logoutRequestMatcher != null) {
return logoutRequestMatcher;
}
if (http.getConfigurer(CsrfConfigurer.class) != null) {
this.logoutRequestMatcher = new AntPathRequestMatcher(this.logoutUrl, "POST");
}
else {
this.logoutRequestMatcher = new OrRequestMatcher(
new AntPathRequestMatcher(this.logoutUrl, "GET"),
new AntPathRequestMatcher(this.logoutUrl, "POST"),
new AntPathRequestMatcher(this.logoutUrl, "PUT"),
new AntPathRequestMatcher(this.logoutUrl, "DELETE")
);
}
return this.logoutRequestMatcher;
}

즉 csrf  기능이 활성화 되어 있을 경우에는 POST 방식의 요청에 한해서 LogoutFilter 가 동작하고

csrf  기능을 비활성화 할 경우에는 GET 방식도 LogoutFilter 가 처리하고 있습니다. 

if (http.getConfigurer(CsrfConfigurer.class) != null) {
this.logoutRequestMatcher = new AntPathRequestMatcher(this.logoutUrl, "POST");
}
else {
this.logoutRequestMatcher = new OrRequestMatcher(
new AntPathRequestMatcher(this.logoutUrl, "GET"),
...
);
}

이 부분에 대해서는 강의에서 다루지 못했는데 저도 알게 되었습니다.

나지수님의 소스에서 csrf 기능을 비활성화해서 GET 방식도 LogoutFilter 가 처리하고 있습니다.

http.csrf().disable();                  // csrf 일단 사용안함

다시 활성화하면 정상적으로 Controller에서 처리합니다.

1

나지수

앗 감사합니다...

시큐리티 독학했을 때 모든 POST요청이 동작을 안해서

csrf를 비활성화해야 POST요청이 동작을 하더라구요...

답변 정말 감사드립니다.

0

나지수

네 인가는 문제 없어보입니다.

SecurityConfig.java 소스입니다.

    private UserDetailsService userDetailsService;
private AuthenticationDetailsSource authenticationDetailsSource;

public SecurityConfig(UserDetailsService userDetailsService, AuthenticationDetailsSource authenticationDetailsSource) {
this.userDetailsService = userDetailsService;
this.authenticationDetailsSource = authenticationDetailsSource;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}

@Bean
public AuthenticationProvider authenticationProvider() {
return new CustomAuthenticationProvider(userDetailsService, passwordEncoder());
}

@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

@Override
public void configure(WebSecurity web) throws Exception {
// resources/static의 css, img 등 권한없이 접근가능하게 세팅
web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
/* 인증 정책 */

http.authorizeRequests()
.antMatchers("/**").permitAll()

;

http.csrf().disable(); // csrf 일단 사용안함


http.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login/action")
.defaultSuccessUrl("/")
.failureUrl("/login.html?error=true")
.usernameParameter("username")
.passwordParameter("password")
.authenticationDetailsSource(authenticationDetailsSource)
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
System.out.println("authentication : "+authentication.getName());
response.sendRedirect("/");
}
})
.failureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
System.out.println("exception :" + exception.getMessage());
response.sendRedirect("/login");
}
})
.permitAll();

0

정수원

현재 /logout 요청에 대한 인가설정을 permitAll 로 해 주었는지요?

스프링시큐리티가 처리할 경우 /logout 요청은 기본적으로 인증이나 특정권한이 없어도 누구나 접근이 가능하지만 커스텀하게 처리할 경우 /logout 요청에 대한 인가설정을 별도로 해 주어야 합니다

가령 http.antMatchers("/logout").permitAll()

처럼 설정이 필요합니다

0

나지수

빠른답변 감사합니다.

답변주신대로 Get 으로 /logout을 요청을 하고 있습니다.

<sec:authorize access="isAuthenticated()">
<li class="nav-item"><a class="nav-link text-light" href="<c:url value="/logout"/>">로그아웃</a></li>
</sec:authorize>
@GetMapping(value="/logout")
public String logout(HttpServletRequest request, HttpServletResponse response) {

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

if(authentication != null) {
new SecurityContextLogoutHandler().logout(request, response, authentication);
}

return "redirect:/";
}

ㅠㅠ..

0

정수원

스프링 시큐리티 로그아웃은 기본적으로 LogoutFilter 에서 처리하는데 두가지 조건을 보게 됩니다.

1. 현재 로그아웃 url 이 /logout 인가?

2. http 요청 메소드 방식이 POST 인가?

두가지 조건이 맞을 때 LogoutFilter 에서 실제 로그아웃 처리를 하게 됩니다.

만약 두가지 조건이 모두 맞지 않을 경우 스프링 시큐리티 로그아웃 처리는 skip 됩니다.

이 때 스프링이나 서블릿에서 /logout 요청을 처리하도록 구현되어 있다면 당연히 커스텀한 로그아웃 기능이 동작됩니다.

요약하자면 SecurityConfig 에서 logout 처리를 하든 자체적으로 logout 처리를 하든 

앞서 설명한 두가지 조건이 맞을 경우 LogoutFilter 가 작동하는 것이고 그렇지 않으면 별도의 로그아웃 처리를 해 주어야 합니다.

위의 두가지 조건이 모두 해당하는지  아닌지 살펴 보시기 바랍니다.

일단 강의 소스에서 다음과 같이 작성되어 있을 경우 LogoutFilter 에서는 로그아웃 처리를 하지 않습니다.

Client request url : /logout

Server url Mapping : @GetMapping("/logout")

             

시큐리티 공부 버전 질문

0

175

1

[해결 방법] MethodSecurityConfig.customMethodSecurityMetadataSource() 호출하지 않는 이슈

0

186

1

AbstractSecurityInterceptor.class.beforeInvocation()를 2번 실행하는 경우

0

174

1

강의 코드가 왜이렇게 뒤죽박죽인가요...

0

249

1

메인 페이지로 접속해도 login url로 리다이렉트가 되지 않습니다..

0

236

1

파라미터값이 넘어가지 않습니다 ....

0

374

1

security filterChain 설정 질문이 있습니다.

0

331

1

소스 부분 질문 드립니다.

0

208

2

섹션4 7번 강의 문제가 있는거 같네요.

0

344

2

파일이 수시로 이름이 바껴있네요 ㄷㄷ

0

304

1

HttpSessionSecurityContextRepository를 사용안하는 문제

0

555

2

error , exception 이 잘 안됩니다.

0

282

2

thymeleaf tag 질문합니다.

0

196

2

버전업하면서 deprecated된 것들이 너무많아요

0

478

1

spring security 패치 관련

0

437

1

모바일을 사용할때 토큰말고 세션

0

846

2

DB 연동한 인가 부분에 대한 질문입니다!

0

264

1

Ajax방식도 똑같이 Session방식을 사용하는건가요?

0

307

1

Config 파일 생성 시 질문이 있습니다.

0

225

1

강사님 몇일동안 구글 검색만 100개 했는데도 이유를 모르겠습니다..

1

429

2

403 에러 뜹니다.

0

813

2

login_proc의 존재에 대한 간략한 설명입니다

0

276

1

top.html에 로그인 링크를 만들어서 로그인을 해봤습니다

0

282

2

안녕하세요. DB에 저장될 때 이해 안 가는 값이 있어서 질문드립니다!

0

189

1