inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

스프링 시큐리티

12) 예외 처리 및 요청 캐시 필터 : ExceptionTranslationFilter, RequestCacheAwareFilter

savedRequest.getRedirectUrl()가 null이 들어가서 로그인 후 localhost:8080/null이 나옵니다

627

gil jung

작성한 질문수 4

0

안녕하세요.

localhost:8080/로 들어가서 나오는 시큐리티의 기본 로그인 페이지에서 아무 계정으로 로그인을 하면 localhost:8080/null이 나옵니다. localhost:8080/login로 request를 보냈을떄도 로그인을 하면 localhost:8080/null이 나옵니다

response header를 보면

Location: http://localhost:8080/null

로 나와있고 디버그시에도 savedRequest가 null인게 확인되는데 로그인전에 request로 보낸 url이 httpSessionRequestCache에 저장돼서 로그인 이후 제대로 이동하려면 뭘 수정해야되나요?

logout이나 rememberme같은 부차적인 요소들은 가독성을 위해 생략했습니다.

밑에는 코드입니다.

    // 메모리 방식으로 사용자를 생성하는 configure()는 생략함    

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .antMatchers("/user").hasRole("USER")
                .antMatchers("/admin/pay").hasRole("ADMIN")
                .antMatchers("/admin/**").access("hasRole('ADMIN') or hasRole('SYS')")
                .anyRequest().authenticated();

        http
                .formLogin()
//                .loginPage("/loginPage") 
                .defaultSuccessUrl("/", true)
                .failureUrl("/login")
                .usernameParameter("userId")
                .passwordParameter("passwd")
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        System.out.println("authentication:"+authentication.getName());

                        // savedRequest가 null로 전달되는게 문제!
                        RequestCache requestCache=new HttpSessionRequestCache();
                        SavedRequest savedRequest=requestCache.getRequest(request,response);
                        String redirectUrl=savedRequest.getRedirectUrl();
                        response.sendRedirect(redirectUrl); 
                    }
                })
                .permitAll();

        // http.logout() 생략
       // http.rememberMe() 생략   
       // http.sessionManagement() 생략

       http.exceptionHandling()
//              .authenticationEntryPoint(new AuthenticationEntryPoint() {
//                    @Override
//                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//                        response.sendRedirect("/login"); 
//                    }
//                })
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        response.sendRedirect("/denied"); 
                    }
                });
    }

 

@RestController
@RequestMapping("/")
public class SecurityController {
    @GetMapping
    public String index() {
        return "home";
    }
    @GetMapping("loginPage")
    public String loginPage() {
        return "loginPage";
    }
    @GetMapping("user")
    public String user() {
        return "user";
    }
    @GetMapping("admin/pay")
    public String adminPay() {
        return "adminPay";
    }
    @GetMapping("admin/**")
    public String admin() {
        return "admin";
    }

    @GetMapping("login") 
    public String login() {
        return "login";
    }
    @GetMapping("denied") 
    public String denied() {
        return "denied";
    }

}

Spring Security spring-boot java

답변 1

0

정수원

제가 테스트를 해보면 정상적으로 동작하는 것 같습니다.

package com.example.demo;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SecurityConfig extends WebSecurityConfigurerAdapter {

// 메모리 방식으로 사용자를 생성하는 configure()는 생략함

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/user").hasRole("USER")
.antMatchers("/admin/pay").hasRole("ADMIN")
.antMatchers("/admin/**").access("hasRole('ADMIN') or hasRole('SYS')")
.anyRequest().authenticated();

http
.formLogin()
// .loginPage("/loginPage")
.defaultSuccessUrl("/", true)
.failureUrl("/login")
.usernameParameter("userId")
.passwordParameter("passwd")
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
System.out.println("authentication:"+authentication.getName());

// savedRequest null로 전달되는게 문제!
RequestCache requestCache=new HttpSessionRequestCache();
SavedRequest savedRequest=requestCache.getRequest(request,response);
String redirectUrl=savedRequest.getRedirectUrl();
response.sendRedirect(redirectUrl);
}
})
.permitAll();

// http.logout() 생략
// http.rememberMe() 생략
// http.sessionManagement() 생략

http.exceptionHandling()
// .authenticationEntryPoint(new AuthenticationEntryPoint() {
// @Override
// public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
// response.sendRedirect("/login");
// }
// })
.accessDeniedHandler(new AccessDeniedHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
response.sendRedirect("/denied");
}
});
}
}
package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/")
public class SecurityController {
@GetMapping
public String index() {
return "home";
}
@GetMapping("loginPage")
public String loginPage() {
return "loginPage";
}
@GetMapping("user")
public String user() {
return "user";
}
@GetMapping("admin/pay")
public String adminPay() {
return "adminPay";
}
@GetMapping("admin/**")
public String admin() {
return "admin";
}

@GetMapping("login")
public String login() {
return "login";
}
@GetMapping("denied")
public String denied() {
return "denied";
}

}

기본적인 계정인 user 와 자동 생성 비밀번호로 로그인 하면 home 으로 이동합니다.

그리고 /user 로 접근하면 denied 가 나옵니다.

동일한 소스로 테스트 한 것인데 위의 null 이 나오는 현상이 재현되지 않아서 질문에 대한 정확한 답변을 드리기가 어렵네요..

디버깅 하시면서 어디서 오류가 발생하는지 소스를 따라가보면서 확인해 보시기 바랍니다.

 

시큐리티 공부 버전 질문

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

332

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

283

2

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

0

189

1