Spring Security Authentication不会给出401错误

时间:2016-01-17 13:49:02

标签: java spring spring-security spring-boot

在过滤器中,我在spring security context中添加了以下角色。

    @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未经授权的错误吗?

1 个答案:

答案 0 :(得分:2)

通过以下方式启用方法级安全性:

@EnableGlobalMethodSecurity(prePostEnabled = true)