스프링 Security 로그인

심규원·2024년 8월 29일


스프링 시큐리티 사용 전


스프링 시큐리티 사용 후

  • Client 의 요청은 모두 Spring Security 를 거치게됨
  • Spring Security 역할
    • 인증/인가
      1. 성공 시: Controller 로 Client 요청 전달
        1. Client 요청 + 사용자 정보 (UserDetails)
      2. 실패 시: Controller 로 Client 요청 전달되지 않음
        1. Client 에게 Error Response 보냄

@AuthenticationPrincipal

@Controller
@RequestMapping("/api")
public class ProductController {

    @GetMapping("/products")
    public String getProducts(@AuthenticationPrincipal UserDetailsImpl userDetails) {
        // Authentication 의 Principal 에 저장된 UserDetailsImpl 을 가져옵니다.
        User user =  userDetails.getUser();
        System.out.println("user.getUsername() = " + user.getUsername());

       return "redirect:/";
    }
}
  • @AuthenticationPrincipal
    • Authentication의 Principal 에 저장된 UserDetailsImpl을 가져올 수 있다.
    • UserDetailsImpl에 저장된 인증된 사용자인 User 객체를 사용할 수 있다
  • @AuthenticationPrincipal 사용해서 메인 페이지 사용자 이름 반영하기
@Controller
public class HomeController {
    @GetMapping("/")
    public String home(Model model, @AuthenticationPrincipal UserDetailsImpl userDetails) {
        // 페이지 동적 처리 : 사용자 이름
        model.addAttribute("username", userDetails.getUser().getUsername());

        return "index";
    }
}

0개의 댓글