@Override protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) { Object user=authResult.getPrincipal(); Assert.notNull(user,"通过Remember Me方式登录成功后未获取到用户信息"); HttpSession session=ContextHolder.getHttpSession(); IUser loginUser=null; if(user instanceof IUser){ loginUser=(IUser)user; }else if(user instanceof String){ loginUser=(IUser)userService.loadUserByUsername((String)user); }else{ throw new RuntimeException("Unsupport current principal["+user+"]"); } if(loginUser instanceof DefaultUser){ DefaultUser u=(DefaultUser)loginUser; u.setDepts(deptService.loadUserDepts(u.getUsername())); u.setPositions(positionService.loadUserPositions(u.getUsername())); u.setGroups(groupService.loadUserGroups(u.getUsername())); } session.setAttribute(ContextHolder.USER_LOGIN_WAY_KEY, "rememberMe"); session.setAttribute(ContextHolder.LOGIN_USER_SESSION_KEY, loginUser); this.doInterceptor(InterceptorType.success, new HttpRequestResponseHolder(request,response)); }
/** * Obtains the security context for the supplied request. For an unauthenticated user, an empty context * implementation should be returned. This method should not return null. * <p> * The use of the <tt>HttpRequestResponseHolder</tt> parameter allows implementations to return wrapped versions of * the request or response (or both), allowing them to access implementation-specific state for the request. * The values obtained from the holder will be passed on to the filter chain and also to the <tt>saveContext</tt> * method when it is finally called. Implementations may wish to return a subclass of * {@link SaveContextOnUpdateOrErrorResponseWrapper} as the response object, which guarantees that the context is * persisted when an error or redirect occurs. * * @param requestResponseHolder holder for the current request and response for which the context should be loaded. * * @return The security context which should be used for the current request, never null. */ @Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { HttpServletRequest request = requestResponseHolder.getRequest(); HttpServletResponse response = requestResponseHolder.getResponse(); requestResponseHolder.setResponse(new SaveToCookieResponseWrapper(request, response)); Cookie authenticationCookie = getAuthenticationCookie(request); if (authenticationCookie == null) { return SecurityContextHolder.createEmptyContext(); } String serialisedAuthentication = tokenEncryption.decryptAndVerify(authenticationCookie.getValue()); if (serialisedAuthentication == null) { response.addCookie(createExpireAuthenticationCookie(request)); return SecurityContextHolder.createEmptyContext(); } Authentication authentication = authenticationSerializer.deserialize(serialisedAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(authentication); return securityContext; }
@Test public void returnsSecurityContextWithAuthenticationForAuthenticatedRequest() throws Exception { TokenEncryption tokenEncryption = createJwtEncryption(); AuthenticationSerializer authenticationSerializer = new JsonAuthenticationSerializer(); CookieSecurityContextRepository repository = createCookieSecurityContextRepository(tokenEncryption, authenticationSerializer); UserDetails userDetails = new User("username", "password", Collections.emptyList()); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, Collections.emptyList()); String serializedAuthentication = authenticationSerializer.serialize(authentication); String payload = tokenEncryption.encryptAndSign(serializedAuthentication); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie(AUTHENTICATION_COOKIE_NAME, payload)); MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContext securityContext = repository.loadContext(new HttpRequestResponseHolder(request, response)); assertThat(securityContext.getAuthentication(), notNullValue()); UserDetails authenticatedUserDetails = (UserDetails) securityContext.getAuthentication().getPrincipal(); assertThat(authenticatedUserDetails.getUsername(), equalTo(userDetails.getUsername())); }
@Test public void expireAuthenticationCookieForExpiredAuthToken() throws Exception { CookieSecurityContextRepository repository = createCookieSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); request.setCookies(new Cookie(AUTHENTICATION_COOKIE_NAME, "eyJjdHkiOiJKV1QiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiZGlyIn0..v3OyQykgTQI5U7gP.dKsmMKX1MHGoMx2rXrCCWOCbyax-J8JS6gu63OBXEDm7Ab926OwlwlZcvoOZGW5nO7ZR95h2pe8pQs8s8cqWJUO4L4dGI9jTj4jK_Lsy9cPWDY4BMzs2bVBuasn88OQYjC-3zuZyvPKfQHrSVS9OjTaMLeMBwMfKP-k3IysOUfUtWUNcRb86v7VCnOd0ATljXUN8DekK8iZ0wD5AtBJVaOQLbaNWiXGY2pnA2eOW9cI_vPbCqqn4ZW-r7sEy6UzHgXYgRAr4bKb7abVtRvO1Xg3CcpquE597Om0bKJIk-VVCz7fVzpz5rkp16vzN-RKBJBs2MK-UsXKD9Lkgedh5w--Q4muiWrAqA5_Tx36mvkESlzR5pbsKu84ZweE5dfen47q_BWaZguVb8jFJB1pofpEgNiZ1C1K8aKIO03CIR-cOOfvoPrsdte-0M4F5bq4KwLna8fYm9D3OeJN3sai3Ba2KKPtLsfz-F5jJlCOV44JE-F9Pqa1xfdpD_S5UenWFi9IUsM912BoCTX4ouEMP6ZUVHwKgTeFjInJXe6iJVqvhPfrWUeVUBmBURy_8XGrzW12GqN_Qp_-275gQ_jlQfyMsdtkLdMp9YxpIbPb4Whq0ey5eKvy924Z4aWKQcw6SrVPAhFjXbvtwGVJYv2lzQ2vQIDE9g1dxqPpRvAG_qb_4M3Xfhtjo2W1Md-U1Oo5cfDsrbqeeegeYDH_AA5t5tJxLDB7TtR8xtjFb52WNItxcKeMnb6jegAwWlEjAkAqY.1d7Z0BNKOegXeUI_fY8yQg")); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response); repository.loadContext(requestResponseHolder); ServletResponseWrapper responseWrapper = (ServletResponseWrapper) requestResponseHolder.getResponse(); MockHttpServletResponse wrappedResponse = (MockHttpServletResponse) responseWrapper.getResponse(); Cookie authenticationCookie = wrappedResponse.getCookie(AUTHENTICATION_COOKIE_NAME); assertThat(authenticationCookie.getMaxAge(), equalTo(0)); assertThat(authenticationCookie.getValue(), isEmptyString()); assertTrue(authenticationCookie.getSecure()); assertTrue(authenticationCookie.isHttpOnly()); }
@Test public void expireAuthenticationCookieForEmptySecurityContext() throws Exception { CookieSecurityContextRepository repository = createCookieSecurityContextRepository(); SecurityContext emptySecurityContext = SecurityContextHolder.createEmptyContext(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response); repository.loadContext(requestResponseHolder); repository.saveContext(emptySecurityContext, requestResponseHolder.getRequest(), requestResponseHolder.getResponse()); Cookie authenticationCookie = response.getCookie(AUTHENTICATION_COOKIE_NAME); assertThat(authenticationCookie.getMaxAge(), equalTo(0)); assertThat(authenticationCookie.getValue(), isEmptyString()); assertTrue(authenticationCookie.getSecure()); assertTrue(authenticationCookie.isHttpOnly()); }
@Test public void returnsSecurityContextWithAuthenticationForAuthenticatedRequest() throws Exception { CookieBasedSecurityContextRepository repository = createCookieBasedSecurityContextRepository(); JwtClientSerializer jwtClientSerializer = createJwtClientSerializer(); Client client = new Client("clientId", "familyName", "customerId", true, true, "unitId", "serviceId", "appointmentTypeId", true); String payload = jwtClientSerializer.serialize(client); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie(SecurityContextSerializer.COOKIE_NAME,payload)); MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContext securityContext = repository.loadContext(new HttpRequestResponseHolder(request, response)); assertThat(securityContext.getAuthentication(), notNullValue()); Client authenticatedClient = (Client) securityContext.getAuthentication().getPrincipal(); assertThat(authenticatedClient.getClientId(), equalTo(client.getClientId())); }
@Test public void expireSessionCookieForExpiredAuthToken() throws Exception { CookieBasedSecurityContextRepository repository = createCookieBasedSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); request.setCookies(new Cookie(SecurityContextSerializer.COOKIE_NAME, "eyJjdHkiOiJKV1QiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiZGlyIn0..v3OyQykgTQI5U7gP.dKsmMKX1MHGoMx2rXrCCWOCbyax-J8JS6gu63OBXEDm7Ab926OwlwlZcvoOZGW5nO7ZR95h2pe8pQs8s8cqWJUO4L4dGI9jTj4jK_Lsy9cPWDY4BMzs2bVBuasn88OQYjC-3zuZyvPKfQHrSVS9OjTaMLeMBwMfKP-k3IysOUfUtWUNcRb86v7VCnOd0ATljXUN8DekK8iZ0wD5AtBJVaOQLbaNWiXGY2pnA2eOW9cI_vPbCqqn4ZW-r7sEy6UzHgXYgRAr4bKb7abVtRvO1Xg3CcpquE597Om0bKJIk-VVCz7fVzpz5rkp16vzN-RKBJBs2MK-UsXKD9Lkgedh5w--Q4muiWrAqA5_Tx36mvkESlzR5pbsKu84ZweE5dfen47q_BWaZguVb8jFJB1pofpEgNiZ1C1K8aKIO03CIR-cOOfvoPrsdte-0M4F5bq4KwLna8fYm9D3OeJN3sai3Ba2KKPtLsfz-F5jJlCOV44JE-F9Pqa1xfdpD_S5UenWFi9IUsM912BoCTX4ouEMP6ZUVHwKgTeFjInJXe6iJVqvhPfrWUeVUBmBURy_8XGrzW12GqN_Qp_-275gQ_jlQfyMsdtkLdMp9YxpIbPb4Whq0ey5eKvy924Z4aWKQcw6SrVPAhFjXbvtwGVJYv2lzQ2vQIDE9g1dxqPpRvAG_qb_4M3Xfhtjo2W1Md-U1Oo5cfDsrbqeeegeYDH_AA5t5tJxLDB7TtR8xtjFb52WNItxcKeMnb6jegAwWlEjAkAqY.1d7Z0BNKOegXeUI_fY8yQg")); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response); repository.loadContext(requestResponseHolder); ServletResponseWrapper responseWrapper = (ServletResponseWrapper) requestResponseHolder.getResponse(); MockHttpServletResponse wrappedResponse = (MockHttpServletResponse) responseWrapper.getResponse(); Cookie sessionCookie = wrappedResponse.getCookie(SecurityContextSerializer.COOKIE_NAME); assertThat(sessionCookie.getMaxAge(), equalTo(0)); assertThat(sessionCookie.getValue(), isEmptyString()); assertTrue(sessionCookie.getSecure()); assertTrue(sessionCookie.isHttpOnly()); }
@Test public void addSessionCookieOnResponseForNonEmptySecurityContext() throws Exception { CookieBasedSecurityContextRepository repository = createCookieBasedSecurityContextRepository(); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Client client = new Client("clientId", "familyName", "customerId", true, true, "unitId", "serviceId", "appointmentTypeId", true); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken(client, null, Collections.emptyList())); String payload = createJwtClientSerializer().serialize(client); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); request.setCookies(new Cookie(SecurityContextSerializer.COOKIE_NAME,payload)); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response); repository.loadContext(requestResponseHolder); repository.saveContext(securityContext, requestResponseHolder.getRequest(), requestResponseHolder.getResponse()); Cookie sessionCookie = response.getCookie(SecurityContextSerializer.COOKIE_NAME); assertThat(sessionCookie.getMaxAge(), equalTo(1800)); assertThat(sessionCookie.getValue().length(), greaterThan(0)); assertTrue(sessionCookie.getSecure()); assertTrue(sessionCookie.isHttpOnly()); }
@Test public void addCsrfCookieOnResponseForNonEmptySecurityContext() throws Exception { CookieBasedSecurityContextRepository repository = createCookieBasedSecurityContextRepository(); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Client client = new Client("clientId", "familyName", "customerId", true, true, "unitId", "serviceId", "appointmentTypeId", true); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken(client, null, Collections.emptyList())); String payload = createJwtClientSerializer().serialize(client); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); request.setCookies(new Cookie(SecurityContextSerializer.COOKIE_NAME, payload)); request.setCookies(new Cookie(CookieBasedCsrfTokenRepository.CSRF_COOKIE_AND_PARAMETER_NAME, "csrfTokenValue")); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response); repository.loadContext(requestResponseHolder); repository.saveContext(securityContext, requestResponseHolder.getRequest(), requestResponseHolder.getResponse()); Cookie csrfCookie = response.getCookie(CookieBasedCsrfTokenRepository.CSRF_COOKIE_AND_PARAMETER_NAME); assertThat(csrfCookie.getMaxAge(), equalTo(1800)); assertThat(csrfCookie.getValue(), equalTo("csrfTokenValue")); assertTrue(csrfCookie.getSecure()); assertTrue(csrfCookie.isHttpOnly()); }
@Test public void expireSessionCookieForEmptySecurityContext() throws Exception { CookieBasedSecurityContextRepository repository = createCookieBasedSecurityContextRepository(); SecurityContext emptySecurityContext = SecurityContextHolder.createEmptyContext(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response); repository.loadContext(requestResponseHolder); repository.saveContext(emptySecurityContext, requestResponseHolder.getRequest(), requestResponseHolder.getResponse()); Cookie sessionCookie = response.getCookie(SecurityContextSerializer.COOKIE_NAME); assertThat(sessionCookie.getMaxAge(), equalTo(0)); assertThat(sessionCookie.getValue(), isEmptyString()); assertTrue(sessionCookie.getSecure()); assertTrue(sessionCookie.isHttpOnly()); }
@RequestMapping(value = "/login", method = RequestMethod.POST) public @ResponseBody User login(@RequestBody User user, HttpServletRequest request, HttpServletResponse response) { User loginedUser = userService.sign(user.getUsername(), user.getPassword()); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(loginedUser, user.getPassword(), loginedUser.getAuthorities()); auth.setDetails(loginedUser.getId()); SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(auth); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response); sessionSecurityContextRepository.saveContext(context, requestResponseHolder.getRequest(), requestResponseHolder.getResponse()); Long notification_count = notificationRepository.countByInbox(loginedUser.getInbox()); loginedUser.setNotificationCount(notification_count); return loginedUser; }
@Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { String token = authStore.getToken(requestResponseHolder.getRequest(), authHeaderName); if(logger.isDebugEnabled()){ logger.debug("load context user token : {}", token); } if(StringUtils.isBlank(token)){ return SecurityContextHolder.createEmptyContext(); } SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = null; try { authentication = jwtTokenService.createAuthentication(token); } catch(CredentialsExpiredException e){ cookieStorer.clear(requestResponseHolder.getRequest(), requestResponseHolder.getResponse(), authHeaderName); } if(authentication!=null){ context.setAuthentication(authentication); } return context; }
@Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { HttpServletRequest request = requestResponseHolder.getRequest(); HttpServletResponse response = requestResponseHolder.getResponse(); HttpSession httpSession = request.getSession(false); String sid = this.getSessionId(request, true); SecurityContext context = readSecurityContextFromSession(request); if (context == null) { context = SecurityContextHolder.createEmptyContext(); } SaveToSessionResponseWrapper wrappedResponse = new SaveToSessionResponseWrapper( response, request, httpSession != null, context, sid); requestResponseHolder.setResponse(wrappedResponse); if (isServlet3) { requestResponseHolder.setRequest(new Servlet3SaveToSessionRequestWrapper(request, wrappedResponse)); } return context; }
@Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { wrapResponse(requestResponseHolder); LOGGER.debug("Trying to load security context from request."); Cookie securityCookie = getCookieForName(requestResponseHolder.getRequest().getCookies(), cookieName); if (securityCookie == null) { LOGGER.debug("No security cookie found in request. Returning empty context."); return createNewContext(); } LOGGER.debug("Security cookie found, trying to deserialize"); SecurityCookie cookie = securityCookieMarshaller.getSecurityCookie(securityCookie.getValue()); if (cookie == null || !cookie.isValid()) { LOGGER.debug("Security cookie was not valid. Returning empty context."); requestResponseHolder.getResponse().addCookie(createRemovalCookie()); return createNewContext(); } LOGGER.debug("Returning context from cookie."); SecurityContext context = cookie.getSecurityContext(); renewContext(context, requestResponseHolder); return context; }
final void save(SecurityContext securityContext, HttpServletRequest request) { HttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response); this.repository.loadContext(requestResponseHolder); request = requestResponseHolder.getRequest(); response = requestResponseHolder.getResponse(); this.repository.saveContext(securityContext, request, response); }
public SecurityContext loadContext( HttpRequestResponseHolder requestResponseHolder) { SecurityContext securityContext = super .loadContext(requestResponseHolder); if (securityContext == null) { logger.debug("securityContext is null"); return null; } if (debug) { return securityContext; } SpringSecurityUserAuth userAuthInSession = SpringSecurityUtils .getCurrentUser(securityContext); if (userAuthInSession == null) { logger.debug("userAuthInSession is null"); return securityContext; } UserAuthDTO userAuthInCache = userAuthConnector.findById( userAuthInSession.getId(), userAuthInSession.getTenantId()); SpringSecurityUserAuth userAuthResult = new SpringSecurityUserAuth(); beanMapper.copy(userAuthInCache, userAuthResult); SpringSecurityUtils.saveUserDetailsToContext(userAuthResult, null, securityContext); return securityContext; }
@RequestMapping(value = "/login", method = RequestMethod.POST) public String login(HttpServletRequest request, HttpServletResponse response, Model model) { HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); httpSessionSecurityContextRepository.loadContext(holder); try { // 使用提供的证书认证用户 List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN"); Authentication auth = new UsernamePasswordAuthenticationToken(request.getParameter("username"), request.getParameter("password"), authorities); SecurityContextHolder.getContext().setAuthentication(authenticationManager.authenticate(auth)); // 认证用户 if(!auth.isAuthenticated()) throw new CredentialException("用户不能够被认证"); } catch (Exception ex) { // 用户不能够被认证,重定向回登录页 logger.info(ex); return "login"; } // 从会话得到默认保存的请求 DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST"); // 为令牌请求生成认证参数Map Map<String, String> authParams = getAuthParameters(defaultSavedRequest); AuthorizationRequest authRequest = new DefaultOAuth2RequestFactory(clientDetailsService).createAuthorizationRequest(authParams); authRequest.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN")); model.addAttribute("authorizationRequest", authRequest); httpSessionSecurityContextRepository.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); return "authorize"; }
@Override protected void additionalAuthenticationChecks(UserDetails userDetails,UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { IUser user=(IUser)userDetails; HttpRequestResponseHolder holder=new HttpRequestResponseHolder(ContextHolder.getRequest(),ContextHolder.getResponse()); this.doInterceptor(InterceptorType.before, holder); try{ frameworkService.authenticate(user, authentication); }catch(Exception ex){ this.doInterceptor(InterceptorType.failure, holder); throw new AuthenticationServiceException(ex.getMessage()); } ContextHolder.getHttpSession().setAttribute(ContextHolder.LOGIN_USER_SESSION_KEY,user); this.doInterceptor(InterceptorType.success, holder); }
private void doInterceptor(InterceptorType type,HttpRequestResponseHolder holder){ for(ISecurityInterceptor intercepor:securityInterceptors){ if(type.equals(InterceptorType.before)){ intercepor.beforeLogin(holder); }else if(type.equals(InterceptorType.success)){ intercepor.loginSuccess(holder); }else if(type.equals(InterceptorType.failure)){ intercepor.loginFailure(holder); } } }
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException { HttpRequestResponseHolder holder=new HttpRequestResponseHolder((HttpServletRequest)request,(HttpServletResponse)response); ContextHolder.setHttpRequestResponseHolder((HttpServletRequest)request,(HttpServletResponse)response); try{ this.doInterceptor(InterceptorType.before, holder); chain.doFilter(request, response); this.doInterceptor(InterceptorType.success, holder); }catch(Exception exception){ this.doInterceptor(InterceptorType.failure, holder); Throwable throwable=this.getThrowableCause(exception); boolean support=false; for(IExceptionHandler handler:exceptionHandlers){ if(handler.support(throwable)){ support=true; handler.handle(holder, throwable); break; } } if(!support){ if(throwable instanceof IOException){ throw (IOException)throwable; }else{ throw new ServletException(throwable); } } }finally{ ContextHolder.clean(); } }
private void doInterceptor(InterceptorType type,HttpRequestResponseHolder holder){ for(ISecurityInterceptor intercepor:securityInterceptors){ if(type.equals(InterceptorType.before)){ intercepor.beforeAuthorization(holder); }else if(type.equals(InterceptorType.success)){ intercepor.authorizationSuccess(holder); }else if(type.equals(InterceptorType.failure)){ intercepor.authorizationFailure(holder); } } }
@Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { final String authToken = getToken(requestResponseHolder.getRequest()); if (authToken == null || hazelcastInstance.getMap("userTokenMap").get(authToken) == null) { logger.info("Returning empty securityContext"); return SecurityContextHolder.createEmptyContext(); } else { logger.info("Returning valid securityContext"); return (SecurityContext) hazelcastInstance.getMap("userTokenMap").get(authToken); } }
@Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { final String authToken = getToken(requestResponseHolder.getRequest()); logger.debug("Reading security context token : " + authToken); if (authToken == null || hazelcastInstance.getMap("userTokenMap").get(authToken) == null) { logger.debug("Returning empty securityContext"); return SecurityContextHolder.createEmptyContext(); } else { logger.info("Returning valid securityContext"); return (SecurityContext) hazelcastInstance.getMap("userTokenMap").get(authToken); } }
@Test public void returnsEmptySecurityContextForUnauthenticatedRequest() throws Exception { CookieSecurityContextRepository repository = createCookieSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContext securityContext = repository.loadContext(new HttpRequestResponseHolder(request, response)); assertThat(securityContext.getAuthentication(), nullValue()); }
@Test public void returnsEmptySecurityContextForExpiredAuthToken() throws Exception { CookieSecurityContextRepository repository = createCookieSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie(AUTHENTICATION_COOKIE_NAME, "eyJjdHkiOiJKV1QiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiZGlyIn0..v3OyQykgTQI5U7gP.dKsmMKX1MHGoMx2rXrCCWOCbyax-J8JS6gu63OBXEDm7Ab926OwlwlZcvoOZGW5nO7ZR95h2pe8pQs8s8cqWJUO4L4dGI9jTj4jK_Lsy9cPWDY4BMzs2bVBuasn88OQYjC-3zuZyvPKfQHrSVS9OjTaMLeMBwMfKP-k3IysOUfUtWUNcRb86v7VCnOd0ATljXUN8DekK8iZ0wD5AtBJVaOQLbaNWiXGY2pnA2eOW9cI_vPbCqqn4ZW-r7sEy6UzHgXYgRAr4bKb7abVtRvO1Xg3CcpquE597Om0bKJIk-VVCz7fVzpz5rkp16vzN-RKBJBs2MK-UsXKD9Lkgedh5w--Q4muiWrAqA5_Tx36mvkESlzR5pbsKu84ZweE5dfen47q_BWaZguVb8jFJB1pofpEgNiZ1C1K8aKIO03CIR-cOOfvoPrsdte-0M4F5bq4KwLna8fYm9D3OeJN3sai3Ba2KKPtLsfz-F5jJlCOV44JE-F9Pqa1xfdpD_S5UenWFi9IUsM912BoCTX4ouEMP6ZUVHwKgTeFjInJXe6iJVqvhPfrWUeVUBmBURy_8XGrzW12GqN_Qp_-275gQ_jlQfyMsdtkLdMp9YxpIbPb4Whq0ey5eKvy924Z4aWKQcw6SrVPAhFjXbvtwGVJYv2lzQ2vQIDE9g1dxqPpRvAG_qb_4M3Xfhtjo2W1Md-U1Oo5cfDsrbqeeegeYDH_AA5t5tJxLDB7TtR8xtjFb52WNItxcKeMnb6jegAwWlEjAkAqY.1d7Z0BNKOegXeUI_fY8yQg")); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response); SecurityContext securityContext = repository.loadContext(requestResponseHolder); assertThat(securityContext.getAuthentication(), nullValue()); }
@Test public void addAuthenticationCookieOnResponseForNonEmptySecurityContext() throws Exception { TokenEncryption tokenEncryption = createJwtEncryption(); AuthenticationSerializer authenticationSerializer = new JsonAuthenticationSerializer(); CookieSecurityContextRepository repository = createCookieSecurityContextRepository(tokenEncryption, authenticationSerializer); UserDetails userDetails = new User("username", "password", Collections.emptyList()); Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, Collections.emptyList()); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(authentication); String serializedAuthentication = authenticationSerializer.serialize(authentication); String payload = tokenEncryption.encryptAndSign(serializedAuthentication); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); request.setCookies(new Cookie(AUTHENTICATION_COOKIE_NAME, payload)); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response); repository.loadContext(requestResponseHolder); repository.saveContext(securityContext, requestResponseHolder.getRequest(), requestResponseHolder.getResponse()); Cookie authenticationCookie = response.getCookie(AUTHENTICATION_COOKIE_NAME); assertThat(authenticationCookie.getMaxAge(), equalTo(AUTHENTICATION_COOKIE_MAX_AGE_SECONDS)); assertThat(authenticationCookie.getValue().length(), greaterThan(0)); assertTrue(authenticationCookie.getSecure()); assertTrue(authenticationCookie.isHttpOnly()); }
@Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { SecurityContext context = SecurityContextHolder.createEmptyContext(); String token = tokenFromRequest(requestResponseHolder.getRequest()); Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token); if (authentication != null) { context.setAuthentication(authentication); logger.debug("Found bearer token in request. Saving it in SecurityContext"); } return context; }
@Test public void shouldLoadContextWithoutAuthenticationIfMissingAuthorizationHeader() throws Exception { BearerSecurityContextRepository repository = new BearerSecurityContextRepository(); HttpServletRequest request = mock(HttpServletRequest.class); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, null); SecurityContext context = repository.loadContext(holder); assertThat(context, is(notNullValue())); assertThat(context.getAuthentication(), is(nullValue())); }
@Test public void shouldLoadContextWithoutAuthenticationIfInvalidAuthorizationHeaderValue() throws Exception { BearerSecurityContextRepository repository = new BearerSecurityContextRepository(); HttpServletRequest request = mock(HttpServletRequest.class); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, null); when(request.getHeader("Authorization")).thenReturn("Bearer <Invalid>"); SecurityContext context = repository.loadContext(holder); assertThat(context, is(notNullValue())); assertThat(context.getAuthentication(), is(nullValue())); }
@Test public void shouldLoadContextWithoutAuthenticationIfEmptyAuthorizationHeaderValue() throws Exception { BearerSecurityContextRepository repository = new BearerSecurityContextRepository(); HttpServletRequest request = mock(HttpServletRequest.class); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, null); when(request.getHeader("Authorization")).thenReturn("Bearer"); SecurityContext context = repository.loadContext(holder); assertThat(context, is(notNullValue())); assertThat(context.getAuthentication(), is(nullValue())); }
@Test public void shouldLoadContextWithoutAuthenticationIfAuthorizationHeaderValueNotBearerToken() throws Exception { BearerSecurityContextRepository repository = new BearerSecurityContextRepository(); HttpServletRequest request = mock(HttpServletRequest.class); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, null); when(request.getHeader("Authorization")).thenReturn("Basic somevalue"); SecurityContext context = repository.loadContext(holder); assertThat(context, is(notNullValue())); assertThat(context.getAuthentication(), is(nullValue())); }
@Test public void shouldLoadContextWithAuthentication() throws Exception { String token = JWT.create() .sign(Algorithm.HMAC256("secret")); BearerSecurityContextRepository repository = new BearerSecurityContextRepository(); HttpServletRequest request = mock(HttpServletRequest.class); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, null); when(request.getHeader("Authorization")).thenReturn("Bearer " + token); SecurityContext context = repository.loadContext(holder); assertThat(context, is(notNullValue())); assertThat(context.getAuthentication(), is(notNullValue())); assertThat(context.getAuthentication(), is(instanceOf(PreAuthenticatedAuthenticationJsonWebToken.class))); assertThat(context.getAuthentication().isAuthenticated(), is(false)); }
@Test public void returnsEmptySecurityContextForUnauthenticatedRequest() throws Exception { CookieBasedSecurityContextRepository repository = createCookieBasedSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContext securityContext = repository.loadContext(new HttpRequestResponseHolder(request, response)); assertThat(securityContext.getAuthentication(), nullValue()); }
@Test public void returnsEmptySecurityContextForExpiredAuthToken() throws Exception { CookieBasedSecurityContextRepository repository = createCookieBasedSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie(SecurityContextSerializer.COOKIE_NAME, "eyJjdHkiOiJKV1QiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiZGlyIn0..v3OyQykgTQI5U7gP.dKsmMKX1MHGoMx2rXrCCWOCbyax-J8JS6gu63OBXEDm7Ab926OwlwlZcvoOZGW5nO7ZR95h2pe8pQs8s8cqWJUO4L4dGI9jTj4jK_Lsy9cPWDY4BMzs2bVBuasn88OQYjC-3zuZyvPKfQHrSVS9OjTaMLeMBwMfKP-k3IysOUfUtWUNcRb86v7VCnOd0ATljXUN8DekK8iZ0wD5AtBJVaOQLbaNWiXGY2pnA2eOW9cI_vPbCqqn4ZW-r7sEy6UzHgXYgRAr4bKb7abVtRvO1Xg3CcpquE597Om0bKJIk-VVCz7fVzpz5rkp16vzN-RKBJBs2MK-UsXKD9Lkgedh5w--Q4muiWrAqA5_Tx36mvkESlzR5pbsKu84ZweE5dfen47q_BWaZguVb8jFJB1pofpEgNiZ1C1K8aKIO03CIR-cOOfvoPrsdte-0M4F5bq4KwLna8fYm9D3OeJN3sai3Ba2KKPtLsfz-F5jJlCOV44JE-F9Pqa1xfdpD_S5UenWFi9IUsM912BoCTX4ouEMP6ZUVHwKgTeFjInJXe6iJVqvhPfrWUeVUBmBURy_8XGrzW12GqN_Qp_-275gQ_jlQfyMsdtkLdMp9YxpIbPb4Whq0ey5eKvy924Z4aWKQcw6SrVPAhFjXbvtwGVJYv2lzQ2vQIDE9g1dxqPpRvAG_qb_4M3Xfhtjo2W1Md-U1Oo5cfDsrbqeeegeYDH_AA5t5tJxLDB7TtR8xtjFb52WNItxcKeMnb6jegAwWlEjAkAqY.1d7Z0BNKOegXeUI_fY8yQg")); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response); SecurityContext securityContext = repository.loadContext(requestResponseHolder); assertThat(securityContext.getAuthentication(), nullValue()); }
@Test public void addCsrfCookieOnResponseOnUserLogin() throws Exception { CookieBasedCsrfTokenRepository csrfTokenRepository = new CookieBasedCsrfTokenRepository(); CookieBasedSecurityContextRepository securityContextRepository = createCookieBasedSecurityContextRepository(csrfTokenRepository); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Client client = new Client("clientId", "familyName", "customerId", true, true, "unitId", "serviceId", "appointmentTypeId", true); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken(client, null, Collections.emptyList())); String payload = createJwtClientSerializer().serialize(client); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); request.setCookies(new Cookie(SecurityContextSerializer.COOKIE_NAME, payload)); MockHttpServletResponse response = new MockHttpServletResponse(); CsrfToken token = csrfTokenRepository.generateToken(request); csrfTokenRepository.saveToken(token, request, response); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response); securityContextRepository.loadContext(requestResponseHolder); securityContextRepository.saveContext(securityContext, requestResponseHolder.getRequest(), requestResponseHolder.getResponse()); Cookie[] cookies = Arrays.stream(response.getCookies()).filter(cookie -> cookie.getName().equals(CookieBasedCsrfTokenRepository.CSRF_COOKIE_AND_PARAMETER_NAME)).toArray(Cookie[]::new); assertThat(cookies.length, equalTo(1)); Cookie csrfCookie = cookies[0]; assertThat(csrfCookie.getMaxAge(), equalTo(1800)); assertThat(csrfCookie.getValue(), equalTo(token.getToken())); assertTrue(csrfCookie.getSecure()); assertTrue(csrfCookie.isHttpOnly()); }
@Override public Action inspect(AtmosphereResource r) { final SecurityContextRepository securityContextRepo = getSecurityContextRepository( r.getAtmosphereConfig().getServletContext()); if (securityContextRepo.containsContext(r.getRequest())) { LOGGER.trace("Loading the security context from the session"); final HttpRequestResponseHolder requestResponse = new HttpRequestResponseHolder(r.getRequest(), r.getResponse()); final SecurityContext securityContext = securityContextRepo.loadContext(requestResponse); SecurityContextHolder.setContext(securityContext); } return Action.CONTINUE; }
final void save(SecurityContext securityContext, HttpServletRequest request) { HttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response); repository.loadContext(requestResponseHolder); request = requestResponseHolder.getRequest(); response = requestResponseHolder.getResponse(); repository.saveContext(securityContext, request, response); }