简体   繁体   中英

Spring security @PreAuthorize(“hasAnyRole('…')”)

I am using spring security @PreAuthorise to check who and who cannot access methods in my service layer. It works really well. Usually my service methods are annotated with

@PreAuthorize("hasAnyRole('MY_USER_ROLE')")

My problem is that I have a war file made up of several jar files. Each of these jar files is responsible for a segment of business logic. I now want one of the services in one jar file to access another service in another jar file. This gets rejected because of the permissions. If I comment out the permission then everything works.

Is there anyway I can authenticate via spring before calling this service? (Perhaps with a dummy user?) Or perhaps turn off the security for jars within the same application? Or is my design wrong?

Anyone else has this sort of problem? What design should I use instead?

You need to give the thread that invokes the service (in the other jar) the permissions that are required by @PreAuthorize (for the invoked service).

If the thread is triggered in an web application by an user request, then this are normally the users permissions.

But if the thread is triggered by some timer service then you need to give them the right authentication

    Authentication authentication = new UsernamePasswordAuthenticationToken("dummy", "password");
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(authentication);

I believe this is a good example where you should use Spring security @Secured annotation

  • What is @Secured annotation?
    From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods. It provides support for JSR-250 annotation security as well as the framework's original @Secured annotation.

    Source: Spring Security 3.1 Reference 2.4 Method Security
    @Secured annotation allows you to put restrictions in your methods. For example, you can authorize a get() method to be accessible by all registered users. But for the edit() method, you can mark it be accessible by admins only.

Check out some tutorials at:
http://burtbeckwith.com/blog/?p=1398
http://krams915.blogspot.in/2010/12/spring-security-3-mvc-using-secured.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM