스프링 MVC 로그인 구현

황상익·2024년 9월 20일

security

목록 보기
12/16

스프링 MVC 인증 구현

필터를 건너 뛰고 MVC 컨트롤러에 엔트포인트 설정해서 사용
요청간 인증을 저장 -> HttpSessionSecurityContextRepository를 사용하여 인증 상태 저장

SecurityContextRepositorysecurityContextRepository=newHttpSessionSecurityContextRepository();

@PostMapping("/login") //Post 방식의 로그인 방식은 -> UserNamePasswordAuthenticationFilter가 기본 적으로 Post 방식에 로그인 url을 처리하는 필터 
-> 이 필터를 disable 해야 문제 안생김 
public void login(@RequestBody  LoginRequest loginRequest, HttpServletRequest request, HttpServletResponse response) {
 UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated (loginRequest.getUsername(), loginRequest.getPassword()); //사용자 이름과 비밀번호를 담은 인증 객체를 생성한다
Authentication authentication = authenticationManager.authenticate(token); //인증을 시도하고 최종 인증 결과를 반환한다
//인증을 성공한 다음 과정 
//인증 정보를 저장 
SecurityContext securityContext = SecurityContextHolder.getContextHolderStrategy ().createEmptyContext();
securityContext.setAuthentication(authentication); //인증결과를 컨텍스트에 저장한다
SecurityContextHolder.getContextHolderStrategy ().setContext(securityContext); //컨텍스트를 ThreadLocal에 저장한다 / 현재 클라이언트가 사용한는 Thread에 저장해야 전역적으로 사용 가능 
//Context에 저장해서 session에 저장 
securityContextRepository.saveContext(securityContext, request, response) //컨텍스트를 세션에 저장해서 인증 상태를 영속
profile
개발자를 향해 가는 중입니다~! 항상 겸손

0개의 댓글