基于此处的其他答案,让我感到困惑的一件事是没有在OAuth2MethodSecurityExpressionHandler
.
确保在您MethodSecurityConfig
加载上下文以使上述答案起作用。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Autowired
private ApplicationContext context;
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
OAuth2MethodSecurityExpressionHandler handler = new OAuth2MethodSecurityExpressionHandler();
handler.setApplicationContext(context);
return handler;
}
}
然后就可以成功访问了
@PreAuthorize("hasRole(@environment.getProperty('role.rolename')")
public void method() {}