List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken getPrincipal
public Object getPrincipal()
From source file:org.glassmaker.spring.web.MirrorTemplate.java
private String getUserId() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) auth; String userId = (String) token.getPrincipal(); return userId; }
From source file:cs544.wamp_blog_engine.filters.MyFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (((HttpServletRequest) request).getSession().getAttribute("loggedUser") == null) { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) ((HttpServletRequest) request) .getUserPrincipal();//w w w. java2 s .com if (token != null) { org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) token .getPrincipal(); ((HttpServletRequest) request).getSession().setAttribute("loggedUser", userService.getUserByUsername(user.getUsername())); // System.out.println("Inside Filter Logged User(from db):" + ((HttpServletRequest) request).getSession().getAttribute("loggedUser")); // System.out.println("Inside Filter Logged User(from request):" + user.getUsername()); } } chain.doFilter(request, response); }
From source file:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenMixinTest.java
@Test public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenWithUserTest() throws IOException { String tokenJson = "{\"@class\": \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\"," + "\"principal\": {\"@class\": \"org.springframework.security.core.userdetails.User\", \"username\": \"user\", \"password\": \"pass\", \"accountNonExpired\": true, \"enabled\": true, " + "\"accountNonLocked\": true, \"credentialsNonExpired\": true, \"authorities\": [\"java.util.Collections$UnmodifiableSet\"," + "[{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}, \"credentials\": \"pass\"," + "\"details\": null, \"name\": \"user\", \"authenticated\": true," + "\"authorities\": [\"java.util.ArrayList\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}"; ObjectMapper mapper = buildObjectMapper(); UsernamePasswordAuthenticationToken token = mapper.readValue(tokenJson, UsernamePasswordAuthenticationToken.class); assertThat(token).isNotNull();/*from w w w .ja v a 2s . c o m*/ assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class); assertThat(((User) token.getPrincipal()).getAuthorities()).isNotNull().hasSize(1) .contains(new SimpleGrantedAuthority("ROLE_USER")); assertThat(token.isAuthenticated()).isEqualTo(true); assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER")); }
From source file:com.oak_yoga_studio.filters.MyFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Inside filter"); if (((HttpServletRequest) request).getSession().getAttribute("loggedUser") == null) { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) ((HttpServletRequest) request) .getUserPrincipal();//from w w w. j av a 2s . co m if (token != null) { org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) token .getPrincipal(); ((HttpServletRequest) request).getSession().setAttribute("loggedUser", userService.getUserByUsername(user.getUsername())); } } //re-attach the customer object to the session else { User customer = (User) ((HttpServletRequest) request).getSession().getAttribute("loggedUser"); if (customer instanceof Customer) { userService.updateCustomer(customer.getId(), (Customer) customer); } } chain.doFilter(request, response); }
From source file:org.taverna.server.master.identity.WorkflowInternalAuthProvider.java
@Override @PerfLogged//www .j av a 2s . co m protected final void additionalAuthenticationChecks(UserDetails userRecord, UsernamePasswordAuthenticationToken token) { try { additionalAuthenticationChecks(userRecord, token.getPrincipal(), token.getCredentials()); } catch (AuthenticationException e) { throw e; } catch (Exception e) { log.warn("unexpected failure in authentication", e); throw new AuthenticationServiceException("unexpected failure in authentication", e); } }
From source file:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenMixinTest.java
@Test public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinWithCustomUserTest() throws Exception { String tokenJson = "{" + " \"@class\" : \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\"," + " \"details\" : null," + " \"authorities\" : [ \"java.util.ArrayList\", [ {" + " \"@class\" : \"org.springframework.security.core.authority.SimpleGrantedAuthority\"," + " \"role\" : \"ROLE_USER\"" + " } ] ]," + " \"authenticated\" : true," + " \"principal\" : {" + " \"@class\" : \"org.springframework.security.jackson2.CustomUserForTest\"," + " \"username\" : \"user\"," + " \"password\" : \"pass\"," + " \"customProperty\" : \"custom\"," + " \"authorities\" : [ \"java.util.ArrayList\", [ {" + " \"@class\" : \"org.springframework.security.core.authority.SimpleGrantedAuthority\"," + " \"role\" : \"ROLE_USER\"" + " } ] ]," + " \"accountNonExpired\" : true," + " \"accountNonLocked\" : true," + " \"credentialsNonExpired\" : true," + " \"enabled\" : true" + " }," + " \"credentials\" : \"pass\"," + " \"name\" : \"user\"" + "}"; UsernamePasswordAuthenticationToken token = buildObjectMapper().readValue(tokenJson, UsernamePasswordAuthenticationToken.class); assertThat(token).isNotNull();// w ww . j a v a 2 s . co m assertThat(token.getPrincipal()).isNotNull().isInstanceOf(CustomUserForTest.class); assertThat(((CustomUserForTest) token.getPrincipal()).getAuthorities()).isNotNull().hasSize(1) .contains(new SimpleGrantedAuthority("ROLE_USER")); assertThat(((CustomUserForTest) token.getPrincipal()).getCustomProperty()).isNotNull().isEqualTo("custom"); assertThat(token.isAuthenticated()).isEqualTo(true); assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER")); }
From source file:nl.surfnet.coin.api.MockApiController.java
@Override protected ClientMetaData getClientMetaData() { try {//ww w .jav a 2s . c o m return super.getClientMetaData(); } catch (IllegalArgumentException e) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // basic if (authentication instanceof UsernamePasswordAuthenticationToken) { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; EntityMetadata metaData = new EntityMetadata(); metaData.setAppEntityId("DUMMY-BASIC-AUTH"); metaData.setOauthConsumerKey(token.getPrincipal() + ":" + token.getCredentials()); JanusClientMetadata clientMetadata = new JanusClientMetadata(metaData); return clientMetadata; } else { throw e; } } }
From source file:org.taverna.server.master.identity.StrippedDownAuthProvider.java
@PerfLogged @Override//from ww w. j a v a 2 s. c o m public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!(authentication instanceof UsernamePasswordAuthenticationToken)) throw new IllegalArgumentException("can only authenticate against username+password"); UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; // Determine username String username = (auth.getPrincipal() == null) ? "NONE_PROVIDED" : auth.getName(); UserDetails user; try { user = retrieveUser(username, auth); if (user == null) throw new IllegalStateException( "retrieveUser returned null - a violation of the interface contract"); } catch (UsernameNotFoundException notFound) { if (logger.isDebugEnabled()) logger.debug("User '" + username + "' not found", notFound); throw new BadCredentialsException("Bad credentials"); } // Pre-auth if (!user.isAccountNonLocked()) throw new LockedException("User account is locked"); if (!user.isEnabled()) throw new DisabledException("User account is disabled"); if (!user.isAccountNonExpired()) throw new AccountExpiredException("User account has expired"); Object credentials = auth.getCredentials(); if (credentials == null) { logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException("Bad credentials"); } String providedPassword = credentials.toString(); boolean matched = false; synchronized (authCache) { AuthCacheEntry pw = authCache.get(username); if (pw != null && providedPassword != null) { if (pw.valid(providedPassword)) matched = true; else authCache.remove(username); } } // Auth if (!matched) { if (!passwordEncoder.matches(providedPassword, user.getPassword())) { logger.debug("Authentication failed: password does not match stored value"); throw new BadCredentialsException("Bad credentials"); } if (providedPassword != null) synchronized (authCache) { authCache.put(username, new AuthCacheEntry(providedPassword)); } } // Post-auth if (!user.isCredentialsNonExpired()) throw new CredentialsExpiredException("User credentials have expired"); return createSuccessAuthentication(user, auth, user); }
From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationProviderTest.java
@Test public void shouldAddCredentialsToClaudiaDataWhenAuthenticatedWithToken() { // given/*from w w w . ja v a2s . com*/ ClaudiaData claudiaData = new ClaudiaData("org", "vdc", "service"); SecurityContext context = mock(SecurityContext.class); SecurityContextHolder.setContext(context); UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = mock( UsernamePasswordAuthenticationToken.class); when(context.getAuthentication()).thenReturn(usernamePasswordAuthenticationToken); when(usernamePasswordAuthenticationToken.getPrincipal()).thenReturn("token1"); when(usernamePasswordAuthenticationToken.getCredentials()).thenReturn("tenantId1"); // when OpenStackAuthenticationProvider.addCredentialsToClaudiaData(claudiaData); // then assertNotNull(claudiaData); assertEquals("org", claudiaData.getOrg()); assertEquals("vdc", claudiaData.getVdc()); assertEquals("service", claudiaData.getService()); assertEquals("token1", claudiaData.getUser().getToken()); assertEquals("tenantId1", claudiaData.getUser().getTenantId()); assertEquals("", claudiaData.getUser().getTenantName()); }
From source file:com.creativity.repository.Fichas.java
private UsuarioSistema getUsuarioLogado() { UsuarioSistema usuario = null;/* ww w.j ava 2 s. c o m*/ UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) FacesContext .getCurrentInstance().getExternalContext().getUserPrincipal(); if (auth != null && auth.getPrincipal() != null) { usuario = (UsuarioSistema) auth.getPrincipal(); } return usuario; }