在过滤器中,我在spring安全上下文中添加了以下角色。
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
GrantedAuthority authority = new SimpleGrantedAuthority(ANONYMOUS);
List<GrantedAuthority> grantedAuthority = new ArrayList<>();
grantedAuthority.add(authority);
Authentication authentication = new AnonymousAuthenticationToken(ANONYMOUS, ANONYMOUS, grantedAuthority);
SecurityContextHolder.getContext().setAuthentication(authentication);
arg2.doFilter(arg0,arg1);
}
然后从控制器使用rest api方法,如下所示检查授权角色,
@RestController
@RequestMapping(value = "/api")
public class MyController {
@RequestMapping(value = "/myservice1", method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_USER')")
public HttpEntity<String> myService() {
System.out.println("-----------myService invoke-----------");
return new ResponseEntity<String>(HttpStatus.OK);
}
}
但是,当我调用上述API时,它会成功打印sysout。但是它应该给我一个401未经授权的错误,对吗?
最佳答案
只需通过以下方法启用方法级别的安全性:
@EnableGlobalMethodSecurity(prePostEnabled = true)