[스프링 부트] 29. 시큐리티 설정 후 View에 User 정보 전달하는 방법 - 웹 게시판 v5

KangHo Lee's avatar
Nov 29, 2024
[스프링 부트] 29. 시큐리티 설정 후 View에 User 정보 전달하는 방법  - 웹 게시판 v5

시큐리티 필터

SecurityConfig
@Configuration public class SecurityConfig { @Bean public SecurityFilterChain configure(HttpSecurity http) throws Exception { http.csrf(c -> c.disable()); http.authorizeHttpRequests( r -> r.requestMatchers("/s/**") .authenticated() .anyRequest() .permitAll()) .formLogin(f -> f.loginPage("/login-form") .loginProcessingUrl("/login") // successHandler 설정 .successHandler((request, response, authentication) -> { User user = (User) authentication.getPrincipal(); . HttpSession session = request.getSession(); session.setAttribute("sessionUser", user); response.sendRedirect("/"); })); return http.build(); } }
  • 시큐리티 세션이 아닌 HttpSession에 User 정보를 sessionUser 저장하는 필터입니다.
  • 필터 설정에서 successHandler 설정을 합니다.
// successHandler 설정 .successHandler((request, response, authentication) -> { User user = (User) authentication.getPrincipal(); HttpSession session = request.getSession(); session.setAttribute("sessionUser", user); response.sendRedirect("/"); }));
  • 로그인 성공 시 추가 작업 설정이 가능합니다.
  • authentication.getPrincipal()
    • authentication에서 UserDetils 객체를 받을 수 있습니다.

Application.properties

# 4. musthache session (세션과 request에 접근 허용) spring.mustache.servlet.expose-session-attributes=true spring.mustache.servlet.expose-request-attributes=true

Mustache 파일

{{> layout/header}} {{sessionUser.username}} <section> <form action="/board/save" method="post"> <input type="text" name="title" placeholder="제목"><br> <input type="text" name="content" placeholder="내용"><br> <button type="submit">글쓰기</button> </form> </section> </body> </html>
  • {{sessionUser.username}}
    • 세션에 저장된 유저 정보를 View에서 바로 접근할 수 있습니다.
 
Share article

devleekangho