Reputation: 7647
In a filter I have added below role in the 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);
}
Then from controller in a rest api method, i check the authorization role as below,
@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);
}
}
But when i invoke above API it successfully print the sysout. But it should give me a 401 unauthorized error right?
Upvotes: 1
Views: 950
Reputation: 48123
Just enable method level security by:
@EnableGlobalMethodSecurity(prePostEnabled = true)
Upvotes: 2