我正在使用带有 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 以检查已登录的用户?