Reputation: 5028
I have implemented a Java EE security realm that redirects users to login.jsp if they try and access a protected resource.
http://mywebapp/shopping_cart
which is mapped to ShoppingCartServlethttp://mywebapp/j_security_check
http://mywebapp/shopping_cart
Now I want to pull the user's details from the database but how can I when there are no parameters in the redirect request?
Their username was sent to http://mywebapp/j_security_check
but there are no parameters in the redirect request that j_security_check makes to http://mywebapp/shopping_cart
. So what method is used to access the user's details once they log in?
Upvotes: 3
Views: 2956
Reputation: 1108742
Create a filter which checks if the user is logged in while no associated User
object from the database is present in the session. Then, just load that data and put in session.
Basically,
@WebFilter("/*")
public class UserFilter implements Filter {
@EJB
private UserService service;
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
String remoteUser = request.getRemoteUser();
if (remoteUser != null) {
HttpSession session = request.getSession();
if (session.getAttribute("user") == null) {
User user = service.find(remoteUser);
session.setAttribute("user", user);
}
}
chain.doFilter(req, res);
}
// ...
}
Upvotes: 4