Autowired annotation returns null in AuthenticationSuccessHandler - java

In my Spring Security application, I am trying to return cookie 'remember_token' after successful login. My AuthenticanSuccessHandler class auto wires RememberMeService class to get 'token' value from database. But autowired reference rememberMeService returns null. I did mention #Component annotation for the class, but it did not change the result. Link to complete source code
FormAuthenticationSuccessHandler:
package com.fastcheck.timesheet.common.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import com.fastcheck.timesheet.common.services.RememberMeService;
#Component
public class FormAuthenticationSuccessHandler implements AuthenticationSuccessHandler
{
#Autowired
public RememberMeService rememberMeService;
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException
{
String username;
Object principal = authentication.getPrincipal();
if (principal instanceof UserDetails)
{
username = ((UserDetails)principal).getUsername();
}
else
{
username = principal.toString();
}
System.out.println("rememberMeService :"+rememberMeService);
if(rememberMeService != null)
{
Cookie cookie=new Cookie("remember_token",rememberMeService.getRememberMeToken(username));
cookie.setMaxAge(200);
response.addCookie(cookie);
}
response.setStatus(200);
response.sendRedirect("home");
}
}

What I understand from your code is that you are trying to achieve what spring security is created to do out-of-the-box for you.
If you implemented spring security properly, I don't see why remember-me token will not be stored automatically on the user's browser after a successful authentication as you are trying to do.

Remember token automatically sent to the browser. You don't need to send it separately. Would it be possible to provide cookie value returned by browser? otherwise please use below script to decode it.
String cookieAsPlainText = new String(Base64.decode(cookies[i].getValue());
cookieAsPlainText as plain value should be series:token format. Please let me know if this helps

Related

Spring boot - find username from session cookie value

I am currently working on a spring boot application, and I've got a handler which takes the HttpServletRequest as an argument.
I was wondering, is it possible to invoke a bean that - provided the session cookie - can return the information of who made the request? (e.g. username)
In the end I found this way to make the code work in the desired way.
package org.my.package;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.csrf.InvalidCsrfTokenException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static org.springframework.security.web.context.HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY;
#Slf4j
#Configuration
public class CsrfDeniedHandlerConfig {
#AllArgsConstructor
static class CsrfDeniedHandler implements AccessDeniedHandler {
private final AccessDeniedHandler accessDeniedHandler;
#Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
if (accessDeniedException.getClass().equals(InvalidCsrfTokenException.class)) {
SecurityContextImpl securityContext = (SecurityContextImpl) request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY);
User user = (User) securityContext.getAuthentication().getPrincipal();
log.error("Invalid CSRF token request from {}: {}", user.getUsername().toUpperCase(), accessDeniedException.getMessage());
}
accessDeniedHandler.handle(request, response, accessDeniedException);
}
}
#Bean
public AccessDeniedHandler csrfDeniedHandler() {
return new CsrfDeniedHandler(new AccessDeniedHandlerImpl());
}
}

Should JWT be a separate auth micro-service and not sit with the backend business logic?

I am new to the micro-services architecture , I am building application using SpringBoot and wanted to add JWT auth for my APIs .
Ref link : https://dzone.com/articles/spring-boot-security-json-web-tokenjwt-hello-world
I was wondering if I should separate out the authentication / authorization code from the business-micro-service(BMS) . So each time a rest API call to BMS would in turn call the auth-microservice for validation . Would this be a good practice or would it be a lot on the network traffic ?
Calls might look like :
Client -> BusinessApp -> AuthMS -> Business App -> Client
The reason of separating it out is that there is some configuration and code that would not look good coupled with business app , but I am unsure of the network cost it would take for each API call.
Example code in JWT app which would make sense to be in different service / server running ? :
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.javainuse.service.JwtUserDetailsService;
import com.javainuse.config.JwtTokenUtil;
import com.javainuse.model.JwtRequest;
import com.javainuse.model.JwtResponse;
#RestController
#CrossOrigin
public class JwtAuthenticationController {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private JwtTokenUtil jwtTokenUtil;
#Autowired
private JwtUserDetailsService userDetailsService;
#RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(#RequestBody JwtRequest authenticationRequest) throws Exception {
authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
final UserDetails userDetails = userDetailsService
.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(userDetails);
return ResponseEntity.ok(new JwtResponse(token));
}
private void authenticate(String username, String password) throws Exception {
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
} catch (DisabledException e) {
throw new Exception("USER_DISABLED", e);
} catch (BadCredentialsException e) {
throw new Exception("INVALID_CREDENTIALS", e);
}
}
}
It is a good practice to let your api gateway handle all the authorization requests.
The request will pass through the api gateway where it will be validated and only then have access to the micro-service (where the business logic is there). Let your gateway take care of the following:
(1) validate tokens with every request
(2) prevent all unauthenticated requests to the services
Check this out for more details

Remember me in REST using Spring security

I need to create "Remember me"-provided REST service. My app should receive JSON with login data, authenticate user and make it possible for app to remember the user. I've written some code snippet with few mocked #RequestMapping's and simple Spring security config, and, however, application authenticates user (because of successfulAuthentication() Filter's method invocation). But when I'm trying to send request to the secured url even after login action, it returns 401 code. I know, this is quite obvious that new request creates a new session, but is there any way to perform "remember me" behaviour without sending login info in each Request's body? Here is some of my code:
package com.checkpoint.aimer.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
public class RestSecurityFilter extends AbstractAuthenticationProcessingFilter{
public RestSecurityFilter(String url, AuthenticationManager m) {
super(url);
this.setAuthenticationManager(m);
}
#Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException,
IOException, ServletException {
HttpSession session = request.getSession();
Authentication auth = this.getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken("roman", "sawawluha"));
SecurityContextHolder.getContext().setAuthentication(auth);
return auth;
}
}
Security configuration:
package com.checkpoint.aimer.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
#Configuration
#EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
public RestSecurityFilter restSecurity() throws Exception {
RestSecurityFilter filter = new RestSecurityFilter("/auth/login_test", authenticationManagerBean());
return filter;
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public UserDetailsService usr() {
return new UserSecurityService();
}
#Override
public void configure(HttpSecurity http) throws Exception{
http
.httpBasic().authenticationEntryPoint(new AuthenticationEntryPoint() {
#Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException arg2) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Oops");
}
}).and()
.addFilterBefore(restSecurity(),BasicAuthenticationFilter.class )
.rememberMe().rememberMeServices(new TokenBasedRememberMeServices("key",usr()) ).and()
.authorizeRequests()
.antMatchers("/**").hasRole("USER")
.antMatchers("/auth/**").anonymous()
.and()
.csrf().disable()
.logout().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception{
auth
.userDetailsService(usr());
}
}
Do you have any ideas?
Remember me features are mostly implemented based on cookies. You can store some authentication token into cookie. I believe you can even use Session Cookies for this.
BUT REMEMBER:
You have to use HTTPS all the time
Use HttpOnly cookie attribute all the time
Use Secure cookie attribute all the time
Because cookie is send to client with every request, you need to make sure it's send via secure channel, and not accessible to cross site attacks.

How to close user session/auth. context after access token is sent for a user/client in Spring OAuth2

I am implementing an app, let's call it OAuth2Client, whose authentication/authorization layer is managed with the spring OAuth2 protocol implementation on a different server, OAuth2Server.
Everything is working great so far, I just want to divert a little bit from the "normal" OAuth2 flow.
So for example, in my third party app OAuth2Client, when users wants to log in, they have to authenticate via OAuth2Server.
We then have the familiar OAuth2 flow where the user is redirected to the authentication page of the OAuth2Server, enters credentials, is asked for the permission to access his/her data etc.
If authentication is successful, he is redirected to the 'redirect_uri' registered with the OAuth2Client app, with the auth. 'code' included in the request. OAuth2Client then exchanges this 'code' with an 'access token' via an api call to the access token endpoint on the OAuth2Server.
What I want to do is close the user session/authentication context immediately after the user has successfully authenticated and has been provided with an access token.
I thought of using a filter to do that but I am not sure whether that's the best solution.
Any help would be appreciated
thanks in advance...
I don't think you can attach the session event to the /token endpoint, but the session is actually not needed any more after the user has approved the grant and the authorization code is issued. So this would work:
#Controller
#SessionAttributes("authorizationRequest")
public class ApprovalEndpoint {
#RequestMapping("/oauth/confirm_access")
public ModelAndView getAccessConfirmation(Map<String, Object> model, HttpServletRequest request, SessionStatus status) throws Exception {
String template = createTemplate(model, request);
if (request.getAttribute("_csrf") != null) {
model.put("_csrf", request.getAttribute("_csrf"));
}
status.setComplete();
return new ModelAndView(new SpelView(template), model);
}
}
Or you could use a Filter as you suggest, but since you probably want to customize the user experience for approval anyway, you might as well do it via this endpoint.
My oauth clients are set to autoApprove(true) , so I cannot do as Dave says.
My solution is mapping /oauth/authorize to another endpoint ,and inject the origin AuthorizationEndpoint, after origin Endpoint finish his work, call request.getSession().invalidate();
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;
#Controller
#RequestMapping
#SessionAttributes({SessionClosedAuthorizationEndpoint.AUTHORIZATION_REQUEST_ATTR_NAME, SessionClosedAuthorizationEndpoint.ORIGINAL_AUTHORIZATION_REQUEST_ATTR_NAME})
public class SessionClosedAuthorizationEndpoint {
private AuthorizationEndpoint authorizationEndpoint;
#Autowired
public void setAuthorizationEndpoint(AuthorizationEndpoint authorizationEndpoint) {
this.authorizationEndpoint = authorizationEndpoint;
}
static final String AUTHORIZATION_REQUEST_ATTR_NAME = "authorizationRequest";
static final String ORIGINAL_AUTHORIZATION_REQUEST_ATTR_NAME = "org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.ORIGINAL_AUTHORIZATION_REQUEST";
#RequestMapping(value = "/oauth/authorize/custom")
public ModelAndView authorize(HttpServletRequest request, Map<String, Object> model, #RequestParam Map<String, String> parameters, SessionStatus sessionStatus, Principal principal) {
ModelAndView authorize = authorizationEndpoint.authorize(model, parameters, sessionStatus, principal);
request.getSession().invalidate();
return authorize;
}
#RequestMapping(value = "/oauth/authorize/custom", method = RequestMethod.POST, params = OAuth2Utils.USER_OAUTH_APPROVAL)
public View approveOrDeny(#RequestParam Map<String, String> approvalParameters, Map<String, ?> model,
SessionStatus sessionStatus, Principal principal){
return authorizationEndpoint.approveOrDeny(approvalParameters,model,sessionStatus,principal);
}
}

The httpsession which i get from modifyHandshake is not the correct session,why? [duplicate]

Is it possible to get the HttpServletRequest inside a #ServerEndpoint? Primarily I am trying to get it so I can access the HttpSession object.
Update (November 2016): The information provided in this answer is for the JSR356 spec, individual implementations of the spec may vary outside of this information. Other suggestions found in comments and other answers are all implementation specific behaviors outside of the JSR356 spec.
If the suggestions in here are causing you problems, upgrade your various installations of Jetty, Tomcat, Wildfly, or Glassfish/Tyrus. All current versions of those implementations have all been reported to work in the way outlined below.
Now back to the original answer from August 2013...
The answer from Martin Andersson has a concurrency flaw. The Configurator can be called by multiple threads at the same time, it is likely that you will not have access to the correct HttpSession object between the calls from modifyHandshake() and getEndpointInstance().
Or said another way...
Request A
Modify Handshake A
Request B
Modify Handshake B
Get Endpoint Instance A <-- this would have Request B's HttpSession
Get Endpoint Instance B
Here's a modification to Martin's code that uses ServerEndpointConfig.getUserProperties() map to make the HttpSession available to your socket instance during the #OnOpen method call
GetHttpSessionConfigurator.java
package examples;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator
{
#Override
public void modifyHandshake(ServerEndpointConfig config,
HandshakeRequest request,
HandshakeResponse response)
{
HttpSession httpSession = (HttpSession)request.getHttpSession();
config.getUserProperties().put(HttpSession.class.getName(),httpSession);
}
}
GetHttpSessionSocket.java
package examples;
import java.io.IOException;
import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint(value = "/example",
configurator = GetHttpSessionConfigurator.class)
public class GetHttpSessionSocket
{
private Session wsSession;
private HttpSession httpSession;
#OnOpen
public void open(Session session, EndpointConfig config) {
this.wsSession = session;
this.httpSession = (HttpSession) config.getUserProperties()
.get(HttpSession.class.getName());
}
#OnMessage
public void echo(String msg) throws IOException {
wsSession.getBasicRemote().sendText(msg);
}
}
Bonus feature: no instanceof or casting required.
Some EndpointConfig Knowledge
EndpointConfig objects do exist per "Endpoint Instance".
However, an "Endpoint Instance" has 2 meanings with the spec.
Default behavior of the JSR, where each incoming upgrade request results in a new object instance of the endpoint class
A javax.websocket.Session that ties together the object endpoint instance, with its configuration, to a specific logical connection.
It is possible to have a singleton Endpoint instance being used for multiple javax.websocket.Session instances (that is one of the features that ServerEndpointConfig.Configurator supports)
The ServerContainer implementation will track a set of ServerEndpointConfig's that represent all of the deployed endpoints that the server can respond to a websocket upgrade request.
These ServerEndpointConfig object instances can come from a few different sources.
Manually provided by the javax.websocket.server.ServerContainer.addEndpoint(ServerEndpointConfig)
Usually done within a javax.servlet.ServletContextInitializer.contextInitialized(ServletContextEvent sce) call
From the javax.websocket.server.ServerApplicationConfig.getEndpointConfigs(Set) call.
Automatically created from scanning of the web application for #ServerEndpoint annotated classes.
These ServerEndpointConfig object instances exist as defaults for when a javax.websocket.Session does eventually get created.
ServerEndpointConfig.Configurator Instance
Before any upgrade requests are received or processed, all of the ServerEndpointConfig.Configurator objects now exist and are ready to perform their main and sole purpose, to allow for customization of the upgrade process of a websocket connection to an eventual javax.websocket.Session
Access to Session specific EndpointConfig
Note, you cannot access the ServerEndpointConfig object instances from within a endpoint instance. You can only access EndpointConfig instances.
This means if you provided ServerContainer.addEndpoint(new MyCustomServerEndpointConfig()) during deploy and later tried to access it via the annotations, it will not work.
All of the following would be invalid.
#OnOpen
public void onOpen(Session session, EndpointConfig config)
{
MyCustomServerEndpointConfig myconfig = (MyCustomServerEndpointConfig) config;
/* this would fail as the config is cannot be cast around like that */
}
// --- or ---
#OnOpen
public void onOpen(Session session, ServerEndpointConfig config)
{
/* For #OnOpen, the websocket implementation would assume
that the ServerEndpointConfig to be a declared PathParam
*/
}
// --- or ---
#OnOpen
public void onOpen(Session session, MyCustomServerEndpointConfig config)
{
/* Again, for #OnOpen, the websocket implementation would assume
that the MyCustomServerEndpointConfig to be a declared PathParam
*/
}
You can access the EndpointConfig during the life of the Endpoint object instance, but under a limited time. The javax.websocket.Endpoint.onOpen(Session,Endpoint), annotated #OnOpen methods, or via the use of CDI. The EndpointConfig is not available in any other way or at any other time.
However, you can always access the UserProperties via the Session.getUserProperties() call, which is available always. This User Properties map is always available, be it via the annotated techniques (such as a Session parameter during #OnOpen, #OnClose, #OnError, or #OnMessage calls), via CDI injection of the Session, or even with the use of non-annotated websockets that extend from javax.websocket.Endpoint.
How Upgrade Works
As stated before, every one of the defined endpoints will have a ServerEndpointConfig associated with it.
Those ServerEndpointConfigs are a single instance that represents the default state of the EndpointConfig that are eventually made available to the Endpoint Instances that are possibly and eventually created.
When a incoming upgrade request arrives, it has go through the following on the JSR.
does the path match any of the ServerEndpointConfig.getPath() entries
If no match, return 404 to upgrade
pass upgrade request into ServerEndpointConfig.Configurator.checkOrigin()
If not valid, return error to upgrade response
create HandshakeResponse
pass upgrade request into ServerEndpointConfig.Configurator.getNegotiatedSubprotocol()
store answer in HandshakeResponse
pass upgrade request into ServerEndpointConfig.Configurator.getNegotiatedExtensions()
store answer in HandshakeResponse
Create new endpoint specific ServerEndpointConfig object. copy encoders, decoders, and User Properties. This new ServerEndpointConfig wraps default for path, extensions, endpoint class, subprotocols, configurator.
pass upgrade request, response, and new ServerEndpointConfig into ServerEndpointConfig.Configurator.modifyHandshake()
call ServerEndpointConfig.getEndpointClass()
use class on ServerEndpointConfig.Configurator.getEndpointInstance(Class)
create Session, associate endpoint instance and EndpointConfig object.
Inform endpoint instance of connect
annotated methods that want EndpointConfig gets the one associated with this Session.
calls to Session.getUserProperties() returns EndpointConfig.getUserProperties()
To note, the ServerEndpointConfig.Configurator is a singleton, per mapped ServerContainer endpoint.
This is intentional, and desired, to allow implementors several features.
to return the same Endpoint instance for multiple peers if they so desire. The so called stateless approach to websocket writing.
to have a single point of management of expensive resources for all Endpoint instances
If the implementations created a new Configurator for every handshake, this technique would not be possible.
(Disclosure: I write and maintain the JSR-356 implementation for Jetty 9)
Preface
It's unclear whether you're wanting the HttpServletRequest, the HttpSession, or properties out of the HttpSession. My answer will show how to get the HttpSession or individual properties.
I've omitted null and index bounds checks for brevity.
Cautions
It's tricky. The answer from Martin Andersson is not correct because the same instance of ServerEndpointConfig.Configurator is used for every connection, hence a race condition exists. While the docs state that "The implementation creates a new instance of the configurator per logical endpoint," the spec does not clearly define a "logical endpoint." Based on the context of all the places that phrase is used, it appears to mean the binding of a class, configurator, path, and other options, i.e., a ServerEndpointConfig, which is clearly shared. Anyway you can easily see if an implementation is using the same instance by printing out its toString() from within modifyHandshake(...).
More surprisingly the answer from Joakim Erdfelt also does not work reliably. The text of JSR 356 itself does not mention EndpointConfig.getUserProperties(), it is only in the JavaDoc, and nowhere does it seem to be specified what its exact relationship is to Session.getUserProperties(). In practice some implementations (e.g., Glassfish) return the same Map instance for all calls to ServerEndpointConfig.getUserProperties() while others (e.g., Tomcat 8) don't. You can check by printing out the map contents before modifying it within modifyHandshake(...).
To verify, I copied the code directly from the other answers and then tested it against a multithreaded client I wrote. In both cases I observed the incorrect session being associated with the endpoint instance.
Outline of Solutions
I've developed two solutions, which I've verified work correctly when tested against a multithreaded client. There are two key tricks.
First, use a filter with the same path as the WebSocket. This will give you access to the HttpServletRequest and HttpSession. It also gives you a chance to create a session if it doesn't already exist (although in that case using an HTTP session at all seems dubious).
Second, find some properties that exist in both the WebSocket Session and HttpServletRequest or HttpSession. It turns out there are two candidates: getUserPrincipal() and getRequestParameterMap(). I will show you how to abuse both of them :)
Solution using User Principal
The easiest way is to take advantage of Session.getUserPrincipal() and HttpServletRequest.getUserPrincipal(). The downside is this could interfere with other legitimate uses of this property, so use it only if you are prepared for those implications.
If you want to store just one string, such as a user ID, this is actually not too much of an abuse, though it presumably should be set in some container managed way rather than overriding the wrapper as I'll show you. Anyway you would do that by just overriding Principal.getName(). Then you don't even need to cast it in the Endpoint. But if you can stomach it, you can also pass the whole HttpSession object as follows.
PrincipalWithSession.java
package example1;
import java.security.Principal;
import javax.servlet.http.HttpSession;
public class PrincipalWithSession implements Principal {
private final HttpSession session;
public PrincipalWithSession(HttpSession session) {
this.session = session;
}
public HttpSession getSession() {
return session;
}
#Override
public String getName() {
return ""; // whatever is appropriate for your app, e.g., user ID
}
}
WebSocketFilter.java
package example1;
import java.io.IOException;
import java.security.Principal;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
#WebFilter("/example1")
public class WebSocketFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
final PrincipalWithSession p = new PrincipalWithSession(httpRequest.getSession());
HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(httpRequest) {
#Override
public Principal getUserPrincipal() {
return p;
}
};
chain.doFilter(wrappedRequest, response);
}
public void init(FilterConfig config) throws ServletException { }
public void destroy() { }
}
WebSocketEndpoint.java
package example1;
import javax.servlet.http.HttpSession;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/example1")
public class WebSocketEndpoint {
private HttpSession httpSession;
#OnOpen
public void onOpen(Session webSocketSession) {
httpSession = ((PrincipalWithSession) webSocketSession.getUserPrincipal()).getSession();
}
#OnMessage
public String demo(String msg) {
return msg + "; (example 1) session ID " + httpSession.getId();
}
}
Solution Using Request Parameters
The second option uses Session.getRequestParameterMap() and HttpServletRequest.getParameterMap(). Note that it uses ServerEndpointConfig.getUserProperties() but it is safe in this case because we're always putting the same object into the map, so whether it's shared makes no difference. The unique session identifier is passed not through the user parameters but instead through the request parameters, which is unique per request.
This solution is slightly less hacky because it does not interfere with the user principal property. Note that if you need to pass through the actual request parameters in addition to the one that's inserted, you can easily do so: just start with the existing request parameter map instead of a new empty one as shown here. But take care that the user cannot spoof the special parameter added in the filter by supplying their own request parameter by the same name in the actual HTTP request.
SessionTracker.java
/* A simple, typical, general-purpose servlet session tracker */
package example2;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
#WebListener
public class SessionTracker implements ServletContextListener, HttpSessionListener {
private final ConcurrentMap<String, HttpSession> sessions = new ConcurrentHashMap<>();
#Override
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute(getClass().getName(), this);
}
#Override
public void contextDestroyed(ServletContextEvent event) {
}
#Override
public void sessionCreated(HttpSessionEvent event) {
sessions.put(event.getSession().getId(), event.getSession());
}
#Override
public void sessionDestroyed(HttpSessionEvent event) {
sessions.remove(event.getSession().getId());
}
public HttpSession getSessionById(String id) {
return sessions.get(id);
}
}
WebSocketFilter.java
package example2;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
#WebFilter("/example2")
public class WebSocketFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
final Map<String, String[]> fakedParams = Collections.singletonMap("sessionId",
new String[] { httpRequest.getSession().getId() });
HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(httpRequest) {
#Override
public Map<String, String[]> getParameterMap() {
return fakedParams;
}
};
chain.doFilter(wrappedRequest, response);
}
#Override
public void init(FilterConfig config) throws ServletException { }
#Override
public void destroy() { }
}
WebSocketEndpoint.java
package example2;
import javax.servlet.http.HttpSession;
import javax.websocket.EndpointConfig;
import javax.websocket.HandshakeResponse;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
#ServerEndpoint(value = "/example2", configurator = WebSocketEndpoint.Configurator.class)
public class WebSocketEndpoint {
private HttpSession httpSession;
#OnOpen
public void onOpen(Session webSocketSession, EndpointConfig config) {
String sessionId = webSocketSession.getRequestParameterMap().get("sessionId").get(0);
SessionTracker tracker =
(SessionTracker) config.getUserProperties().get(SessionTracker.class.getName());
httpSession = tracker.getSessionById(sessionId);
}
#OnMessage
public String demo(String msg) {
return msg + "; (example 2) session ID " + httpSession.getId();
}
public static class Configurator extends ServerEndpointConfig.Configurator {
#Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request,
HandshakeResponse response) {
Object tracker = ((HttpSession) request.getHttpSession()).getServletContext().getAttribute(
SessionTracker.class.getName());
// This is safe to do because it's the same instance of SessionTracker all the time
sec.getUserProperties().put(SessionTracker.class.getName(), tracker);
super.modifyHandshake(sec, request, response);
}
}
}
Solution for Single Properties
If you only need certain properties out of the HttpSession and not the whole HttpSession itself, like say a user ID, then you could do away with the whole SessionTracker business and just put the necessary parameters in the map you return from your override of HttpServletRequestWrapper.getParameterMap(). Then you can also get rid of the custom Configurator; your properties will be conveniently accessible from Session.getRequestParameterMap() in the Endpoint.
WebSocketFilter.java
package example5;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
#WebFilter("/example5")
public class WebSocketFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
final Map<String, String[]> props = new HashMap<>();
// Add properties of interest from session; session ID
// is just for example
props.put("sessionId", new String[] { httpRequest.getSession().getId() });
HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(httpRequest) {
#Override
public Map<String, String[]> getParameterMap() {
return props;
}
};
chain.doFilter(wrappedRequest, response);
}
#Override
public void destroy() {
}
#Override
public void init(FilterConfig arg0) throws ServletException {
}
}
WebSocketEndpoint.java
package example5;
import java.util.List;
import java.util.Map;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/example5")
public class WebSocketEndpoint {
private Map<String, List<String>> params;
#OnOpen
public void onOpen(Session session) {
params = session.getRequestParameterMap();
}
#OnMessage
public String demo(String msg) {
return msg + "; (example 5) session ID " + params.get("sessionId").get(0);
}
}
Is it possible?
Let's review the Java API for WebSocket specification to see if getting hold of the HttpSession object is possible. The specification says on page 29:
Because websocket connections are initiated with an http request,
there is an association between the HttpSession under which a client
is operating and any websockets that are established within that
HttpSession. The API allows access in the opening handshake to the
unique HttpSession corresponding to that same client.
So yes it is possible.
However, I don't think it is possible for you to get hold of a reference to the HttpServletRequest object though. You could listen for all new servlet requests using a ServletRequestListener, but you would still have to figure out which request belong to which server endpoint. Please let me know if you find a solution!
Abstract how-to
How-to is loosely described on pages 13 and 14 in the specification and exemplified by me in code under the next heading.
In English, we will need to intercept the handshake process to get hold of a HttpSession object. To then transfer the HttpSession reference to our server endpoint, we also need to intercept when the container creates the server endpoint instance and manually inject the reference. We do all of this by providing our own ServerEndpointConfig.Configurator and override the methods modifyHandshake() and getEndpointInstance().
The custom configurator will be instantiated once per logical ServerEndpoint (See the JavaDoc).
Code example
This is the server endpoint class (I provide the implementation of the CustomConfigurator class after this code snippet):
#ServerEndpoint(value = "/myserverendpoint", configurator = CustomConfigurator.class)
public class MyServerEndpoint
{
private HttpSession httpSession;
public void setHttpSession(HttpSession httpSession) {
if (this.httpSession != null) {
throw new IllegalStateException("HttpSession has already been set!");
}
this.httpSession = httpSession;
}
#OnOpen
public void onOpen(Session session, EndpointConfig config) {
System.out.println("My Session Id: " + httpSession.getId());
}
}
And this is the custom configurator:
public class CustomConfigurator extends ServerEndpointConfig.Configurator
{
private HttpSession httpSession;
// modifyHandshake() is called before getEndpointInstance()!
#Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
httpSession = (HttpSession) request.getHttpSession();
super.modifyHandshake(sec, request, response);
}
#Override
public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
T endpoint = super.getEndpointInstance(endpointClass);
if (endpoint instanceof MyServerEndpoint) {
// The injection point:
((MyServerEndpoint) endpoint).setHttpSession(httpSession);
}
else {
throw new InstantiationException(
MessageFormat.format("Expected instanceof \"{0}\". Got instanceof \"{1}\".",
MyServerEndpoint.class, endpoint.getClass()));
}
return endpoint;
}
}
All above answers worth reading, but none of them solves OP's (and my) problem.
You can access HttpSession when a WS end point is opening and pass it to newly created end point instance but no one guarantees there exist HttpSession instance!
So we need step 0 before this hacking (I hate JSR 365 implementation of WebSocket).
Websocket - httpSession returns null
All possible solutions are based upon:
A. Client browser implementations maintains Session ID via Cookie value passed as an HTTP Header, or (if cookies are disabled) it is managed by Servlet container which will generate Session ID postfix for generated URLs
B. You can access HTTP Request Headers only during HTTP handshake; after that, it is Websocket Protocol
So that...
Solution 1: use "handshake" to access HTTP
Solution 2: In your JavaScript on the client side, dynamically generate HTTP Session ID parameter and send first message (via Websocket) containing this Session ID. Connect "endpoint" to the cache / utility class maintaining Session ID -> Session mapping; avoid memory leaks, you can use Session Listener for instance to remove session from cache.
P.S. I appreciate answers from Martin Andersson and Joakim Erdfelt.
Unfortunately, solution of Martin is not thread safe...
The only way that works across all applications servers is use ThreadLocal. See:
https://java.net/jira/browse/WEBSOCKET_SPEC-235

Categories

Resources