Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to propagate spring security login to EJBs?

Context

I have a J2EE application running on a JBoss 4.2.3 application server. The application is reachable through a web interface. The authentication is done with basic authentication. Inside of the EJBs I ask the security context of the bean for the principal (the name of the logged in user) and do some authorization checks if this user is allowed to access this method of the EJB. The EJBs life inside a different ear than the servlets handling the web frontend, so I can't access the spring application context directly.

Required change

I want to switch to Spring Security for handling the user login.

Question

How can I propagate the spring login information to the JBoss security context so I can still use my EJBs without having to rewrite them?


Ideas and links

I already found a page talking about "Propagating Identity from Spring Security to the EJB Layer", but unfortunatelly it refers to an older version of Spring Security (Acegi) and I'm not familiar enough with Spring Security to make this work with the actual version (3.0.2).

Here is something that looks similar using WebLogic.

like image 268
tangens Avatar asked May 02 '10 09:05

tangens


1 Answers

If you properly configure spring-security (filter in filter chain, security-context.xml), you may use annotation @Secured, to restrict users with needed user roles. You may use this annotation on class level or/and method level.

If you need to know all authorization info about current user, you may use this helper (i wrote this for my webapp, but it maybe useful for other. MyUserDetails is a service bean, the spring-security's UserDetail descendant.):

public class LoginHelper {

    /**
     * @return user object if user is authenticated and null if is not
     */
    public static User getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof MyUserDetails) {
                return ((MyUserDetails) principal).getUser();
            }
        }
        return null;
    }

    /**
     * Check for authenticated user
     *
     * @return true if user is authenticated and false if is not
     */
    public static boolean isAuthenticated() {
        final User user = getUser();
        return user != null;
    }

}
like image 112
Yuri.Bulkin Avatar answered Sep 30 '22 16:09

Yuri.Bulkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!