Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Produces for the current user object in JSF2 and JAX-RS?

I've a simple @Stateless EJB that looks like this (stripped of all logging and error handling):

@Stateless
public class CurrentUserBean {
    @PersistenceContext
    private EntityManager em;

    @Produces @Named @LoggedIn
    @SessionScoped
    public User produceCurrentUser() {
        Principal principal = Faces.getExternalContext().getUserPrincipal();
        String username = (principal == null ? null : principal.getName());

        return em.createNamedQuery("findByLogin", User.class)
                .setParameter("login", username)
                .getSingleResult();
    }
}

Works fine when the user logs in with JSF. But the same user can also authenticate via webservice, where I can (need to?) get the user principal from SecurityContext in a bean controlled by JAX-RS (resteasy in my case):

public User doAuth(@Context SecurityContext ctx) {
    return em.createNamedQuery("findByLogin", User.class)
         .setParameter("login", ctx.getUserPrincial().getName())
         .getSingleResult();
}

How can I unify these approaches so that the production of the current user object is the responsibility of only one class?

like image 542
mabi Avatar asked Jan 30 '26 01:01

mabi


1 Answers

CDI allows you to inject the Principal directly. Just do this:

@Inject Principal userPrincipal;

And that will have the user name.

like image 106
John Ament Avatar answered Feb 01 '26 22:02

John Ament



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!