IndexController에 추가
@GetMapping("/user")
@ResponseBody
public String user() {
return "user";
}
@GetMapping("/admin")
@ResponseBody
public String admin() {
return "admin";
}
@GetMapping("/manager")
@ResponseBody
public String manager() {
return "manager";
}
// 현재는 스프링 시큐리티가 낚아채간다.
@GetMapping("/login")
@ResponseBody
public String login() {
return "login";
}
@GetMapping("/join")
@ResponseBody
public String join() {
return "join";
}
@GetMapping("/joinProc")
@ResponseBody
public String joinProc() {
return "회원가입 완료됨!";
}
아직 페이지를 만들지 않았기 때문에 @ResponseBody를 붙여 데이터를 직접 넣어준다.
localhost:8080/logout으로 가서 먼저 로그아웃을 하자
그리고 다시 로그인한 후 Mapping 테스트를 한다.
user는 로그인 한 사람만, 그리고 로그인 한 사람 중 admin은 admin 권한이 있는 사람만, manager는 manager 권한이 있는 사람만 접속할 수 있게 하고 싶을 수 있다.
이런 설정을 위해
package com.cos.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.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/user/**").authenticated()
.requestMatchers("/manager/**").hasAnyRole("ADMIN", "MANAGER")
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().permitAll());
return http.build();
}
}
/user는 authenticated() 즉, 로그인 한 사람만
/manager는 admin과 manager 역할인 사람만
/admin은 admin 역할인 사람만
나머지는 누구나 접속할 수 있게 해 놨다.
스프링부트 재시작 후 접속해 보면 인덱스 페이지는 로그인없이 접속이 가능하다.
user로 접속해보면
권한이 없기 때문에 403 에러가 발생한 것을 볼 수 있다.
누구나 접속 가능하게 해 둔 join으로 가보면
login으로 가보면 이전과 달리 스프링 시큐리티가 낚아채가지 않고 우리가 설정한 페이지가 나온다.
/user와 같은 권한이 없는 페이지로 이동 시 에러 페이지를 띄우지 않고 로그인 페이지로 이동할 수 있도록 설정할 수 있다.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeHttpRequests()
.requestMatchers("/user/**").authenticated()
.requestMatchers("/manager/**").hasAnyRole("MANAGER", "ADMIN")
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().permitAll()
.and().formLogin().loginPage("/login");
return http.build();
}
이제 admin, manager와 같은 페이지로 이동 시 자동으로 login페이지로 간다.
'Spring Security' 카테고리의 다른 글
[OAuth] 구글 로그인 준비 (0) | 2023.03.26 |
---|---|
[기본] 시큐리티 권한처리 (0) | 2023.03.25 |
[기본] 시큐리티 로그인 (0) | 2023.03.25 |
[기본] 시큐리티 회원가입 (0) | 2023.03.25 |
[기본] 환경 설정 (0) | 2023.03.25 |