org.springframework.security.authentication.AuthenticationCredentialsNotFoundException#org.springframework.security.core.authority.SimpleGrantedAuthority源码实例Demo

下面列出了org.springframework.security.authentication.AuthenticationCredentialsNotFoundException#org.springframework.security.core.authority.SimpleGrantedAuthority 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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;
}
 
@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);
}
 
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
  Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
  SimpleGrantedAuthority authority = new SimpleGrantedAuthority(this.role);
  authorities.add(authority);
  return authorities;
}
 
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);
}
 
源代码5 项目: kafka-webview   文件: CustomUserDetails.java
/**
 * 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);
}
 
源代码6 项目: alf.io   文件: TicketReservationManagerTest.java
@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));
}
 
源代码7 项目: blog-sample   文件: DefaultUserDetailsService.java
@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);
}
 
源代码8 项目: molgenis   文件: CachedRoleHierarchyImplTest.java
@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)));
}
 
@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!");
	}

}
 
源代码10 项目: expper   文件: UserDetailsService.java
@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"));
}
 
源代码11 项目: jhipster-registry   文件: JWTFilterTest.java
@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);
}
 
@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);
}
 
源代码13 项目: JavaSpringMvcBlog   文件: UserServiceTest.java
@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);
}
 
源代码14 项目: kylin   文件: KylinUserGroupService.java
@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;
}
 
源代码15 项目: alf.io   文件: OpenIdCallbackLoginFilter.java
@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);
}
 
源代码16 项目: tutorials   文件: CustomIpAuthenticationProvider.java
@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");
    }
}
 
源代码17 项目: pentaho-kettle   文件: PurRepositoryIT.java
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();
}
 
@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);
}
 
@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;
    }
}
 
源代码20 项目: OpenLRW   文件: AjaxAuthenticationProvider.java
@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());
}
 
@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);
}
 
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);
}
 
源代码23 项目: sctalk   文件: JwtUserDetailsServiceImpl.java
@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()));
    }
}
 
@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.");
}
 
源代码25 项目: data-highway   文件: OnrampAuthorisationTest.java
@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);
}
 
源代码26 项目: server   文件: UserDto.java
@JsonIgnore
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return roles.stream()
            .map(role -> new SimpleGrantedAuthority(role.getName()))
            .collect(Collectors.toList());
}
 
@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());
}
 
源代码28 项目: cubeai   文件: DomainUserDetailsService.java
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);
}
 
源代码29 项目: platform   文件: SecurityUserDetailsService.java
@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);
}
 
@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;
}