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

The following examples show how to use org.springframework.security.core.authority.SimpleGrantedAuthority. 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
Source File: WithMockAdminUserSecurityContextFactory.java    From jakduk-api with MIT License 7 votes vote down vote up
@Override
public SecurityContext createSecurityContext(WithMockAdminUser customUser) {
    SecurityContext context = SecurityContextHolder.createEmptyContext();

    UserDetailsImpl userDetails = new UserDetailsImpl("[email protected]", "a!b@c#",
            "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
Source File: JWTFilterTest.java    From jhipster-microservices-example with Apache License 2.0 7 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(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
Source File: CustomUserDeatilService.java    From springrest-angularjs with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: CustomUserDetails.java    From kafka-webview with 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 #5
Source File: CommonAuthenticationTokenFilter.java    From microservices-sample-project with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: TicketReservationManagerTest.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
@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 File: SAMLUserDetailsServiceImpl.java    From spring-boot-security-saml-sample with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: WebSecurityConfig.java    From spring-cloud-docker-microservice-book-code with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
  Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
  SimpleGrantedAuthority authority = new SimpleGrantedAuthority(this.role);
  authorities.add(authority);
  return authorities;
}
 
Example #9
Source File: DefaultUserDetailsService.java    From blog-sample with 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 #10
Source File: CachedRoleHierarchyImplTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #11
Source File: KylinUserGroupService.java    From kylin with 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 #12
Source File: UserDetailsService.java    From expper with 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 #13
Source File: AjaxAuthenticationProvider.java    From OpenLRW with Educational Community License v2.0 6 votes vote down vote up
@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 #14
Source File: OpenIdCallbackLoginFilter.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
@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 #15
Source File: UserServiceTest.java    From JavaSpringMvcBlog with 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 #16
Source File: AuthenticationCheck.java    From ranger with Apache License 2.0 6 votes vote down vote up
private Authentication getADBindAuthentication(String ldapUrl, String bindDn, String bindPassword,
                                               String userName, String userPassword) {
    Authentication result = null;
    try {
        LdapContextSource ldapContextSource = new DefaultSpringSecurityContextSource(ldapUrl);
        ldapContextSource.setUserDn(bindDn);
        ldapContextSource.setPassword(bindPassword);
        ldapContextSource.setReferral("follow");
        ldapContextSource.setCacheEnvironmentProperties(true);
        ldapContextSource.setAnonymousReadOnly(false);
        ldapContextSource.setPooled(true);
        ldapContextSource.afterPropertiesSet();

        String searchFilter="(sAMAccountName={0})";
        FilterBasedLdapUserSearch userSearch=new FilterBasedLdapUserSearch(adDomain, searchFilter,ldapContextSource);
        userSearch.setSearchSubtree(true);

        BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
        bindAuthenticator.setUserSearch(userSearch);
        bindAuthenticator.afterPropertiesSet();

        LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(bindAuthenticator);

        if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) {
            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
            final UserDetails principal = new User(userName, userPassword, grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths);

            result = ldapAuthenticationProvider.authenticate(finalAuthentication);
        }

    } catch (BadCredentialsException bce) {
        logFile.println("ERROR: LDAP Authentication Failed. Please verify values for ranger.admin.auth.sampleuser and " +
                "ranger.admin.auth.samplepassword\n");
    } catch (Exception e) {
        logFile.println("ERROR: LDAP Authentication Failed: " + e);
    }
    return result;
}
 
Example #17
Source File: UserDetailsServiceImpl.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
@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 #18
Source File: CustomIpAuthenticationProvider.java    From tutorials with 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 #19
Source File: PurRepositoryIT.java    From pentaho-kettle with 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 #20
Source File: JWTFilterTest.java    From jhipster-registry with 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 #21
Source File: UserDetailsServiceImpl.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
@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
Source File: KiteUserDetailsService.java    From spring-cloud-study with 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 #23
Source File: UserDetailsServiceImpl.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
@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 #24
Source File: SecurityUserDetailsServiceImpl.java    From ywh-frame with GNU General Public License v3.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    SysUserEntity sysUserEntity = sysUserDao.selectByUserName(username);
    if(sysUserEntity != null){
        // stream java8的新特性,Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。
        // 参考http://www.runoob.com/java/java8-streams.html
        List<SimpleGrantedAuthority> collect = sysUserEntity.getRoles().stream().map(SysRoleEntity::getSysRoleName)
                .map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return new SecurityUserDetails(sysUserEntity.getSysUserPassword(),sysUserEntity.getSysUserName(),sysUserEntity.getSysUserState(),collect);
    }
    throw MyExceptionUtil.mxe(String.format("'%s'.这个用户不存在", username));
}
 
Example #25
Source File: SecurityUtilsUnitTest.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnonymousIsNotAuthenticated() {
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    Collection<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
    securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities));
    SecurityContextHolder.setContext(securityContext);
    boolean isAuthenticated = SecurityUtils.isAuthenticated();
    assertThat(isAuthenticated).isFalse();
}
 
Example #26
Source File: UserDetailServiceImpl.java    From code with Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    List<GrantedAuthority> authorityList=new ArrayList<GrantedAuthority>();
    authorityList.add(new SimpleGrantedAuthority("ROLE_USER"));

    return new User(username,"",authorityList);
}
 
Example #27
Source File: StaffDetails.java    From HIS with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    //返回当前用户的权限
    return permissionList.stream()
            .filter(permission -> permission.getValue()!=null)
            .map(permission ->new SimpleGrantedAuthority(permission.getValue()))
            .collect(Collectors.toList());
}
 
Example #28
Source File: CustomWebSecurityConfig.java    From tutorials with MIT License 5 votes vote down vote up
public ReactiveAuthenticationManager employeesAuthenticationManager() {
    return authentication -> employee(authentication)
      .switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication
        .getPrincipal()
        .toString())))
      .map(
        b -> new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
          authentication.getCredentials(),
          Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
        )
      );
}
 
Example #29
Source File: UacUserServiceImpl.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<GrantedAuthority> loadUserAuthorities(Long userId) {

	List<UacAction> ownAuthList = uacActionService.getOwnActionListByUserId(userId);
	List<GrantedAuthority> authList = Lists.newArrayList();
	for (UacAction action : ownAuthList) {
		GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(action.getUrl());
		authList.add(grantedAuthority);
	}
	return authList;
}
 
Example #30
Source File: User.java    From webFluxTemplate with MIT License 5 votes vote down vote up
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    List<GrantedAuthority> authorities = new ArrayList(this.roles.size());
    for(String role : this.roles) {
        authorities.add(new SimpleGrantedAuthority(role));
    }

    return authorities;
}