Hett
Hett

Reputation: 3825

EJB: how to check user is authenticated

Use logged throuth the JSP form:

@ManagedBean
@SessionScoped
public class LoginView {

    private String username; //+getter +setter
    private String password; //+getter +setter


    public String submit()
    {
        try {
            HttpServletRequest request = (HttpServletRequest) FacesContext
                    .getCurrentInstance()
                    .getExternalContext()
                    .getRequest();

            request.login(username, password);

        } catch (ServletException e) {
            FacesContext.getCurrentInstance().addMessage("login-form:username",
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Validation Error", "Incorrect login or password"));
            return "/login";
        }
        return "/index?faces-redirect=true";
    }
}

How to check user logged in thorug EJB?

Below example whan I need:

@Stateless
public class SessionServiceBean {

    @Resource
    SessionContext sessionContext;

    @EJB
    UserService userService;

    @Produces
    @Named
    @LoggedIn
    public User getLoggedUser() {
        if (/*  check user is logged */) {
            return userService.getByName(sessionContext.getCallerPrincipal().getName());
        }
    }

}

I foun only that the not logged use has name "anonymous", but it not better way, I think.

Upvotes: 0

Views: 898

Answers (1)

user1930502
user1930502

Reputation:

  1. You are using a @Stateless EJB. In a Stateless EJB, you are working with user sessions. This is probably not right and the bean should be @Stateful.
  2. I see no point in using EJBs in your example. Using pure CDI bean annotated with @SessionScoped would be sufficient.

You can store you user's session information directly in a session scoped bean. There is not need to use HttpServletRequest. For example:

@Named
@SessionScoped
public class UserSession implements Serializable {

    private User activeUser;

    public void logIn(User user) {
        this.activeUser = user;
    }

    public void logOut() {
        activeUser = null;
    }

    public boolean isLoggedIn() {
        return activeUser != null;
    }

    public User getActiveUser() {
        return activeUser;
    }

}

Upvotes: 1

Related Questions