List of usage examples for org.springframework.security.core.userdetails User getAuthorities
public Collection<GrantedAuthority> getAuthorities()
From source file:ch.silviowangler.dox.security.DoxUserDetailService.java
@Override @Transactional(readOnly = true)//from w w w . ja v a 2s . c om public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { logger.trace("Trying create user details for user '{}'", username); final DoxUser user = userRepository.findByUsername(username); if (user == null) { logger.info("No such user with name '{}'", username); throw new UsernameNotFoundException("No such user " + username); } Collection<SimpleGrantedAuthority> authorities = Sets.newHashSet(); for (Role role : user.getRoles()) { final String roleName = "ROLE_" + role.getName(); logger.debug("Adding role {}", roleName); authorities.add(new SimpleGrantedAuthority(roleName)); for (ch.silviowangler.dox.domain.security.GrantedAuthority grantedAuthority : role .getGrantedAuthorities()) { authorities.add(new SimpleGrantedAuthority(grantedAuthority.getName())); } } User springSecurityUser = new User(user.getUsername(), user.getPassword(), authorities); logger.trace("User '{}' has these granted authorities '{}'", springSecurityUser.getUsername(), springSecurityUser.getAuthorities()); return springSecurityUser; }
From source file:org.ff4j.security.test.FlipSecurityTests.java
@Before public void setUp() throws Exception { securityCtx = SecurityContextHolder.getContext(); // Init SpringSecurity Context SecurityContext context = new SecurityContextImpl(); List<GrantedAuthority> listOfRoles = new ArrayList<GrantedAuthority>(); listOfRoles.add(new SimpleGrantedAuthority("ROLE_USER")); User u1 = new User("user1", "user1", true, true, true, true, listOfRoles); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(u1.getUsername(), u1.getPassword(), u1.getAuthorities()); token.setDetails(u1);//www .j av a 2 s . c om context.setAuthentication(token); SecurityContextHolder.setContext(context); // <-- ff4j = new FF4j("test-ff4j-security-spring.xml"); ff4j.setAuthorizationsManager(new SpringSecurityAuthorisationManager()); }
From source file:com.mastercard.test.spring.security.WithMockUserSecurityContextFactory.java
public SecurityContext createSecurityContext(WithMockUser withUser) { String username = StringUtils.hasLength(withUser.username()) ? withUser.username() : withUser.value(); if (username == null) { throw new IllegalArgumentException( withUser + " cannot have null username on both username and value properites"); }/* ww w. j a va2s . c o m*/ List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); for (String authority : withUser.authorities()) { grantedAuthorities.add(new SimpleGrantedAuthority(authority)); } if (grantedAuthorities.isEmpty()) { for (String role : withUser.roles()) { if (role.startsWith("ROLE_")) { throw new IllegalArgumentException("roles cannot start with ROLE_ Got " + role); } grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role)); } } else if (!(withUser.roles().length == 1 && "USER".equals(withUser.roles()[0]))) { throw new IllegalStateException("You cannot define roles attribute " + Arrays.asList(withUser.roles()) + " with authorities attribute " + Arrays.asList(withUser.authorities())); } User principal = new User(username, withUser.password(), true, true, true, true, grantedAuthorities); Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities()); SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(authentication); return context; }
From source file:com.netflix.genie.web.security.x509.X509UserDetailsServiceUnitTests.java
/** * Make sure if everything is present and proper the service returns a valid user. * * @throws UsernameNotFoundException on any error *//*www . j a v a2 s . c o m*/ @Test public void canAuthenticate() throws UsernameNotFoundException { final String username = UUID.randomUUID().toString(); final String role1 = UUID.randomUUID().toString(); final String role2 = UUID.randomUUID().toString(); Mockito.when(this.token.getPrincipal()).thenReturn(username + ":" + role1 + "," + role2); final UserDetails userDetails = this.service.loadUserDetails(this.token); if (!(userDetails instanceof User)) { throw new UsernameNotFoundException("Invalid return type"); } final User user = (User) userDetails; Assert.assertThat(user.getUsername(), Matchers.is(username)); Assert.assertThat(user.getPassword(), Matchers.is("NA")); Assert.assertThat(user.getAuthorities().size(), Matchers.is(3)); Assert.assertThat(user.getAuthorities(), Matchers.hasItems(new SimpleGrantedAuthority("ROLE_USER"), new SimpleGrantedAuthority("ROLE_" + role1.toUpperCase()), new SimpleGrantedAuthority("ROLE_" + role2.toUpperCase()))); }
From source file:org.springframework.security.jackson2.UserDeserializerTests.java
@Test public void deserializeUserWithNullPasswordNoAuthorityTest() throws IOException { String userJsonWithoutPasswordString = "{\"@class\": \"org.springframework.security.core.userdetails.User\", " + "\"username\": \"user\", \"accountNonExpired\": true, " + "\"accountNonLocked\": true, \"credentialsNonExpired\": true, \"enabled\": true, " + "\"authorities\": [\"java.util.HashSet\", []]}"; ObjectMapper mapper = buildObjectMapper(); User user = mapper.readValue(userJsonWithoutPasswordString, User.class); assertThat(user).isNotNull();/*w w w . j a va2s . co m*/ assertThat(user.getUsername()).isEqualTo("user"); assertThat(user.getPassword()).isEqualTo(""); assertThat(user.getAuthorities()).hasSize(0); assertThat(user.isEnabled()).isEqualTo(true); }
From source file:org.carewebframework.security.spring.AbstractAuthenticationProvider.java
/** * Authentication Provider. Produces a trusted <code>UsernamePasswordAuthenticationToken</code> * if// w w w . j av a 2 s . c o m * * @param authentication The authentication context. * @return authentication Authentication object if authentication succeeded. Null if not. */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { CWFAuthenticationDetails details = (CWFAuthenticationDetails) authentication.getDetails(); String username = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials(); String domain = null; if (log.isDebugEnabled()) { log.debug("User: " + username); log.debug("Details, RA: " + details == null ? "null" : details.getRemoteAddress()); } if (username != null) { String pcs[] = username.split("\\\\", 2); domain = pcs[0]; username = pcs.length > 1 ? pcs[1] : null; } ISecurityDomain securityDomain = domain == null ? null : SecurityUtil.getSecurityService().getSecurityDomain(domain); if (username == null || password == null || securityDomain == null) { throw new BadCredentialsException("Missing security credentials."); } IUser user = authenticate(username, password, securityDomain, details); details.setDetail("user", user); List<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>(); List<String> list = getAuthorities(user); Set<String> authorities = list == null ? new HashSet<String>() : new HashSet<String>(list); for (String grantedAuthority : grantedAuthorities) { if (grantedAuthority.startsWith("-")) { authorities.remove(grantedAuthority.substring(1)); } else { authorities.add(grantedAuthority); } } for (String authority : authorities) { if (!authority.isEmpty()) { userAuthorities.add(new SimpleGrantedAuthority(authority)); } } User principal = new User(username, password, true, true, true, true, userAuthorities); authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities()); ((UsernamePasswordAuthenticationToken) authentication).setDetails(details); return authentication; }
From source file:com.qpark.eip.core.spring.auth.DatabaseUserProvider.java
/** * Get a clone of the {@link User}./* w w w .j ava 2 s . c om*/ * * @param user * the {@link User} to clone. * @return the clone. */ private User clone(final User user) { User c = null; if (user != null) { c = new User(user.getUsername(), user.getPassword(), user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(), user.isAccountNonLocked(), user.getAuthorities()); } return c; }
From source file:eu.trentorise.smartcampus.permissionprovider.oauth.ClientCredentialsFilter.java
@Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { String clientId = request.getParameter("client_id"); String clientSecret = request.getParameter("client_secret"); // If the request is already authenticated we can assume that this filter is not needed Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.isAuthenticated()) { return authentication; }//from w w w. j a v a2 s . c om if (clientId == null) { throw new BadCredentialsException("No client credentials presented"); } if (clientSecret == null) { clientSecret = ""; } clientId = clientId.trim(); // UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId, clientSecret); ClientDetailsEntity clientDetails = clientDetailsRepository.findByClientId(clientId); boolean isTrusted = false; if (clientDetails.getAuthorities() != null) { for (GrantedAuthority ga : clientDetails.getAuthorities()) if (Config.AUTHORITY.ROLE_CLIENT_TRUSTED.toString().equals(ga.getAuthority())) { isTrusted = true; break; } } if (!isTrusted) { throw new InvalidGrantException("Unauthorized client access by client " + clientId); } String clientSecretServer = clientDetails.getClientSecret(); ClientAppInfo info = ClientAppInfo.convert(clientDetails.getAdditionalInformation()); String clientSecretMobile = clientDetails.getClientSecretMobile(); if (clientSecretMobile.equals(clientSecret) && !info.isNativeAppsAccess()) { throw new InvalidGrantException("Native app access is not enabled"); } if (!clientSecretServer.equals(clientSecret) && !clientSecretMobile.equals(clientSecret)) { throw new BadCredentialsException(messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } User user = new User(clientId, clientSecret, clientDetails.getAuthorities()); UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user, clientSecretServer, user.getAuthorities()); // result.setDetails(authRequest.getDetails()); return result; }
From source file:eu.openanalytics.rsb.security.JmxSecurityAuthenticator.java
private boolean isRsbAdminRole(final User authenticatedUser) { if ((configuration.getRsbSecurityConfiguration() == null) || (configuration.getRsbSecurityConfiguration().getAdminRoles() == null)) { return false; }//from w ww . ja v a2s. c o m final Set<String> authoritiesNames = new HashSet<String>(); for (final GrantedAuthority authority : authenticatedUser.getAuthorities()) { authoritiesNames.add(authority.getAuthority()); } return CollectionUtils.containsAny(configuration.getRsbSecurityConfiguration().getAdminRoles(), authoritiesNames); }
From source file:com.callcenter.service.UserService.java
@Override public UserDetails loadUserByUsername(final String userName) throws UsernameNotFoundException, DataAccessException { final com.callcenter.domain.User user = com.callcenter.domain.User.findUserByName(userName); if (user == null) throw new UsernameNotFoundException("User with the name: " + userName + " was not found"); final ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); for (final String authorityName : user.getAuthorities()) { grantedAuthorities.add(new GrantedAuthorityImpl(authorityName)); }/* www. ja v a 2 s . com*/ return new User(user.getName(), user.getPassword(), true, true, true, true, grantedAuthorities); }