복붙노트

[SPRING] 사용자가 자신의 프로필 만 업데이트하도록 스프링 부트 보안을 구성하는 방법

SPRING

사용자가 자신의 프로필 만 업데이트하도록 스프링 부트 보안을 구성하는 방법

필자는 웹 서비스 보안을 위해 기본 스프링 부트 보안을 구현했습니다. 일부 사용자 역할에만 일부 서비스에 대한 액세스 권한을 부여 할 수 있지만 특정 사용자 (동적 사용자 일 수 있음)에 대한 액세스 권한을 부여 할 수도 있습니다.

모든 사용자가 자신의 프로필을 가지고있는 소셜 앱이 있다고 가정 해 보겠습니다. 다음 휴식 서비스를 사용하면 프로필을 수정할 수있는 유일한 서비스가 있어야합니다.

@RestController
public class UserController {
    @RequestMapping(method = RequestMethod.PUT, path = "/user/{userId}", ...)
    public UserDetails updateUserDetails(@PathVariable("userId") String userId) {
        // code for updating the description for the specified user
    }}
}

스프링 보안으로 어떻게하면 사용자 만이 개인 프로파일을 업데이트 할 수 있습니까? 다른 사용자는 거부해야합니다. 이 동작을 구성 할 수있는 우아한 방법이 있습니까?

내 WebSecurityConfig 내부에서 그 방법을 찾으려고했지만 성공하지 못했습니다.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    // configure authorization for urls
                    .authorizeRequests()
                    // grant access to all users for root path and /home
                    //.antMatchers("/", "/home").permitAll()
                    // here i would like to grant access in the way, that only the user is allowed to perform this request by calling url with his userId
                    .antMatchers(HttpMethod.PUT,"/user/<userId>").and().httpBasic();
      }

이 동작을 구현하는 좋은 접근 방법은 무엇입니까?

해결법

  1. ==============================

    1.나는 이런 식으로 구현하는 가장 좋은 방법은 컨트롤러 (이 요청에 대한 로그인 사용자가 포함 된 개체) 주입 및 사용자 ID 또는 사용자 이름이 일치하는지 확인하는 것입니다 생각합니다.

    나는 이런 식으로 구현하는 가장 좋은 방법은 컨트롤러 (이 요청에 대한 로그인 사용자가 포함 된 개체) 주입 및 사용자 ID 또는 사용자 이름이 일치하는지 확인하는 것입니다 생각합니다.

    @RestController
    public class UserController {
        @RequestMapping(method = RequestMethod.PUT, path = "/user/{userId}", ...)
        public UserDetails updateUserDetails(@PathVariable("userId") String userId, Principal principal) {
    
            CustomUserDetails userDetails = (CustomUserDetails) principal;
            if (userDetails.getUserId().equals(userId)) {
                // Update the user
            }
        }}
    }
    

    기본적으로 사용자 이름 만 제공 했으므로 사용자 ID를 추가하려면 사용자 정의 UserDetails 인터페이스가 필요합니다. 방법을 알고 싶다면이 질문을 확인하십시오.

  2. ==============================

    2.@PreAuthorize 주석 사용 :

    @PreAuthorize 주석 사용 :

    @PreAuthorize("#userId == principal.userId")
    @RequestMapping(method = RequestMethod.PUT, path = "/user/{userId}", ...)
    public UserDetails updateUserDetails(@PathVariable("userId") String userId) {
        // code for updating the description for the specified user
    }
    

    여기서는 UserDetails 인터페이스를 구현하는 클래스에 userId 속성이 있다고 가정합니다.

  3. from https://stackoverflow.com/questions/45536894/how-to-configure-spring-boot-security-so-that-a-user-is-only-allowed-to-update-t by cc-by-sa and MIT license