How to get login attributes from a servlet/jsp or in web service? - Java @ Desk

Wednesday, July 3, 2013

How to get login attributes from a servlet/jsp or in web service?

There are scenarios where we may require the user name and password of the system from where the servlet request is coming.

What is the need to get the login attributes?
1) The very basic requirement to do that is to authenticate the user from where the request is coming. We may require to authenticate the user who is requesting for a servlet for security purposes.
2) To check for access rights. Say for example, we may block some user from accessing the servlet due to some violation. We can do the same in a servlet if we have the user information.

I would like to explain how to get login user name/username or password from the servlet request.

The below code is useful in a servlet.
String name = request.getUserPrincipal().getName();

String name = request.getRemoteUser();
The below code is useful when you are in a web service and wants the user info.
@Resource
WebServiceContext ctx; // Use this as a class variable.

SecurityContextHolderAwareRequestWrapper map = (SecurityContextHolderAwareRequestWrapper) ctx
                    .getMessageContext().get(MessageContext.SERVLET_REQUEST);

String name = map.getUserPrincipal().getName();

String name = map.getRemoteUser();
The below code is useful when you are in a JSP
${pageContext.request.userPrincipal.name}

${pageContext.request.remoteUser}







No comments:

Post a Comment