Java Code Examples for org.springframework.security.core.authority.SimpleGrantedAuthority

The following examples show how to use org.springframework.security.core.authority.SimpleGrantedAuthority. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public SecurityContext createSecurityContext(WithMockAdminUser customUser) {
    SecurityContext context = SecurityContextHolder.createEmptyContext();

    UserDetailsImpl userDetails = new UserDetailsImpl("[email protected]", "[email protected]#",
            "1234", "jakduk-admin", Constants.ACCOUNT_TYPE.JAKDUK, true, true,
            true, true, Arrays.asList(new SimpleGrantedAuthority(JakdukAuthority.ROLE_ROOT.name())));

    userDetails.setPicture(
            new UserPictureInfo(
                    "597a0d53807d710f57420aa5",
                    "https://dev-api.jakduk.com/user/picture/small/597a0d53807d710f57420aa5",
                    "https://dev-api.jakduk.com/user/picture/597a0d53807d710f57420aa5"
            )
    );

    Authentication auth =
            new UsernamePasswordAuthenticationToken(userDetails, "1234", userDetails.getAuthorities());

    context.setAuthentication(auth);
    return context;
}
 
Example 2
@Test
public void testJWTFilter() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
    assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
}
 
Example 3
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
  Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
  SimpleGrantedAuthority authority = new SimpleGrantedAuthority(this.role);
  authorities.add(authority);
  return authorities;
}
 
Example 4
private UserDetails prepareUserDetails(String jsonUserDetails) throws JsonProcessingException, IOException{
	
	ObjectMapper objectMapper = new ObjectMapper();
	JsonNode root = objectMapper.readTree(jsonUserDetails);
	
	String userId = root.get("dbUser").get("id").asText();
	String username = root.get("username").asText();
	boolean isEnabled =  root.get("enabled").asBoolean();
	
	List<SimpleGrantedAuthority> authorities = new ArrayList<>();
	
	Iterator<JsonNode> authoritiesIterator = root.get("authorities").elements();
	while(authoritiesIterator.hasNext()){
		JsonNode authorityNode = authoritiesIterator.next();
		authorities.add(new SimpleGrantedAuthority(authorityNode.get("authority").asText()));
	}
	
	return new AuthUser(userId, username, authorities, isEnabled);
}
 
Example 5
Source Project: kafka-webview   Source File: CustomUserDetails.java    License: MIT License 6 votes vote down vote up
/**
 * Constructor when authenticating from local user as defined in database.
 * @param userModel User entity model to authenticate as.
 */
public CustomUserDetails(final User userModel) {
    // set model
    this.userModel = userModel;

    // Generate authorities/roles
    final List<GrantedAuthority> roles = new ArrayList<>();

    // Everyone gets user
    roles.add(new SimpleGrantedAuthority("ROLE_USER"));

    // Add Admin
    if (UserRole.ROLE_ADMIN.equals(userModel.getRole())) {
        roles.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
    }

    // Save to immutable collection.
    authorities = Collections.unmodifiableList(roles);
}
 
Example 6
@Test
void doNotSendWarningEmailIfAdmin() {
    final String ticketId = "abcde";
    final String ticketReservationId = "abcdef";
    final String originalEmail = "[email protected]";
    final String originalName = "First Last";
    Ticket original = mock(Ticket.class);
    Ticket modified = mock(Ticket.class);
    UpdateTicketOwnerForm form = new UpdateTicketOwnerForm();
    when(event.getShortName()).thenReturn("short-name");
    initUpdateTicketOwner(original, modified, ticketId, originalEmail, originalName, form);
    TicketReservation reservation = mock(TicketReservation.class);
    when(original.getTicketsReservationId()).thenReturn(ticketReservationId);
    when(ticketReservationRepository.findOptionalReservationById(eq(ticketReservationId))).thenReturn(Optional.of(reservation));
    UserDetails userDetails = new User("user", "password", singletonList(new SimpleGrantedAuthority(Role.ADMIN.getRoleName())));
    trm.updateTicketOwner(original, Locale.ENGLISH, event, form, (a) -> null,(b) -> null, Optional.of(userDetails));
    verify(messageSource, never()).getMessage(eq("ticket-has-changed-owner-subject"), eq(new Object[] {"short-name"}), eq(Locale.ITALIAN));
}
 
Example 7
Source Project: blog-sample   Source File: DefaultUserDetailsService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    // 从数据库中取出用户信息
    SysUser user = userService.getByName(username);

    // 判断用户是否存在
    if (user == null) {
        throw new UsernameNotFoundException("用户名不存在");
    }

    // 添加权限
    List<SysUserRole> userRoles = userRoleService.listByUserId(user.getId());
    for (SysUserRole userRole : userRoles) {
        SysRole role = roleService.getById(userRole.getRoleId());
        authorities.add(new SimpleGrantedAuthority(role.getName()));
    }

    // 返回UserDetails实现类
    return new User(user.getName(), user.getPassword(), authorities);
}
 
Example 8
@Test
void testGetReachableGrantedAuthoritiesUsingCacheMultiple() {
  TransactionSynchronizationManager.setCurrentTransactionReadOnly(true);

  GrantedAuthority managerAuthority = new SimpleGrantedAuthority("ROLE_MANAGER");
  GrantedAuthority editorAuthority = new SimpleGrantedAuthority("ROLE_EDITOR");
  GrantedAuthority viewerAuthority = new SimpleGrantedAuthority("ROLE_VIEWER");
  ImmutableMap<GrantedAuthority, ImmutableSet<GrantedAuthority>> authorityInclusions =
      ImmutableMap.<GrantedAuthority, ImmutableSet<GrantedAuthority>>builder()
          .put(managerAuthority, ImmutableSet.of(editorAuthority))
          .put(editorAuthority, ImmutableSet.of(viewerAuthority))
          .put(viewerAuthority, ImmutableSet.of())
          .build();
  when(dataserviceRoleHierarchy.getAllGrantedAuthorityInclusions())
      .thenReturn(authorityInclusions);
  assertEquals(
      ImmutableSet.of(managerAuthority, editorAuthority, viewerAuthority),
      cachedRoleHierarchyImpl.getReachableGrantedAuthorities(
          asList(managerAuthority, editorAuthority)));
}
 
Example 9
@Override
public UserDetails loadUserByUsername(String username)
		throws UsernameNotFoundException {

	try {

		Collection<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>();
		userAuthorities.add(new SimpleGrantedAuthority(ROLE_USER));

		List<Userinfo> userinfos = userService.findByUserName(username);

		Userinfo userinfo = userinfos.get(0);

		User user = new User(userinfo.getUserName(),
				userinfo.getPassword(), true, true, true, true,
				userAuthorities);
		currentUser.set(user);
		return user;

	} catch (Exception e) {
		throw new UsernameNotFoundException("Username " + username
				+ " not found!");
	}

}
 
Example 10
Source Project: expper   Source File: UserDetailsService.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
    log.debug("Authenticating {}", login);
    String lowercaseLogin = login.toLowerCase();
    Optional<User> userFromDatabase = userRepository.findOneByLoginOrEmail(lowercaseLogin, lowercaseLogin);
    return userFromDatabase.map(user -> {
        if (!user.getActivated()) {
            throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
        }
        List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
                .map(authority -> new SimpleGrantedAuthority(authority.getName()))
            .collect(Collectors.toList());
        return new org.springframework.security.core.userdetails.User(lowercaseLogin,
            user.getPassword(),
            grantedAuthorities);
    }).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " +
    "database"));
}
 
Example 11
Source Project: jhipster-registry   Source File: JWTFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJWTFilter() throws Exception {
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
        "test-user",
        "test-password",
        Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
    );
    String jwt = tokenProvider.createToken(authentication, false);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
    request.setRequestURI("/api/test");
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();
    jwtFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
    assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
    assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
}
 
Example 12
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {

    CalendarUser user = userRepository.findByEmail(username);

    if (user == null)
        throw new UsernameNotFoundException("username " + username
                + " not found");

    Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
    for (Role role : user.getRoles()){
        grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
    }

    return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), grantedAuthorities);
}
 
Example 13
Source Project: JavaSpringMvcBlog   Source File: UserServiceTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldLoadUserDetails() {
    User user = new User();
    user.setUsername(NAME);
    user.setPassword("123");

    List<String> role1Names = Arrays.asList("role1", "role2");
    for (String roleName : role1Names) {
        Role role = new Role();
        role.setName(roleName);
        user.getRoles().add(role);
    }

    when(userRepository.findByUsernameOrEmail(NAME, NAME)).thenReturn(user);

    UserDetails userDetails = userService.loadUserByUsername(NAME);

    List<SimpleGrantedAuthority> authorities = role1Names.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    assertThat(userDetails.getAuthorities().containsAll(authorities), is(equalTo(true)));

    verify(userRepository, times(1)).findByUsernameOrEmail(NAME, NAME);
}
 
Example 14
Source Project: kylin   Source File: KylinUserGroupService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, List<String>> getGroupMembersMap() throws IOException {
    Map<String, List<String>> result = Maps.newHashMap();
    List<ManagedUser> users = userService.listUsers();
    for (ManagedUser user : users) {
        for (SimpleGrantedAuthority authority : user.getAuthorities()) {
            String role = authority.getAuthority();
            List<String> usersInGroup = result.get(role);
            if (usersInGroup == null) {
                result.put(role, Lists.newArrayList(user.getUsername()));
            } else {
                usersInGroup.add(user.getUsername());
            }
        }
    }
    return result;
}
 
Example 15
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException {
    String code = request.getParameter(CODE);
    if (code == null) {
        logger.warn("Error: authorization code is null");
        throw new IllegalArgumentException("authorization code cannot be null");
    }
    logger.trace("Received code. Attempting to exchange it with an access Token");
    OpenIdAlfioUser alfioUser = openIdAuthenticationManager.retrieveUserInfo(code);

    logger.trace("Got user info: "+alfioUser);
    if (!userManager.usernameExists(alfioUser.getEmail())) {
        createUser(alfioUser);
    }
    updateRoles(alfioUser.getAlfioRoles(), alfioUser.getEmail());
    updateOrganizations(alfioUser, response);

    List<GrantedAuthority> authorities = alfioUser.getAlfioRoles().stream().map(Role::getRoleName)
        .map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    WebSecurityConfig.OpenIdAlfioAuthentication authentication = new WebSecurityConfig.OpenIdAlfioAuthentication(authorities, alfioUser.getIdToken(), alfioUser.getSubject(), alfioUser.getEmail(), openIdAuthenticationManager.buildLogoutUrl());
    return getAuthenticationManager().authenticate(authentication);
}
 
Example 16
Source Project: tutorials   Source File: CustomIpAuthenticationProvider.java    License: MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
    String userIp = details.getRemoteAddress();
    if(! whitelist.contains(userIp)){
        throw new BadCredentialsException("Invalid IP Address");
    }
    final String name = auth.getName();
    final String password = auth.getCredentials().toString();
    
    if (name.equals("john") && password.equals("123")) {
    List<GrantedAuthority> authorities =new ArrayList<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
    return new UsernamePasswordAuthenticationToken(name, password, authorities);
    }
    else{
        throw new BadCredentialsException("Invalid username or password");
    }
}
 
Example 17
Source Project: pentaho-kettle   Source File: PurRepositoryIT.java    License: Apache License 2.0 6 votes vote down vote up
protected void setUpUser() {
  StandaloneSession pentahoSession = new StandaloneSession( userInfo.getLogin() );
  pentahoSession.setAuthenticated( userInfo.getLogin() );
  pentahoSession.setAttribute( IPentahoSession.TENANT_ID_KEY, "/pentaho/" + EXP_TENANT );
  List<GrantedAuthority> authorities = new ArrayList<>( 2 );
  authorities.add( new SimpleGrantedAuthority( "Authenticated" ) );
  authorities.add( new SimpleGrantedAuthority( "acme_Authenticated" ) );
  final String password = "ignored"; //$NON-NLS-1$
  UserDetails userDetails = new User( userInfo.getLogin(), password, true, true, true, true, authorities );
  Authentication authentication = new UsernamePasswordAuthenticationToken( userDetails, password, authorities );
  // next line is copy of SecurityHelper.setPrincipal
  pentahoSession.setAttribute( "SECURITY_PRINCIPAL", authentication );
  SecurityContextHolder.setStrategyName( SecurityContextHolder.MODE_GLOBAL );
  PurRepositoryTestingUtils.setSession( pentahoSession, authentication );
  repositoryLifecyleManager.newTenant();
  repositoryLifecyleManager.newUser();
}
 
Example 18
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {

    CalendarUser user = userRepository.findByEmail(username);

    if (user == null)
        throw new UsernameNotFoundException("username " + username
                + " not found");

    Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
    for (Role role : user.getRoles()){
        grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
    }

    return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), grantedAuthorities);
}
 
Example 19
Source Project: spring-cloud-study   Source File: KiteUserDetailsService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    log.info("usernameis:" + username);
    // 查询数据库操作
    if(!username.equals("admin")){
        throw new UsernameNotFoundException("the user is not found");
    }else{
        // 用户角色也应在数据库中获取
        String role = "ROLE_ADMIN";
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(role));
        // 线上环境应该通过用户名查询数据库获取加密后的密码
        String password = passwordEncoder.encode("123456");
        // 返回默认的 User
        // return new org.springframework.security.core.userdetails.User(username,password, authorities);

        // 返回自定义的 KiteUserDetails
        User user = new User(username,password,authorities);
       return user;
    }
}
 
Example 20
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.notNull(authentication, "No authentication data provided");

    String key = (String) authentication.getPrincipal();
    String secret = (String) authentication.getCredentials();
    
    Org org;
    try {
      org = orgService.findByApiKeyAndApiSecret(key, secret);
    } 
    catch (OrgNotFoundException e) {
      throw new AuthenticationCredentialsNotFoundException(e.getMessage());
    }
    List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_ORG_ADMIN"));        
    UserContext userContext = UserContext.create(org.getMetadata().get(Vocabulary.TENANT), org.getSourcedId(), authorities);
    return new UsernamePasswordAuthenticationToken(userContext, null, userContext.getAuthorities());
}
 
Example 21
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {

    CalendarUser user = userRepository.findByEmail(username);

    if (user == null)
        throw new UsernameNotFoundException("username " + username
                + " not found");

    Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
    for (Role role : user.getRoles()){
        grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
    }

    return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), grantedAuthorities);
}
 
Example 22
public Object loadUserBySAML(SAMLCredential credential)
		throws UsernameNotFoundException {
	
	// The method is supposed to identify local account of user referenced by
	// data in the SAML assertion and return UserDetails object describing the user.
	
	String userID = credential.getNameID().getValue();
	
	LOG.info(userID + " is logged in");
	List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
	GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
	authorities.add(authority);

	// In a real scenario, this implementation has to locate user in a arbitrary
	// dataStore based on information present in the SAMLCredential and
	// returns such a date in a form of application specific UserDetails object.
	return new User(userID, "<abc123>", true, true, true, true, authorities);
}
 
Example 23
Source Project: sctalk   Source File: JwtUserDetailsServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    ManagerUser user = userRepository.findByUsername(username);
    if (user == null) {
        throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
    } else {
        return new JwtTalkUser(user.getUsername(), user.getPassword(),
                user.getRoles().stream().map(role -> role.getRoleName())
                        .map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
    }
}
 
Example 24
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  String name = authentication.getName();
  String password = authentication.getCredentials().toString();

  if (isValidUser(name, password)) {
    List<GrantedAuthority> grantedAuths = new ArrayList<>();
    grantedAuths.add(new SimpleGrantedAuthority("USER"));
    return new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
  }

  throw new BadCredentialsException("Invalid password or user name.");
}
 
Example 25
Source Project: data-highway   Source File: OnrampAuthorisationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void authorised() throws Exception {
  onramp.setAuthorities(singletonList("AUTHORIZED"));
  doReturn(true).when(authentication).isAuthenticated();
  doReturn(singletonList(new SimpleGrantedAuthority("AUTHORIZED"))).when(authentication).getAuthorities();

  boolean result = underTest.isAuthorised(authentication, ROAD_NAME);
  assertThat(result, is(true));
  verify(metrics).increment("road1", AUTHENTICATED, AUTHORISED);
}
 
Example 26
Source Project: server   Source File: UserDto.java    License: MIT License 5 votes vote down vote up
@JsonIgnore
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return roles.stream()
            .map(role -> new SimpleGrantedAuthority(role.getName()))
            .collect(Collectors.toList());
}
 
Example 27
@Override
public List<GrantedAuthority> extractAuthorities(Map<String, Object> map) {
    return Optional.ofNullable((List<String>) map.get(oauth2AuthoritiesAttribute))
        .filter(it -> !it.isEmpty())
        .orElse(Collections.emptyList())
        .stream()
        .map(SimpleGrantedAuthority::new)
        .collect(toList());
}
 
Example 28
Source Project: cubeai   Source File: DomainUserDetailsService.java    License: Apache License 2.0 5 votes vote down vote up
private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {
    if (!user.getActivated()) {
        throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
    }
    List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
        .map(authority -> new SimpleGrantedAuthority(authority.getName()))
        .collect(Collectors.toList());
    return new org.springframework.security.core.userdetails.User(user.getLogin(),
        user.getPassword(),
        grantedAuthorities);
}
 
Example 29
Source Project: platform   Source File: SecurityUserDetailsService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserDto user = userService.findByUsername(username);
    if (null == user) {
        throw new UsernameNotFoundException(username);
    }

    List<SimpleGrantedAuthority> authorities = Lists.newArrayList();
    authorities.add(new SimpleGrantedAuthority("USER"));

    return new SecurityUser(user.getUsername(), user.getPassword(), authorities);
}
 
Example 30
Source Project: multitenancy   Source File: CustomUserDetailsServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsernameAndTenantname(String username, String tenant)
        throws UsernameNotFoundException {
    if (StringUtils.isAnyBlank(username, tenant)) {
        throw new UsernameNotFoundException("Username and domain must be provided");
    }
    // Look for the user based on the username and tenant by accessing the
    // UserRepository via the UserService
    User user = userService.findByUsernameAndTenantname(username, tenant);

    if (user == null) {
        throw new UsernameNotFoundException(
                String.format("Username not found for domain, "
                        + "username=%s, tenant=%s", username, tenant));
    }

    Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
    for (Role role : user.getRoles()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(role.getRole()));
    }

    CustomUserDetails customUserDetails = 
            new CustomUserDetails(user.getUsername(), 
                    user.getPassword(), grantedAuthorities, tenant);
    
    return customUserDetails;
}