@Before public void setup() { resource = new ResourceOwnerPasswordResourceDetails(); resource.setAccessTokenUri(serverRunning.getUrl("/sparklr2/oauth/token")); resource.setClientId("my-trusted-client"); resource.setId("sparklr"); resource.setScope(Arrays.asList("trust")); resource.setUsername("marissa"); resource.setPassword("koala"); OAuth2RestTemplate template = new OAuth2RestTemplate(resource); existingToken = template.getAccessToken(); ((DefaultOAuth2AccessToken) existingToken).setExpiration(new Date(0L)); SecurityContextImpl securityContext = new SecurityContextImpl(); securityContext.setAuthentication(new TestingAuthenticationToken("marissa", "koala", "ROLE_USER")); SecurityContextHolder.setContext(securityContext); }
@Test public void shouldExtractPrincipalNameFromAuthentication() throws Exception { // given MongoSession toSerialize = new MongoSession(); String principalName = "john_the_springer"; SecurityContextImpl context = new SecurityContextImpl(); context.setAuthentication( new UsernamePasswordAuthenticationToken(principalName, null)); toSerialize.setAttribute("SPRING_SECURITY_CONTEXT", context); // when DBObject dbObject = convertToDBObject(toSerialize); // then assertThat(dbObject.get("principal")).isEqualTo(principalName); }
@Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return authenticationConverter.convert(exchange) .then( token -> { return authenticationManager.authenticate(token) .then(authentication -> { SecurityContext context = new SecurityContextImpl(); context.setAuthentication(authentication); return securityContextRepository .save(exchange, context) .then( () ->{ return chain.filter(exchange); }); }) .otherwise( AuthenticationException.class, t -> { return entryPoint.commence(exchange, t); }); }) .otherwiseIfEmpty(Mono.defer(() -> { return chain.filter(exchange); })); }
@Around("execution(org.springframework.web.servlet.ModelAndView org.gra4j.dataMigration.controller..*.*(..)) " + " and @annotation(org.springframework.web.bind.annotation.RequestMapping)") public Object before(ProceedingJoinPoint pjp) throws Throwable { // 从切点上获取目标方法 MethodSignature methodSignature = (MethodSignature) pjp.getSignature(); Method method = methodSignature.getMethod(); // 若目标方法忽略了安全性检查,则直接调用目标方法 if (method.isAnnotationPresent(UnCheck.class)) return pjp.proceed(); if (StringUtils.isEmpty(tokenName)) tokenName = DEFAULT_TOKEN_NAME; HttpServletRequest request = WebContext.getRequest(); HttpServletResponse response = WebContext.getResponse(); String token = tokenManager.createToken( ((SecurityContextImpl) request.getSession() .getAttribute("SPRING_SECURITY_CONTEXT")) .getAuthentication() .getName()); response.addHeader(tokenName,token); return pjp.proceed(); }
@RequestMapping("/materias/imaginie") public ModelAndView materiasImaginie(HttpSession session, HttpServletResponse httpServletResponse) { SecurityContextImpl context = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT"); User user = (User) context.getAuthentication().getPrincipal(); ImaginieLogin imaginieLogin = new ImaginieLogin(user); String requestURL = imaginieLogin.connect(); if(requestURL != null){ return new ModelAndView("redirect:" + requestURL); } else { return new ModelAndView("404"); } }
@Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { return authenticationConverter.convert(exchange) .flatMap( token -> { return authenticationManager.authenticate(token) .flatMap(authentication -> { SecurityContext context = new SecurityContextImpl(); context.setAuthentication(authentication); return securityContextRepository .save(exchange, context) .flatMap( value ->{ return chain.filter(exchange); }); }) .onErrorResume( AuthenticationException.class, t -> { return entryPoint.commence(exchange, t); }); }) .switchIfEmpty(Mono.defer(() -> { return chain.filter(exchange); })); }
/** * JAVADOC Method Level Comments * * @throws Exception JAVADOC. */ @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); interceptor = new CurrentUserChannelInterceptor(systemUserService, userAccessor); if (null == SecurityContextHolder.getContext()) { SecurityContextHolder.setContext(new SecurityContextImpl()); } SecurityContext context = SecurityContextHolder.getContext(); user = new User(); user.setName("user"); AbstractAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(user, null); authToken.setDetails("pipipi"); context.setAuthentication(authToken); }
/** * JAVADOC Method Level Comments * * @throws Throwable JAVADOC. */ @Test public void testWithNull() throws Throwable { if (null == SecurityContextHolder.getContext()) { SecurityContextHolder.setContext(new SecurityContextImpl()); } //mock systemUserService returns username String systemUsername = "ADMIN"; when(systemUserService.getUsername()).thenReturn(systemUsername); SystemUserMethodInterceptor interceptor = new SystemUserMethodInterceptor(userAccessor, systemUserService); interceptor.invoke(methodInvocation); //mock authenticatioNService call verify(userAccessor).forceUserToContext(systemUsername); verify(methodInvocation).proceed(); //test it switches back assertEquals(CurrentUserAccessor.currentAuthentication(), null); }
@Override protected void setUp() throws Exception { super.setUp(); // store initial security context for later restoration initialSecurityContext = SecurityContextHolder.getContext(); SecurityContext context = new SecurityContextImpl(); User user = new User("user"); user.setId(1L); user.setPassword("password"); user.addRole(new Role(Constants.USER_ROLE)); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( user.getUsername(), user.getPassword(), user.getAuthorities()); token.setDetails(user); context.setAuthentication(token); SecurityContextHolder.setContext(context); }
public void testAddUserAsAdmin() throws Exception { SecurityContext context = new SecurityContextImpl(); User user = new User("admin"); user.setId(2L); user.setPassword("password"); user.addRole(new Role(Constants.ADMIN_ROLE)); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( user.getUsername(), user.getPassword(), user.getAuthorities()); token.setDetails(user); context.setAuthentication(token); SecurityContextHolder.setContext(context); UserManager userManager = makeInterceptedTarget(); User adminUser = new User("admin"); adminUser.setId(2L); userDao.expects(once()).method("saveUser"); userManager.saveUser(adminUser); }
public void testAddUserRoleWhenHasAdminRole() throws Exception { SecurityContext context = new SecurityContextImpl(); User user1 = new User("user"); user1.setId(1L); user1.setPassword("password"); user1.addRole(new Role(Constants.ADMIN_ROLE)); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( user1.getUsername(), user1.getPassword(), user1 .getAuthorities()); token.setDetails(user1); context.setAuthentication(token); SecurityContextHolder.setContext(context); UserManager userManager = makeInterceptedTarget(); User user = new User("user"); user.setId(1L); user.getRoles().add(new Role(Constants.ADMIN_ROLE)); user.getRoles().add(new Role(Constants.USER_ROLE)); userDao.expects(once()).method("saveUser"); userManager.saveUser(user); }
@Before public void setUp() throws Exception { // store initial security context for later restoration initialSecurityContext = SecurityContextHolder.getContext(); SecurityContext context = new SecurityContextImpl(); User user = new User("user"); user.setId(1L); user.setPassword("password"); user.addRole(new Role(Constants.USER_ROLE)); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities()); token.setDetails(user); context.setAuthentication(token); SecurityContextHolder.setContext(context); }
@Test public void testAddUserAsAdmin() throws Exception { SecurityContext securityContext = new SecurityContextImpl(); User user = new User("admin"); user.setId(2L); user.setPassword("password"); user.addRole(new Role(Constants.ADMIN_ROLE)); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities()); token.setDetails(user); securityContext.setAuthentication(token); SecurityContextHolder.setContext(securityContext); UserManager userManager = makeInterceptedTarget(); final User adminUser = new User("admin"); adminUser.setId(2L); given(userDao.saveUser(adminUser)).willReturn(adminUser); given(passwordEncoder.encode(adminUser.getPassword())).willReturn(adminUser.getPassword()); userManager.saveUser(adminUser); }
@Test public void testAddUserRoleWhenHasAdminRole() throws Exception { SecurityContext securityContext = new SecurityContextImpl(); User user1 = new User("user"); user1.setId(1L); user1.setPassword("password"); user1.addRole(new Role(Constants.ADMIN_ROLE)); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user1.getUsername(), user1.getPassword(), user1.getAuthorities()); token.setDetails(user1); securityContext.setAuthentication(token); SecurityContextHolder.setContext(securityContext); UserManager userManager = makeInterceptedTarget(); final User user = new User("user"); user.setId(1L); user.getRoles().add(new Role(Constants.ADMIN_ROLE)); user.getRoles().add(new Role(Constants.USER_ROLE)); given(userDao.saveUser(user)).willReturn(user); given(passwordEncoder.encode(user.getPassword())).willReturn(user.getPassword()); userManager.saveUser(user); }
@BeforeMethod public void setUp() { // create new security context securityContext = new SecurityContextImpl(); SecurityContextHolder.setContext(securityContext); // new service instance service = new SecurityServiceImpl(); // set the aclManager mock on the security service ReflectionTestUtils.setField(service, "userGroupStoreService", userGroupStoreService); ReflectionTestUtils.setField(service, "aclStoreService", aclStoreServiceMock); ReflectionTestUtils.setField(service, "repositoryService", repositoryServiceMock); ReflectionTestUtils.setField(service, "centralConfig", centralConfigServiceMock); // reset mocks reset(aclStoreServiceMock, repositoryServiceMock, centralConfigServiceMock); }
/** * This method sets up the security context with the given username/password credentials and the list * of provided permissions. This allows to make calls to secured service methods from the test. * @param username the username to set in the context * @param password the password to set in the context * @param permissionNames the names of permissions to put into the security context */ protected void setUpSecurityContext(String username, String password, String... permissionNames) { getLogger().info("Setting up security context with permissions: {}", Arrays.toString(permissionNames)); List<SimpleGrantedAuthority> authorities = new ArrayList<>(); for (String permissionName : permissionNames) { authorities.add(new SimpleGrantedAuthority(permissionName)); } User principal = new User(username, password, authorities); Authentication authentication = new UsernamePasswordAuthenticationToken(principal, null, authorities); SecurityContext securityContext = new SecurityContextImpl(); securityContext.setAuthentication(authentication); SecurityContextHolder.setContext(securityContext); }
private SecurityContext createContext(final User user) { SecurityContext securityContext = new SecurityContextImpl(); securityContext.setAuthentication(new AbstractAuthenticationToken(user.getAuthorities()) { private static final long serialVersionUID = 1L; @Override public Object getCredentials() { return "N/A"; } @Override public Object getPrincipal() { return user; } @Override public boolean isAuthenticated() { return true; } }); return securityContext; }
@Test public void getAuthenticatedUser_validUser() { final User authUser = new UserImpl(USER_ID); AbstractAuthenticationToken auth = createNiceMock(AbstractAuthenticationToken.class); expect(auth.getPrincipal()).andReturn(authUser).anyTimes(); replay(auth); SecurityContext context = new SecurityContextImpl(); context.setAuthentication(auth); SecurityContextHolder.setContext(context); User result = service.getAuthenticatedUser(); assertThat(result, is(sameInstance(authUser))); verify(auth); }
@SuppressWarnings("unchecked") @Before public void setup() throws SQLException { restOperations = EasyMock.createNiceMock(RestOperations.class); EasyMock.expect(restOperations.postForObject(EasyMock.anyObject(String.class), EasyMock.anyObject(String.class), EasyMock.anyObject(Class.class))) .andReturn(VALID_METADATA); EasyMock.replay(restOperations); //Replace the real restOperations instance with a mock -- otherwise the call for gadget metadata would fail since //we don't have a shindig server available to hit. ReflectionTestUtils.setField(metadataRepository, "restOperations", restOperations); //Setup a mock authenticated user final User authUser = new UserImpl(VALID_USER_ID, VALID_USER_NAME); AbstractAuthenticationToken auth = EasyMock.createNiceMock(AbstractAuthenticationToken.class); EasyMock.expect(auth.getPrincipal()).andReturn(authUser).anyTimes(); EasyMock.replay(auth); SecurityContext context = new SecurityContextImpl(); context.setAuthentication(auth); SecurityContextHolder.setContext(context); }
public boolean equals(Object obj) { if (obj instanceof SecurityContextImpl) { SecurityContextImpl test = (SecurityContextImpl) obj; if ((this.getAuthentication() == null) && (test.getAuthentication() == null)) { return true; } if ((this.getAuthentication() != null) && (test.getAuthentication() != null) && this.getAuthentication().equals(test.getAuthentication())) { return true; } } return false; }
@Test public void shouldReturnValueWithValidUntilWhenSecurityCookieGiven() throws Exception { // GIVEN SecurityContext securityContext = new SecurityContextImpl(); byte[] serializedContext = new byte[0]; when(serializerMock.serialize(securityContext)).thenReturn(serializedContext); // WHEN SecurityCookie cookie = new SecurityCookie(securityContext, now); String base64EncodedData = marshaller.getBase64EncodedValue(cookie); // THEN String[] values = base64EncodedData.split("&"); byte[] decodedValue = decodeBase64(values[0]); DataInputStream inputStream = getDataInputStream(decodedValue); long validUntil = inputStream.readLong(); assertEquals(now.getMillis(), validUntil); }
@Test public void shouldReturnValueWithSerializedContextWhenSecurityCookieGiven() throws Exception { // GIVEN SecurityContext securityContext = new SecurityContextImpl(); byte[] serializedContext = new byte[] { 1, 2, 3 }; when(serializerMock.serialize(securityContext)).thenReturn(serializedContext); // WHEN SecurityCookie cookie = new SecurityCookie(securityContext, now); String base64EncodedData = marshaller.getBase64EncodedValue(cookie); // THEN String[] values = base64EncodedData.split("&"); byte[] decodedValue = decodeBase64(values[0]); DataInputStream inputStream = getDataInputStream(decodedValue); inputStream.skipBytes(Long.SIZE / 8); byte[] serializedData = new byte[3]; inputStream.read(serializedData); assertArrayEquals(serializedContext, serializedData); }
@Test public void shouldReturnValueWithHashWhenValidSecurityCookieGiven() throws Exception { // GIVEN SecurityContext securityContext = new SecurityContextImpl(); byte[] serializedContext = new byte[0]; byte[] hash = new byte[] { 7, 8, 9 }; when(serializerMock.serialize(securityContext)).thenReturn(serializedContext); when(hashMock.createHash(any(byte[].class))).thenReturn(hash); // WHEN SecurityCookie cookie = new SecurityCookie(securityContext, now); String base64EncodedData = marshaller.getBase64EncodedValue(cookie); // THEN String[] values = base64EncodedData.split("&"); byte[] decodedValue = decodeBase64(values[1]); assertArrayEquals(hash, decodedValue); }
@Test public void shouldExtractName() { // given String principalName = "john_the_springer"; SecurityContextImpl context = new SecurityContextImpl(); context.setAuthentication(new UsernamePasswordAuthenticationToken(principalName, null)); // when String extractedName = AuthenticationParser.extractName(context); // then assertThat(extractedName).isEqualTo(principalName); }
/** * Put new information in SecurityContextHolder. * * @param context * the security context to update. * @param newPrincipal * the new principal to place. */ private void replaceContext(final SecurityContext context, final UserDetails newPrincipal) { final PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(newPrincipal, null); authentication.setDetails(newPrincipal); context.setAuthentication(authentication); final SecurityContextImpl securityContextImpl = new SecurityContextImpl(); securityContextImpl.setAuthentication(authentication); // Replace the old context SecurityContextHolder.setContext(securityContextImpl); }
@Around("execution(org.gra4j.dataMigration.utils.web.Response org.gra4j.dataMigration.controller..*.*(..)) " + " and @annotation(org.springframework.web.bind.annotation.RequestMapping)") public Object execute(ProceedingJoinPoint pjp) throws Throwable { // 从切点上获取目标方法 MethodSignature methodSignature = (MethodSignature) pjp.getSignature(); Method method = methodSignature.getMethod(); // 若目标方法忽略了安全性检查,则直接调用目标方法 if (method.isAnnotationPresent(UnCheck.class)) return pjp.proceed(); HttpServletRequest request = WebContext.getRequest(); String userName = ((SecurityContextImpl) request.getSession() .getAttribute("SPRING_SECURITY_CONTEXT")) .getAuthentication() .getName(); if (StringUtils.isEmpty(tokenName)) tokenName = DEFAULT_TOKEN_NAME; // 从 request header 中获取当前 token String token = request.getHeader(tokenName); // 检查 token 有效性 if (!tokenManager.checkToken(tokenName+"-"+userName,token)) { String message = String.format("token [%s] is invalid", token); throw new TokenException(message); } // 调用目标方法 Object result = pjp.proceed(); tokenManager.removeToke(tokenName+"-"+userName); return result; }
private void checkSession(final HttpSession session) { if (null == session.getAttribute("currentUser")) { SecurityContextImpl spring_security_context = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT"); User user = (User) spring_security_context.getAuthentication().getPrincipal(); session.setAttribute("currentUser", user.getUsername()); } }
/** * Creates an authentication token based on the specified user details and sets it to the current thread's security * context. * * @param userDetails Details of the user to set as current * @return The generated authentication token */ public AuthenticationToken setCurrentUser(UserDetails userDetails) { final AuthenticationToken token = new AuthenticationToken(userDetails.getAuthorities(), userDetails); token.setAuthenticated(true); final SecurityContext context = new SecurityContextImpl(); context.setAuthentication(token); SecurityContextHolder.setContext(context); return token; }
/** * Initializes security context with the specified user. * * @param user User to set as currently authenticated */ public static void setCurrentUser(Person user) { currentUser = user; final UserDetails userDetails = new UserDetails(user, new HashSet<>()); SecurityContext context = new SecurityContextImpl(); context.setAuthentication(new AuthenticationToken(userDetails.getAuthorities(), userDetails)); SecurityContextHolder.setContext(context); }
@RequestMapping("/materias") public ModelAndView materias(HttpSession session){ ModelAndView model = new ModelAndView("modulo/materias"); SecurityContextImpl context = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT"); User user = (User) context.getAuthentication().getPrincipal(); String nonce = getRandomString(); String timeStamp = String.valueOf(System.currentTimeMillis()); String organizationId = geekieLab.getOrganizationId(user); model.addObject("userId", user.getGeekieId()); model.addObject("organizationId", organizationId); model.addObject("nonce", nonce); model.addObject("timestamp", timeStamp); String methodAndUrl = "POST&https%3A%2F%2Fwww.geekielab.com.br%2Flogin%2Flaunch&"; String oauthConsumer ="oauth_consumer_key%3D" + organizationId + "%26"; String oauthNonce = "oauth_nonce%3D" + nonce + "%26"; String oauthSignatureMethod = "oauth_signature_method%3DHMAC-SHA1%26"; String oauthTimeStamp = "oauth_timestamp%3D" + timeStamp + "%26"; String oauthVersion = "oauth_version%3D1.0%26"; String oauthUserId = "user_id%3D" + user.getGeekieId(); String baseString = methodAndUrl + oauthConsumer + oauthNonce + oauthSignatureMethod + oauthTimeStamp + oauthVersion + oauthUserId; model.addObject("signature", geekieClient.generateHmacSha(baseString, geekieLab.getOauthSigninKey(user))); return model; }
@RequestMapping("/entrega-missao-3/submit") public ModelAndView mission3Submit(MultipartFile delivery, HttpSession session){ SecurityContextImpl context = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT"); User user = (User) context.getAuthentication().getPrincipal(); ModelAndView model = new ModelAndView("modulo/cultura/missao-3/ano-"+user.getAno()+"/delivered"); String fileName = user.getIsmartId() + "_" + delivery.getOriginalFilename(); String webPath = fileSaver.write("deliveries/ano-"+user.getAno()+"/missao-3", delivery, fileName); File file = new File(webPath); String urlEncoded; try { urlEncoded = java.net.URLEncoder.encode(webPath, "UTF-8"); String link = AWS_S3_BASE_URL+urlEncoded; StudentMission studentMission = new StudentMission(Calendar.getInstance(), link, missionDAO.finbMissionByYearAndNumber(Long.valueOf(user.getAno()), 3L), user, fileName); missionDAO.saveStudentMission(studentMission); model.addObject("webPath", webPath); model.addObject("file", file); System.out.println("WEBPATH " + webPath); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return model; }
@Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { System.err.println("successfulAuthentication"); final SecurityContextImpl sCtx = new SecurityContextImpl(); sCtx.setAuthentication(authResult); // SecurityContextHolder.getContext().setAuthentication(authResult); final String sessionToken = sessionToken(); hazelcastInstance.getMap("userTokenMap").put(sessionToken, sCtx); try (PrintWriter out = response.getWriter()) { final LoginResponse loginResponse = new LoginResponse(); loginResponse.setAccessToken(sessionToken); if (authResult.getPrincipal() instanceof User) { final User user = (User) authResult.getPrincipal(); loginResponse.setName(user.getUsername()); loginResponse.setName(user.getUsername()); } out.write(jacksonObjectMapper.writeValueAsString(loginResponse)); } System.err.println("############ SUCCESSS ################"); }