[Spring] @EnableGlobalMethodSecurity 간단 사용으로 페이지 권한 관리(With. Item Create)

@EnableGlobalMethodSecurity
Web Security에서 URL과 Token 유무로 인증을 하고 Method Security를 사용해서 권한에 따라 인가를 하는 방법

prePostEnabled - @PreAuthorize
- @PreAuthorize를 사용하기 위해서 true로 설정한다.
- @PreAuthorize는 SpEL을 사용해서 인가처리가 가능하다. 
- @PreAuthorize는 스프링 시큐리티 프레임워크에 일부이다.

 

@EnableWebSecurity 어노테이션의 역할
스프링 시큐리티를 활성화하고 웹 보안 설정을 구성하는데 사용

 


@EnableGlobalMethodSecurity & @PreAuthorize

@EnableGlobalMethodSecurity 선언
//SecurityConfig.java

@EnableWebSecurity
⭐@EnableGlobalMethodSecurity(prePostEnabled = true) // 권한관리 ROLE_ADMIN 관리자일 때 들어갈 수 있는 페이지 권한관리
// pre : 사전, post : 사후, 사전/사후에 인증/권한 검사 어노테이션 사용가능
public class SecurityConfig {

    private final JwtAuthFilter authFilter;

    public SecurityConfig(JwtAuthFilter authFilter) {
        this.authFilter = authFilter;
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean // Filter
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
//                csrf보안공격에 대한 설정은 하지 않겠다라는 의미
//                xss와 csrf의 차이 정리 필요
                .csrf().disable()
                .cors().and() // CORS 활성화
                .httpBasic().disable()
                .authorizeRequests()
//                인증 미적용 url 패턴 작성
                    .antMatchers("/member/create", "/doLogin", "/items", "/item/*/image")
                    .permitAll()
//                그외 요청은 모두 인증필요
                .anyRequest().authenticated()
                .and()
//                세션을 사용하지 않겠다라는 설정 추가
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class) //authFilter 사용
//                커스텀한 Filter를 사용하면 무조건 Filter를 타게된다.
                .build();
    }
}

 

@PreAuthorize 어노테이션 사용
"hasRole('ADMIN')" 설정으로 ADMIN만 접근가능 설정

 

//Controller

    ⭐@PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/item/create") // 관리자만 가능
    public ResponseEntity<CommonResponse> itemCreate(ItemReqDto itemReqDto) { // image를 받아야 하기때문에 json말고 form 데이터 multipart사용
        Item item = itemService.create(itemReqDto);
        return new ResponseEntity<>(
                new CommonResponse(HttpStatus.CREATED, "item succesfully create", item.getId())
                , HttpStatus.CREATED);
        // CommonResponse 공통문구 출력
    }

 

ItemCreate service 기능구현
//Service

    public Item create(ItemReqDto itemReqDto) {
        MultipartFile multipartFile = itemReqDto.getItemImage();
        String fileName = multipartFile.getOriginalFilename(); // fileName 가져오기
        Item new_item = Item.builder()
                .name(itemReqDto.getName())
                .category(itemReqDto.getCategory())
                .price(itemReqDto.getPrice())
                .stockQuantity(itemReqDto.getStockQuantity())
                .build();
        Item item = itemRepository.save(new_item); // DB저장
        Path path = Paths.get("C:/Users/Playdata/Desktop/tmp/", item.getId() + "_" + fileName); // 사진 파일은 해당 경로에 넣겠다.
//        Id를 넣으므로서 중복제거
        item.setImagePath(path.toString());

        try { // ⭐파일 넣을때 에러처리 중요하다.
            byte[] bytes = multipartFile.getBytes();
//            있으면 덮어쓰기, 없으면 create
            Files.write(path, bytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        } catch (IOException e) {
            throw new IllegalArgumentException("image not available");
        }
        return item;
    }

 


POSTMAN TEST

ADMIN계정 로그인

 

 

ADMIN계정으로 ItemCreate시 item 생성 성공 및
DB 데이터 삽입 확인

 

 

 USER계정 로그인

 

 

USER계정으로 ItemCreate시 item 생성 실패
500ERROR

 

 

REFERENCE

 

Spring - @EnableGlobalMethodSecurity

Spring Security 두가지 방법 Spring에서는 Web 기반의 Security과 Method 기반의 Security 기능을 제공한다. 메소드 기반은 메소드 별로 권한을 체크하는데 Web 기반과 다르게 필터가 아닌 컨트롤러 단에서 권

obv-cloud.com

 

 

스프링 시큐리티에서 @EnableWebSecurity 어노테이션의 활용 방법과 기능

안녕하세요! 이번에는 스프링 시큐리티에서 자주 사용되는 `@EnableWebSecurity` 어노테이션에 대해 알아보겠습니다. `@EnableWebSecurity` 어노테이션은 스프링 시큐리티를 활성화하고 웹 보안 설정을 구

jjangadadcodingdiary.tistory.com