我正在尝试了解Spring Security,并且我想知道如何使用我创建的权威创建自己的注释。我有这样的东西:
@PreAuthorize("hasAuthority('STANDARD')")
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface StandardRole {
}
@PreAuthorize("hasAuthority('ADMIN')")
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AdminRole {
}
实际上它看起来像:
@AdminRole
@StandardRole
@GetMapping(path = "user", produces = "application/json")
public ResponseEntity<User> getUser(@RequestParam String login) {
...
}
但是只有第一个注释有效,第二个被省略了。我想做一些类似@AllowRoles()
注释的事情,例如@允许({UserType. ADMIN,UserType.STANDARD})
或@允许({UserType.ADMIN})
。
我该怎么做?谢谢。
强行把门打开很可惜。
我在我的SecurityConfig类中使用了jsr250注释:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
在我的控制器中的@R药品
:
@RolesAllowed({UserType.TYPE_1, UserType.TYPE_2})
@GetMapping(path = "user", produces = "application/json")
public ResponseEntity<User> getUser() {
最后,在我实现用户详细信息
时:
private static final String PREFIX = "ROLE_";
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.singletonList(
new SimpleGrantedAuthority(
PREFIX + user.getUserType()));
}
我忘了“ROLE_”前缀。代码干净得多。