반응형
[24.01.26] 116차
<<진도>>
[Back-end] Spring Security 6.0 스프링 시큐리티 -3
: 커스터마이징(로그인,로그아웃 페이지)
: admin 회원가입
: 권한없는 페이지 접근오류 처리
정적자원 Request Patcher
spring security 자체에서 post로 id password를 알아서 검사하고 검증
로그인 실패하면, 로그인 페이지로 error와 함께 redirect!
login-form.html
<form th:action="@{/login}" method="post" id="form" class="container d-flex flex-column mt-5">
<!-- 시큐리티는 로그인 실패하면, 로그인페이지로 에러와 함께 redirect 됨 -->
<div th:if="${param.error}" class="row">
사용자 ID 또는 비밀번호를 확인해 주세요
</div>
...
SecurityConfig.java
public class SecurityConfig {
// 이 메서드가 실행이돼서 리턴되는 SecurityFilterChain 객체를 Bean으로 등록
// 이 Bean은 내부적으로 써야하므로 protected
@Bean
protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
UserDetailsServiceAutoConfiguration a;
// 메소드 체이닝
http
.csrf((csrf) -> csrf.disable()) // security는 기본적으로 csrf(보안 공격) 공격에 대한 방어 세팅이 있다. (disable로 해제도 가능)
.authorizeHttpRequests((authorizeRequests) ->
authorizeRequests
.requestMatchers("/", "/info", "/join/**","/login", "/login/**", "/css/**").permitAll() // "/","info" 해당 리소스(URI) 접근을 인증 절차없이 모두 허용
.requestMatchers("/admin").hasRole("ADMIN")
// "/admin" 리소스(URI)로의 접근은 ADMIN 롤role만 허용
.anyRequest().authenticated()) // 나머지 리소스는 인증절차 필요
.exceptionHandling(error ->
error
.accessDeniedPage("/access-denied")) // 에러가 나면 보여줄 URL 요청되면 핸들러 실행
// .formLogin(Customizer.withDefaults()); // spring security 기본 로그인 form
.formLogin(formLogin ->
formLogin // GET 핸들러메서드는 따로 필요
.loginPage("/login-form") // 사용자 정의 로그인 페이지 (파일명) / default:/login
// 로그인이 필요한 페이지에 접속하면, 로그인 페이지로 redirect(post)
// 인증되지 않은 사용자에게 보여줄 페이지 설정
.loginProcessingUrl("/login") // 로그인 form Action URL, default: /login
.defaultSuccessUrl("/", true) // 로그인 성공 시 요청 URL (, true는 어떤 설정을해도 앞url로)
.failureUrl("/login?error=true") // 로그인 실패 시 요청 URL
.usernameParameter("username") // 아이디 파라미터 설정 / 로그인 페이지의 인풋 name 속성과 동일하게
.passwordParameter("password") // 비밀번호 파라미터 설정 / default: password
// 위 파라미터들은 로그인 뷰의 name과 동일하게
);
http.logout(logout -> logout
.logoutUrl("/logout") // 로그아웃 시 처리할 URL
// .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) // 위랑 같음 대신 객체생성 필요
.logoutSuccessUrl("/") // 로그아웃 시 이동 URL
.invalidateHttpSession(true) // 세션 삭제 (세션 무효화)
);
return http.build(); //이렇게 반환하는 객체로 Bean을 생성(Build)
}
반응형
'학습 기록 > BE (Spring Boot, JPA, JSP, ...)' 카테고리의 다른 글
240129 [Back-end / DB] JPA yml DDL DML 관련 DB 설정 (0) | 2024.01.29 |
---|---|
240125 [Back-end] Spring Security 스프링 시큐리티 -2 (로그인, 회원가입, role ) / JPA / Entity (1) | 2024.01.25 |
240121 [Back-end] Spring Security스프링 시큐리티 (인증 / 접근제한) (1) | 2024.01.23 |
240119 [Back-end] Spring Boot / Open API (0) | 2024.01.19 |
240118 [Back-end] git / github / Source Tree 소스트리 (0) | 2024.01.18 |