728x90
반응형
시작하기 전에 전에 만든걸로 회원 가입을 해주자
manaer
admin

현재 권한은 전부 ROLE_USER !
해당 권한의 페이지로 잘 들어가지는지 확인을 위해
db에서 직접 권한을 수정해주자
가입시에 권한은 따로 만들면 된다
UPDATE user SET role = 'ROLE_MANAGER' WHERE id = 2;
UPDATE user SET role = 'ROLE_ADMIN' WHERE id = 3;
id는 해당 데이터에 맞게 넣어주면 된다.
그후 manager 로 로그인 후 /manager 을 가보면

페이지를 만들지 않아서 그렇지 밑에 type 과 status 를 보면 제대로 접속이 된걸 확인 할 수 있다
하지만 admin 을 가보면 어떨까

당연히 권한이 없어서 안됨
SecurityConfig
package com.example.security.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@EnableWebSecurity
// @secured 어노테이션 활성, preAuthorize,postAuthorize 어노테이션 활성
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/user/**").authenticated()
.antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
.anyRequest().permitAll()
.and()
.formLogin()
.loginPage("/loginForm")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/");
}
}
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
어노테이션이 있는데
각각
@secured("ROLE_ADMIN")
@PreAuthorize("")
@Secured("ROLE_ADMIN")
@GetMapping("/info")
public @ResponseBody String info() {
return "개인정보";
}
@PreAuthorize("hasRole('ROLE_MANAGER') or hasRole('ROLE_AMDIN')")
@GetMapping("/data")
public @ResponseBody String data() {
return "데이터정보";
}
이런식으로 개별적인 controller 에 권한을 부여 할 수 있다.
Secuerd 같은 경우는 1개의 권한정도로 보면 되고
PreAuthorize는 그 이상, 이며 해당 메서드 (여기서는 /data) 가 실행되기 직전에 실행이 된다.
728x90
반응형
'Spring > Spring Security' 카테고리의 다른 글
| OAuth 개념 (0) | 2022.08.24 |
|---|---|
| 시큐리티 로그인 (0) | 2022.08.24 |
| security 로 간단한 회원가입과 비밀번호 암호화 (0) | 2022.08.23 |
| CORS (Cross-Origin Resource Sharing) 설정 (0) | 2021.12.13 |
| 스프링 시큐리티 (0) | 2021.11.23 |