Search code examples
jspservletsspring-securitypasswordsuserprincipal

Is pageContext.request.userPrincipal stored in session? Can I get password too?


I'm learning Spring security and as I understand by using request.getUserPrincipal() we could access the name, we could get the name with pageContext.request.userPrincipal.name ,

This is my code (everything is working) :

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page session="true"%>
<html>
    <body>
        <h5>Title : ${title}</h5>
        <h5>Message : ${message}</h5>


        <c:if test="${pageContext.request.userPrincipal.name != null}">
            <h2>Hi User : ${pageContext.request.userPrincipal.name}></h2> 
            <br>
        </c:if>

    </body>
</html>

my questions are:

1). Is this name on pageContext.request.userPrincipal.name retrieved from session? because there's <%@page session="true"%> on the top of the form

2). Is it possible to retrieve the password also? I mean something like pageContext.request.userPrincipal.password, if not how I could get the password in the form?

Thank you I really appreciate your help to get me understand this framework as I don't have enough money to buy some springs books, I'm just using some tutorials in the internet so your helps will be so much mean to me.


Solution

  • Is this name on pageContext.request.userPrincipal.name retrieved from session?

    No, it's retrieved from request, not from session. Under the covers, however, the security framework may store the internal identifier in the HTTP session. But this should be your least concern.

    There's by the way a shorter way to retrieve the principal name.

    ${pageContext.request.remoteUser}
    

    See also a.o. How to get login attributes from a servlet/jsp.


    because there's <%@page session="true"%> on the top of the form

    This has a different meaning and is the default already. By default, when a JSP is opened, it will implicitly create the HTTP session if not already created yet. This may not be desirable in pages which are designed to be stateless. Developers will then use <%@page session="false"%> to turn off implicit session creation and leave it to the servlet code. See also a.o. Can I turn off the HttpSession in web.xml?


    Is it possible to retrieve the password also? I mean something like pageContext.request.userPrincipal.password, if not how I could get the password in the form?

    Based on the question's comments I gather that you needed it in order to validate the login. This makes no sense. If the login was not valid, there would be no logged-in user in first place.