I have tomcat authentication (form authentication) in my application, after successful authentication ,I am able to get username by request.getRemoteUser() method in my servlet.where I can find request.getRemoteUser() code ? how this works ? where the RemoteUser has been setted and stored. since http requests are stateless and executes independently , how this giving the username in all subsequent requests??
CodePudding user response:
In order to deal with authentication, every context in Tomcat has a Valve
that extends AuthenticatorBase
, that:
- tries to authenticate the user using the data in the
HttpServletRequest
, - checks the authorization requirements for the URL,
- if authentication is required, but absent, sends an appropriate response to the browser, asking for authentication. This usually means a
401
response with aWWW-Authenticate
header for most authentication methods or a302
redirect to the login page for form authentication. - if authentication is present, but the access is not authorized, it sends a
403
response. - otherwise calls
Request#setUserPrincipal
and proceeds with the next valve.
For the details check the AuthenticatorBase#invoke
method.
Most authentication methods are based on the Authorization
header sent by the browser (the form authenticator uses request parameters).
If a session is present (e.g. you called HttpServletRequest#getSession
), the authenticated user will be cached in the session and subsequent requests will not need to authenticate any more. You can force session creation using the alwaysUseSession
attribute on the authenticator valves (cf. documentation). The server can recognize the presence of a previously established session through many methods:
- A
JSESSIONID
Cookie
header in the request, - A
jsessionid
path parameter in the URL, - If you use TLS, the TLS session can be also be used to detect the appropriate HTTP session.