@RequestMapping(value = "/authenticate", method = RequestMethod.POST) public TokenTransfer authenticate(@RequestParam("username") String username, @RequestParam("password") String password) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password); Authentication authentication = authManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); UserDetails userDetails = userDetailsService.loadUserByUsername(username); return new TokenTransfer(TokenUtils.createToken(userDetails)); }
public Collection<? extends GrantedAuthority> attemptAuthentication(String username, String password) throws RemoteAuthenticationException { UsernamePasswordAuthenticationToken request = new UsernamePasswordAuthenticationToken( username, password); try { return authenticationManager.authenticate(request).getAuthorities(); } catch (AuthenticationException authEx) { throw new RemoteAuthenticationException(authEx.getMessage()); } }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials(); UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (!password.equals(userDetails.getPassword())) { return new UsernamePasswordAuthenticationToken(username, null, null); } return null; }
@Test public void serializingThenDeserializingWithNoCredentialsOrDetailsShouldWork() throws IOException { // given UsernamePasswordAuthenticationToken original = new UsernamePasswordAuthenticationToken("Frodo", null); // when String serialized = this.mapper.writeValueAsString(original); UsernamePasswordAuthenticationToken deserialized = this.mapper.readValue(serialized, UsernamePasswordAuthenticationToken.class); // then assertThat(deserialized).isEqualTo(original); }
@Test(expected = IllegalArgumentException.class) public void testRejectsNulls() { new AuthorizedEvent(null, SecurityConfig.createList("TEST"), new UsernamePasswordAuthenticationToken("foo", "bar")); }
@Test public void serializingThenDeserializingWithConfiguredObjectMapperShouldWork() throws IOException { // given this.mapper.setDefaultPropertyInclusion(construct(ALWAYS, NON_NULL)).setSerializationInclusion(NON_ABSENT); UsernamePasswordAuthenticationToken original = new UsernamePasswordAuthenticationToken("Frodo", null); // when String serialized = this.mapper.writeValueAsString(original); UsernamePasswordAuthenticationToken deserialized = this.mapper.readValue(serialized, UsernamePasswordAuthenticationToken.class); // then assertThat(deserialized).isEqualTo(original); }
@Test public void serializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws JsonProcessingException, JSONException { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("admin", "1234"); String serializedJson = mapper.writeValueAsString(token); JSONAssert.assertEquals(UNAUTHENTICATED_STRINGPRINCIPAL_JSON, serializedJson, true); }
@Test public void delegateUsesExisitingAuthentication() { String username = "user"; String password = "password"; when(this.uds.loadUserByUsername(username)).thenReturn(PasswordEncodedUser.user()); AuthenticationManager authenticationManager = this.adapter.authenticationManager; assertThat(authenticationManager).isNotNull(); Authentication auth = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(username, password)); verify(this.uds).loadUserByUsername(username); assertThat(auth.getPrincipal()).isEqualTo(PasswordEncodedUser.user()); }
private OAuth2Authentication extractAuthentication(Map<String, Object> map) { Object principal = getPrincipal(map); OAuth2Request request = getRequest(map); List<GrantedAuthority> authorities = this.authoritiesExtractor .extractAuthorities(map); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( principal, "N/A", authorities); token.setDetails(map); return new OAuth2Authentication(request, token); }
private OAuth2Authentication extractAuthentication(Map<String, Object> map) { Object principal = getPrincipal(map); OAuth2Request request = getRequest(map); List<GrantedAuthority> authorities = this.authoritiesExtractor .extractAuthorities(map); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( principal, "N/A", authorities); token.setDetails(map); return new OAuth2Authentication(request, token); }
@Test public void permitAllShouldBeDefaultAttribute() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "Test", "Password", AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(token); target.someOther(0); }
@Test public void getAuthenticationWhenUserDetailsServiceBeanThenAuthenticationManagerUsesUserDetailsServiceBean() throws Exception { this.spring.register(UserDetailsServiceBeanConfig.class).autowire(); UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class); AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager(); when(uds.loadUserByUsername("user")).thenReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user()); am.authenticate(new UsernamePasswordAuthenticationToken("user", "password")); assertThatThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid"))) .isInstanceOf(AuthenticationException.class); }
@Test public void getAuthenticationWhenGlobalAuthenticationConfigurerAdapterThenAuthenticates() throws Exception { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password"); this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class, UserGlobalAuthenticationConfigurerAdapter.class).autowire(); AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager(); assertThat(authentication.authenticate(token).getName()).isEqualTo(token.getName()); }
@Test public void testSuccessfulAuthenticationCreatesObject() { RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider(); provider.setRemoteAuthenticationManager( new MockRemoteAuthenticationManager(true)); Authentication result = provider .authenticate(new UsernamePasswordAuthenticationToken("rod", "password")); assertThat(result.getPrincipal()).isEqualTo("rod"); assertThat(result.getCredentials()).isEqualTo("password"); assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())).contains("foo"); }
@Test public void roleHiearchy() throws Exception { loadConfig(RoleHiearchyConfig.class); SecurityContext securityContext = new SecurityContextImpl(); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("test", "notused", AuthorityUtils.createAuthorityList("ROLE_USER"))); this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext); this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain); assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK); }
@Test public void methodSecurityAuthenticationManagerPublishesEvent() { this.spring.register(InMemoryAuthWithGlobalMethodSecurityConfig.class).autowire(); try { this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar")); } catch(AuthenticationException e) {} assertThat(this.events.getEvents()).extracting(Object::getClass).containsOnly((Class) AuthenticationFailureBadCredentialsEvent.class); }
@Test public void testNotEqualsDueToDifferentAuthenticationClass() { final Assertion assertion = new AssertionImpl("test"); CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", ROLES, makeUserDetails(), assertion); UsernamePasswordAuthenticationToken token2 = new UsernamePasswordAuthenticationToken( "Test", "Password", ROLES); assertThat(!token1.equals(token2)).isTrue(); }
@Test public void testDoesNotReturnAdditionalAuthoritiesIfCalledWithoutARunAsSetting() throws Exception { UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken( "Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); RunAsManagerImpl runAs = new RunAsManagerImpl(); runAs.setKey("my_password"); Authentication resultingToken = runAs.buildRunAs(inputToken, new Object(), SecurityConfig.createList("SOMETHING_WE_IGNORE")); assertThat(resultingToken).isNull(); }
@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 createNewAuthenticationUsesNullPasswordToKeepPassordsSave() { insertJoe(); UsernamePasswordAuthenticationToken currentAuth = new UsernamePasswordAuthenticationToken( "joe", null, AuthorityUtils.createAuthorityList("ROLE_USER")); Authentication updatedAuth = manager.createNewAuthentication(currentAuth, "new"); assertThat(updatedAuth.getCredentials()).isNull(); }