인프런 커뮤니티 질문&답변
스프링 시큐리티6 커스텀 로그인 오류
작성
·
941
·
수정됨
0
스프링 시큐리티 커스텀 로그인 오류가 발생하는데 코드를 잘 작성한 것 같은데 로그인이 안되는 오류가 생겨 오류 해결에 어려움을 겪고 있습니다.... 도와주세요
의존성
thymeleaf
mysql driver
spring security
spring web
jpa
config
package com.chatp.security.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration // 이 클래스는 config용 이라는 것을 나타냄
@EnableWebSecurity // 시큐리티라는 것을 나타내기 위해 작성
public class SecurityConfig {
// 비밀번호 암호화 해싱
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
// 스프링 시큐리티 커스텀 config
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
// 특정한 경로일 때 스프링 시큐리티 인증 권한을 받도록 함
http
.authorizeHttpRequests((auth) -> auth
.requestMatchers("/", "/login", "/sign", "/signProc").permitAll()
.requestMatchers("/admin").hasRole("ADMIN")
.requestMatchers("/my/**").hasAnyRole("ADMIN", "USER")
.anyRequest().authenticated()
);
http
.formLogin((auth) -> auth
.loginPage("/login") // 커스텀 로그인 페이지 설정!
.defaultSuccessUrl("/") // 로그인 성공 티폴트 redirect 경로
.permitAll()
);
http
.csrf((auth) -> auth.disable());
return http.build();
}
}로그인페이지
경로 ../resources/templates/Login.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h2>로그인</h2>
<form th:action="@{/login}" method="post">
<label for="username">아이디:</label>
<input type="text" id="username" name="username" required/>
<br/>
<label for="password">비밀번호:</label>
<input type="password" id="password" name="password" required/>
<br/>
<button type="submit">로그인</button>
</form>
</body>
</html>
컨트롤러
package com.chatp.security.controller;
import com.chatp.security.dto.SignDTO;
import com.chatp.security.service.SignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class HomeController {
@Autowired private SignService signService;
@GetMapping("/")
public String HomePage(){
return "/Home";
}
// 로그인
@GetMapping("/login")
public String LoginPage(){
return "/Login";
}
// 회원가입
@GetMapping("/sign")
public String signUpPage(){
return "/SignUp";
}
// 회원가입 처리
@PostMapping("/signProc")
public String signProc(SignDTO signDTO){
// username 얻기 + 회원가입 처리 진행
System.out.println(signDTO.getUsername());
signService.signProcess(signDTO);
// 회원가입 성공 시 로그인 페이지로 리다이렉트
return "redirect:/login";
}
}답변 1
0
안녕하세요, 인프런 AI 인턴입니다.
밈닌님, 스프링 시큐리티에 대한 커스텀 로그인 관련하여 문제를 겪고 계시군요. 코드를 확인해보았습니다만, 여기에서는 특별히 잘못된 부분을 찾기 힘듭니다. 하지만 문제해결을 돕기 위해 몇 가지 확인해야 할 사항들을 알려드리겠습니다.
커스텀 로그인 페이지인
/login요청이HomeController의LoginPage()로 잘 매핑되어있는지 확인해주세요. 매핑 경로에 오타가 없는지 체크합니다.커스텀 로그인 페이지의 form 태그 내의
th:action="@{/login}"속성이 정확하게 스프링 시큐리티의 로그인 처리 경로와 일치하는지 확인합니다. 스프링 시큐리티는 기본적으로 POST 요청을/login경로로 처리하도록 설정되어 있어야 합니다.BCryptPasswordEncoder를 통해 비밀번호를 암호화하여 저장하였는지, 그리고 로그인 시 입력한 비밀번호가 암호화된 비밀번호와 정확히 비교되고 있는지 확인합니다.만약 커스텀 UserDetailsService를 구현하였다면, 해당 서비스가 정상적으로 작동하는지 확인합니다.
로그인 시 발생하는 오류 메시지나, 세부적인 오류 사항을 로그를 통하여 확인하여 문제의 원인을 좁혀봅니다.
Security 설정에서
.anyRequest().authenticated()부분이 모든 요청에 대한 인증을 필요로 하기 때문에, 로그인 관련한 URI(/login,/sign, 등)가 이 인증과정에 영향을 받지 않는지 잘 설정되어 있는지 확인합니다.
이 사항들을 체크하신 후에도 문제가 해결되지 않는다면, 추가적인 로그 정보나 오류 메시지를 제공해주시면 더 정확한 진단을 내리는 데 도움이 될 것입니다.




