[Start Spring Boot] Spring Security Method

·2024년 4월 20일
0

Start Spring Boot!

목록 보기
46/53
post-thumbnail

메서드 보안이란?

  • 내부의 메서드 혹은 함수에 보안을 설정하는 것
  • 필터와 권한을 설정할 수 있음

메소드 보안 사용하기

메소드 보안 활성화 하기

  • SsbApplication.java
package com.chan.ssb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;

@SpringBootApplication
@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SsbApplication {

	public static void main(String[] args) {
		SpringApplication.run(SsbApplication.class, args);
	}

}

PreAuthorize

  • 함수를 실행하기 이전에 검사를 진행
    @PreAuthorize("hasRole('ROOT')")
    public List<PlayerDTO> getAllPlayers() {
        List<Player> players = playerRepository.findAll();
        List<PlayerDTO> returnPlayers = players.stream().map(PlayerDTO::fromEntity).toList();
        if(returnPlayers.isEmpty()) {
            throw new EntityNotFoundException("No players found");
        }
        return returnPlayers;
    }
    
  • 다음과 같이 권한을 확인할 수 있음

PostAuthorize

  • 함수 실행 후 클라이언트한테 응답을 하기 직전에 검사
    @PostMapping("")
    @PostAuthorize("hasRole('ROOT')")
    public ResponseEntity<CollectionModel<EntityModel<TeamDTO>>> createTeams(@Valid @RequestBody TeamDTOListWrapper teamDTOList) {
        List<TeamDTO> savedTeams = teamService.createTeams(teamDTOList.getTeamDTOList());
        URI location = ServletUriComponentsBuilder
                .fromCurrentRequest()
                .path("")
                .build()
                .toUri();

        List<EntityModel<TeamDTO>> teamEntityModels = savedTeams.stream()
                .map(team -> EntityModel.of(team,
                        linkTo(methodOn(TeamController.class).getTeam(team.getId())).withSelfRel(),
                        linkTo(methodOn(TeamController.class).getAllTeams()).withRel("teams")))
                .toList();

        return ResponseEntity.created(location).body(CollectionModel.of(teamEntityModels,
                linkTo(methodOn(TeamController.class).getAllTeams()).withSelfRel()));
    }
    

PreFilter

  • Filter는 컬렉션, 리스트만 사용가능하다.
    @PostMapping("/filter")
    @PreFilter("filterObject.name != 'test'")
    public List<TeamDTO> getTeamsByFilter(@RequestBody List<TeamDTO> teams) {
        return teams;
    }
    

PostFilter

    @PostMapping("/filter")
//    @PreFilter("filterObject.name != 'test'")
    @PostFilter("filterObject.name != 'test'")
    public List<TeamDTO> getTeamsByFilter(@RequestBody List<TeamDTO> teams) {
        return teams;
    }
    



profile
백엔드 개발자가 꿈인 컴공과

0개의 댓글

관련 채용 정보