String username = request.getParameter("username"); String password = hash(request.getParameter("password")); boolean remember = "true".equals(request.getParameter("remember")); User user = userDAO.find(username, password); if (user != null) { request.login(user.getUsername(), user.getPassword()); // Password should already be the hashed variant. request.getSession().setAttribute("user", user); if (remember) { String uuid = UUID.randomUUID().toString(); rememberDAO.save(uuid, user); addCookie(response, COOKIE_NAME, uuid, COOKIE_AGE); } else { rememberDAO.delete(user); removeCookie(response, COOKIE_NAME); } }
private static final String SQL_EXIST = "SELECT * FROM users WHERE username=? AND password=?"; public boolean exist(User user) throws SQLException { boolean exist = false; try ( Connection connection = Database.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_EXIST); ) { statement.setString(1, user.getUsername()); statement.setString(2, user.getPassword()); try (ResultSet resultSet = preparedStatement.executeQuery()) { exist = resultSet.next(); } } return exist; }
try { long companyId = PortalUtil.getCompanyId(request); User user = UserLocalServiceUtil.getUserByScreenName(companyId, screenName); return new String[] { String.valueOf(user.getUserId()), user.getPassword(), String.valueOf(user.isPasswordEncrypted()) }; } catch (Exception e) { return null; }
/** * Turns the users password, granted authorities and enabled state into a property file value * * @param user */ String serializeUser(User user) { StringBuffer sb = new StringBuffer(); sb.append(user.getPassword()); sb.append(","); for (GrantedAuthority ga : user.getAuthorities()) { sb.append(ga.getAuthority()); sb.append(","); } sb.append(user.isEnabled() ? "enabled" : "disabled"); return sb.toString(); } }
HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; User user = request.getSession().getAttribute("user"); if (user == null) { String uuid = getCookieValue(request, COOKIE_NAME); if (uuid != null) { user = rememberDAO.find(uuid); if (user != null) { request.login(user.getUsername(), user.getPassword()); request.getSession().setAttribute("user", user); // Login. addCookie(response, COOKIE_NAME, uuid, COOKIE_AGE); // Extends age. } else { removeCookie(response, COOKIE_NAME); } } } if (user == null) { response.sendRedirect("login"); } else { chain.doFilter(req, res); }
public class InsecureAutoLogin implements AutoLogin { public String[] login(HttpServletRequest request, HttpServletResponse response) throws AutoLoginException { String screenName = request.getParameter("insecurely_login_user"); if (screenName == null || screenName.isEmpty()) return null; try { long companyId = PortalUtil.getCompanyId(request); User user = UserLocalServiceUtil.getUserByScreenName(companyId, screenName); return new String[] { String.valueOf(user.getUserId()), user.getPassword(), String.valueOf(user.isPasswordEncrypted()) }; } catch (Exception e) { return null; } } }
private CasAuthenticationToken createCasAuthenticationToken() { User principal = new User("admin", "1234", Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))); Collection<? extends GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")); Assertion assertion = new AssertionImpl(new AttributePrincipalImpl("assertName"), START_DATE, END_DATE, START_DATE, Collections.<String, Object>emptyMap()); return new CasAuthenticationToken(KEY, principal, principal.getPassword(), authorities, new User("admin", "1234", authorities), assertion); } }
private UsernamePasswordAuthenticationToken createToken() { User user = createDefaultUser(); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()); return token; }
@Test public void deserializeUserWithClassIdInAuthoritiesTest() throws IOException { User user = mapper.readValue(userJson(), User.class); assertThat(user).isNotNull(); assertThat(user.getUsername()).isEqualTo("admin"); assertThat(user.getPassword()).isEqualTo("1234"); assertThat(user.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER")); }
@Test public void deserializeUserWithNullPasswordNoAuthorityTest() throws Exception { String userJsonWithoutPasswordString = removeNode(userWithNoAuthoritiesJson(), mapper, "password"); User user = mapper.readValue(userJsonWithoutPasswordString, User.class); assertThat(user).isNotNull(); assertThat(user.getUsername()).isEqualTo("admin"); assertThat(user.getPassword()).isNull(); assertThat(user.getAuthorities()).isEmpty(); assertThat(user.isEnabled()).isEqualTo(true); }
@Test public void findByUsernameWhenClearCredentialsThenFindByUsernameStillHasCredentials() { User foundUser = users.findByUsername(USER_DETAILS.getUsername()).cast(User.class).block(); assertThat(foundUser.getPassword()).isNotEmpty(); foundUser.eraseCredentials(); assertThat(foundUser.getPassword()).isNull(); foundUser = users.findByUsername(USER_DETAILS.getUsername()).cast(User.class).block(); assertThat(foundUser.getPassword()).isNotEmpty(); }
@Test public void deserializeRememberMeAuthenticationTokenWithUserTest() throws IOException { RememberMeAuthenticationToken token = mapper .readValue(String.format(REMEMBERME_AUTH_JSON, "\"password\""), RememberMeAuthenticationToken.class); assertThat(token).isNotNull(); assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class); assertThat(((User) token.getPrincipal()).getUsername()).isEqualTo("admin"); assertThat(((User) token.getPrincipal()).getPassword()).isEqualTo("1234"); assertThat(((User) token.getPrincipal()).getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER")); assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER")); assertThat(((User) token.getPrincipal()).isEnabled()).isEqualTo(true); } }
@Test public void serializeUserTest() throws JsonProcessingException, JSONException { User user = createDefaultUser(); String userJson = mapper.writeValueAsString(user); JSONAssert.assertEquals(userWithPasswordJson(user.getPassword()), userJson, true); }
@Test public void withUserDetailsWhenAllEnabled() throws Exception { User expected = new User("rob", "pass", true, true, true, true, ROLE_12); UserDetails actual = User.withUserDetails(expected).build(); assertThat(actual.getUsername()).isEqualTo(expected.getUsername()); assertThat(actual.getPassword()).isEqualTo(expected.getPassword()); assertThat(actual.getAuthorities()).isEqualTo(expected.getAuthorities()); assertThat(actual.isAccountNonExpired()).isEqualTo(expected.isAccountNonExpired()); assertThat(actual.isAccountNonLocked()).isEqualTo(expected.isAccountNonLocked()); assertThat(actual.isCredentialsNonExpired()).isEqualTo(expected.isCredentialsNonExpired()); assertThat(actual.isEnabled()).isEqualTo(expected.isEnabled()); }
@Test public void withUserDetailsWhenAllDisabled() throws Exception { User expected = new User("rob", "pass", false, false, false, false, ROLE_12); UserDetails actual = User.withUserDetails(expected).build(); assertThat(actual.getUsername()).isEqualTo(expected.getUsername()); assertThat(actual.getPassword()).isEqualTo(expected.getPassword()); assertThat(actual.getAuthorities()).isEqualTo(expected.getAuthorities()); assertThat(actual.isAccountNonExpired()).isEqualTo(expected.isAccountNonExpired()); assertThat(actual.isAccountNonLocked()).isEqualTo(expected.isAccountNonLocked()); assertThat(actual.isCredentialsNonExpired()).isEqualTo(expected.isCredentialsNonExpired()); assertThat(actual.isEnabled()).isEqualTo(expected.isEnabled()); }
@Test public void serializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws JsonProcessingException, JSONException { User user = createDefaultUser(); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities()); String serializedJson = mapper.writeValueAsString(token); JSONAssert.assertEquals(AUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true); }
@Test public void deserializeCasAuthenticationTest() throws IOException, JSONException { CasAuthenticationToken token = mapper.readValue(CAS_TOKEN_JSON, CasAuthenticationToken.class); assertThat(token).isNotNull(); assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class); assertThat(((User) token.getPrincipal()).getUsername()).isEqualTo("admin"); assertThat(((User) token.getPrincipal()).getPassword()).isEqualTo("1234"); assertThat(token.getUserDetails()).isNotNull().isInstanceOf(User.class); assertThat(token.getAssertion()).isNotNull().isInstanceOf(AssertionImpl.class); assertThat(token.getKeyHash()).isEqualTo(KEY.hashCode()); assertThat(token.getUserDetails().getAuthorities()) .extracting(GrantedAuthority::getAuthority) .containsOnly("ROLE_USER"); assertThat(token.getAssertion().getAuthenticationDate()).isEqualTo(START_DATE); assertThat(token.getAssertion().getValidFromDate()).isEqualTo(START_DATE); assertThat(token.getAssertion().getValidUntilDate()).isEqualTo(END_DATE); assertThat(token.getAssertion().getPrincipal().getName()).isEqualTo("assertName"); assertThat(token.getAssertion().getAttributes()).hasSize(0); }
@Test public void cacheOperationsAreSuccessful() throws Exception { SpringCacheBasedUserCache cache = new SpringCacheBasedUserCache(getCache()); // Check it gets stored in the cache cache.putUserInCache(getUser()); assertThat(getUser().getPassword()).isEqualTo(cache.getUserFromCache(getUser().getUsername()).getPassword()); // Check it gets removed from the cache cache.removeUserFromCache(getUser()); assertThat(cache.getUserFromCache(getUser().getUsername())).isNull(); // Check it doesn't return values for null or unknown users assertThat(cache.getUserFromCache(null)).isNull(); assertThat(cache.getUserFromCache("UNKNOWN_USER")).isNull(); }
@Test public void authenticationPrincipalExpressionWhenBeanExpressionSuppliedThenBeanUsed() throws Exception { User user = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities())); SecurityContextHolder.setContext(context); MockMvc mockMvc = MockMvcBuilders .webAppContextSetup(wac) .build(); mockMvc.perform(get("/users/self")) .andExpect(status().isOk()) .andExpect(content().string("extracted-user")); }
@Test public void cacheOperationsAreSuccessful() throws Exception { EhCacheBasedUserCache cache = new EhCacheBasedUserCache(); cache.setCache(getCache()); cache.afterPropertiesSet(); // Check it gets stored in the cache cache.putUserInCache(getUser()); assertThat(getUser().getPassword()).isEqualTo(cache.getUserFromCache(getUser().getUsername()).getPassword()); // Check it gets removed from the cache cache.removeUserFromCache(getUser()); assertThat(cache.getUserFromCache(getUser().getUsername())).isNull(); // Check it doesn't return values for null or unknown users assertThat(cache.getUserFromCache(null)).isNull(); assertThat(cache.getUserFromCache("UNKNOWN_USER")).isNull(); }