[Spring] 스프링 시큐리티 default 로그인 경로 변경하는 방법 ("/login")

2023. 4. 29. 12:00·공부/Spring
728x90

스프링 시큐리티를 사용해서 인증을 구현하다보면 로그인 경로를 바꾸고 싶을 때가 있다.

 

로그인 경로를 설정하지 않을 때는 default 로그인 경로가 "/login"으로 되어있는데 이를 바꾸는 방법에 대해 알아보려고 한다.

 

formLogin 방식(form 태그)과 토큰 방식, 두 방식 모두에서 로그인 경로를 "/api/users/login"으로 바꿔보려고 한다.

 

1. formLogin 방식

 

만약 form 태그를 사용해서 직접 로그인을 수행한다고 해보자.

 

아마 아래와 같이 form 태그의 action 속성에 로그인 경로를 넣어서 진행할 것이다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>로그인</title>
</head>
<body>
<form action="/login" method="post">
    <input type="text" name="name"> <br>
    <input type="password" name="password">
    <button>제출</button>
</form>
</body>
</html>

이를 바꾸고 싶다면 SecurityConfig 파일에서 .formLogin().loginProcessingUrl("변경할 경로")를 추가해주면 된다.

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
	...
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
        return httpSecurity
                .formLogin()
                .loginProcessingUrl("/api/users/login").and().build();
    }
    }

}

이제 default 로그인 경로인 "/login"에서 "/api/users/login"으로 바뀐 모습을 확인할 수 있다.

 

2. 토큰 방식

서버의 세션을 통해 인증을 구현하는 formLogin 방식과 달리 토큰 방식에서는 formLogin을 disable하는 경우가 많기 때문에 loginProcessingUrl을 사용할 수 없다.

 

만약 토큰 방식으로 구현하게 될 경우 대부분 filter를 만들어서 등록하는 경우가 대부분일 것이다.

 

그러면 이 filter를 등록하기 전에 filter의 로그인 경로를 세팅한 다음에 이 filter를 등록하면 로그인 경로를 바꿀 수 있다.

 

<SecurityConfig 예시>

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
    
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
        return httpSecurity
                .httpBasic().disable()
                .formLogin().disable()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().apply(new Custom())
                .and().build();
    }

    public class Custom extends AbstractHttpConfigurer<Custom, HttpSecurity> {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
            JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager);
            jwtAuthenticationFilter.setFilterProcessesUrl("/api/users/login");
            http
                    .addFilter(jwtAuthenticationFilter);

        }
    }

}

 

 

728x90

'공부 > Spring' 카테고리의 다른 글

[Spring] 스프링 시큐리티와 jwt 사용해서 인증 및 인가 구현 (1)  (0) 2023.05.01
[Spring] 스프링 jwt 생성, 검증, 값 가져오기 구현  (0) 2023.04.30
[Spring][WebSocket] 스프링 STOMP와 웹 소켓 개념 및 사용법 (Web Socket with STOMP) (1)  (2) 2023.04.20
[Spring] 스프링 OAuth2 네이버 로그인 (OAuth2 스프링 4편)  (0) 2023.04.01
[Spring] 스프링 OAuth2 페이스북 로그인 (OAuth2 스프링 3편)  (6) 2023.03.30
'공부/Spring' 카테고리의 다른 글
  • [Spring] 스프링 시큐리티와 jwt 사용해서 인증 및 인가 구현 (1)
  • [Spring] 스프링 jwt 생성, 검증, 값 가져오기 구현
  • [Spring][WebSocket] 스프링 STOMP와 웹 소켓 개념 및 사용법 (Web Socket with STOMP) (1)
  • [Spring] 스프링 OAuth2 네이버 로그인 (OAuth2 스프링 4편)
웅대
웅대
알고리즘과 백엔드를 중심으로 열심히 공부 중입니다! 같이 소통하며 공부해요!
    250x250
  • 웅대
    웅대 개발 블로그
    웅대
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 백준 알고리즘
        • dp
        • 문자열
        • 정렬
        • 스택
        • 브루트 포스
        • 이진 탐색
        • 정리
        • 우선순위 큐
        • 자료구조
        • 그래프
        • 기타
        • 그리디
      • 컴퓨터 언어
        • Kotlin
        • Python
        • C#
      • 공부
        • Database
        • Android Studio
        • Algorithm
        • 컴퓨터 구조론
        • Spring
        • lombok
        • AWS
        • Network
        • OS
        • Git & GitHub
        • AI
        • Computer Vision
        • 보안
        • Nginx
        • 프론트
        • express
        • GCP
        • grokking concurrency
        • DevOps
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    ci/cd
    bfs
    스택
    codetree
    파이썬
    Merge
    푸쉬 알람
    Vector Store
    code tree
    스프링 OAuth2
    RNN
    parametric search
    nn.RNN
    influxDB CLI
    embedding
    ChatPromptTemplate
    다익스트라
    AWS Lambda
    binary search
    openvidu 배포
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
웅대
[Spring] 스프링 시큐리티 default 로그인 경로 변경하는 방법 ("/login")
상단으로

티스토리툴바