0

Java 11 で Spring Boot 2 と Spring Security 11 を使用しています。API のみのアプリケーションを作成し、「ユーザー」に関連するエンドポイントを保護しようとしています...

@Configuration
@EnableWebSecurity
class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    ...

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .csrf().disable()
        .exceptionHandling().authenticationEntryPoint(jwtUnAuthorizedResponseAuthenticationEntryPoint).and()
                .sessionManagement().sessionCreationPolicy(
                        SessionCreationPolicy.STATELESS).and()
        .authorizeRequests()
        .antMatchers("/api/users").access("hasRole('ADMIN')")
        .anyRequest().authenticated();

        http
        .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        http
        .headers()
        .frameOptions().sameOrigin()
        .cacheControl(); //disable caching
    }

ユーザー用にこの RestController があります...

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public ResponseEntity<List<User>> find() {
        List<User> foundUsers = userService.find();
        return ResponseEntity.ok(foundUsers);
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<User> read(@PathVariable("id") UUID id) {
        User foundUser = userService.findById(id);
        if (foundUser == null) {
            return ResponseEntity.notFound().build();
        } else {
            return ResponseEntity.ok(foundUser);
        }
    }
    
    @PostMapping
    @ResponseStatus(code = HttpStatus.CREATED)
    public void create(@Valid @RequestBody User user) {
        userService.create(user);
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<User> update(@RequestBody User card, @PathVariable UUID id) {
        final User updatedUser = userService.update(id, card);
        if (updatedUser == null) {
            return ResponseEntity.notFound().build();
        } else {
            return ResponseEntity.ok(updatedUser);
        }
    }

}

ログインしているユーザーの ID が要求の ID と一致する場合に、GET および PUT エンドポイントにアクセスできるようにセキュリティを拡張したいと考えています。そのためのルールを HttpSecurity に追加することは可能ですか? または、全員がそれらのエンドポイントにアクセスできるようにしてから、REST メソッドに Java を追加して、ログインしているユーザーをチェックすることはできますか?

4

1 に答える 1