[Spring Security] 커스텀 로그인 설정하기

원모어깨찰빵·2024년 3월 11일

스프링

목록 보기
8/17

커스텀 로그인 설정 이유

Spring Security파일을 Config로 등록하면, 로그인페이지 작업, redirect작업을 직접 설정하여 주어야 하기 때문이다.

로그인 페이지 mustache파일 생성

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    login page
    <hr>
    <form action="/loginProc" method="post" name="loginForm">
        <input id="username" type="text" name="username" placeholder="id"/>
        <input id="password" type="password" name="password" placeholder="password"/>
        <input type="submit" value="login"/>
    </form>
</body>
</html>

로그인시 "/loginProc" 경로로 Post요청 전송됨

로그인 경로에 redirect 설정하기

@Controller
public class LoginController {
    @GetMapping("/login")
    public String loginP(){  //login.mustache로 redirect
        return "login";
    }
}

"/login"경로로 Get요청시 위의 mustache파일로 redirect

SecurityConfig파일에 설정 추가

 //로그인 페이지 redirection 설정, html 로그인 페이지에서 넘어온 데이터를 security가 받아서 로그인 처리 진행
        http
                .formLogin((auth)->auth.loginPage("/login")
                        .loginProcessingUrl("/loginProc")
                        .permitAll()   //이 경로로 아무나 들어올 수 있다.
                );
        //csrf : spring security에 자동으로 설정되어 있는사이트 위변조 방지 설정(csrf토큰도 같이 보내주어야 하므로 일단 disable)
        http
                .csrf((auth)->auth.disable());
        return http.build();

로그인 페이지의 redirect설정과, csrf를 임시 비활성화하는 코드를 추가한다.

BCrypt 암호화 메소드 추가

스프링 시큐리티는 사용자 인증(로그인)시 단방향 해시 함수를 통해 암호화를 진행하므로, 회원가입 시 비밀번호에 암호화를 진행하여야 한다.
이 때 사용하는 암호화 기법은 스프링 시큐리티에서 BCrypt를 권장한다.

@Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){  //메소드명 자유
        return new BCryptPasswordEncoder();
    }

Reference

개발자 유미 유튜브
개발자 유미 노션

profile
https://fuzzy-hose-356.notion.site/1ee34212ee2d42bdbb3c4a258a672612

0개의 댓글