org.springframework.security.core.userdetails.User Java Examples

The following examples show how to use org.springframework.security.core.userdetails.User. 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: CustomAuthenticationProvider.java    From Building-Web-Apps-with-Spring-5-and-Angular with MIT License 7 votes vote down vote up
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
	final String username = authentication.getName();
	final String password = authentication.getCredentials().toString();

	User user = null;
	try {
		user = userService.doesUserExist(username);
	} catch (UserNotFoundException e) {
	}

	if (user == null || !user.getEmail().equalsIgnoreCase(username)) {
		throw new BadCredentialsException("Username not found.");
	}

	if (!password.equals(user.getPassword())) {
		throw new BadCredentialsException("Wrong password.");
	}
	List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
	if(user.getRole() == 1) {
		authorities.add(new SimpleGrantedAuthority("ROLE_DOCTOR"));
	} else {
		authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
	}		
       final UserDetails principal = new org.springframework.security.core.userdetails.User(username, password, authorities);        
	return new UsernamePasswordAuthenticationToken(principal, password, authorities);
}
 
Example #2
Source File: TokenProvider.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
Authentication getAuthentication(String token) {
    Claims claims = Jwts.parser()
            .setSigningKey(key)
            .parseClaimsJws(token)
            .getBody();

    // fix bug: 当前用户如果没有任何权限时,在输入用户名后,刷新验证码会抛IllegalArgumentException
    Object authoritiesStr = claims.get(AUTHORITIES_KEY);
    Collection<? extends GrantedAuthority> authorities =
            ObjectUtil.isNotEmpty(authoritiesStr) ?
                    Arrays.stream(authoritiesStr.toString().split(","))
                            .map(SimpleGrantedAuthority::new)
                            .collect(Collectors.toList()) : Collections.emptyList();

    User principal = new User(claims.getSubject(), "", authorities);

    return new UsernamePasswordAuthenticationToken(principal, token, authorities);
}
 
Example #3
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
/**
     * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
     * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
     * application Spring Security usernames are email addresses).
     */
    @Override
    public CalendarUser getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication == null) {
            return null;
        }

        User user = (User)authentication.getPrincipal();
        String email = user.getUsername();
//        String email = user.getEmail();
        if (email == null) {
            return null;
        }
        CalendarUser result = calendarService.findUserByEmail(email);
        if (result == null) {
            throw new IllegalStateException(
                    "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
        }
        return result;
    }
 
Example #4
Source File: UserConfig.java    From base-admin with MIT License 6 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    //查询用户
    SysUserVo sysUserVo = sysUserService.findByLoginName(username).getData();
    //查询权限
    List<SysUserAuthorityVo> sysUserAuthorityVoList = sysUserAuthorityService.findByUserId(sysUserVo.getUserId()).getData();
    StringBuilder authorityList = new StringBuilder();
    for (int i = 0; i < sysUserAuthorityVoList.size(); i++) {
        SysUserAuthorityVo sysUserAuthorityVo = sysUserAuthorityVoList.get(i);
        authorityList.append(sysUserAuthorityVo.getSysAuthority().getAuthorityName());
        if (i != sysUserAuthorityVoList.size() - 1) {
            authorityList.append(",");
        }
    }

    //查无此用户
    if(StringUtils.isEmpty(sysUserVo.getUserId())){
        sysUserVo.setLoginName("查无此用户");
        sysUserVo.setPassword("查无此用户");
    }

    // 封装用户信息,并返回。参数分别是:用户名,密码,用户权限
    return new User(sysUserVo.getLoginName(), sysUserVo.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(authorityList.toString()));
}
 
Example #5
Source File: CustomUserDetailsService.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.selectByName(username);

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

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

    // 返回UserDetails实现类
    return new User(user.getName(), user.getPassword(), authorities);
}
 
Example #6
Source File: UserInfoService.java    From ChengFeng1.5 with MIT License 6 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    if (StringUtils.isBlank(username)){
        throw new UserAuthenticationException("用户名或密码不正确");
    }


        com.beautifulsoup.chengfeng.pojo.User user ;
            user= userMapper.selectByNicknameAndPassword(username);
        if(null==user){
            throw new UserAuthenticationException("用户不存在,登陆失败");
        }

        return  User.builder().username(user.getNickname())
                .password(user.getCryptPassword().getCryptPassword()).authorities("/admin").build();
}
 
Example #7
Source File: LoginSuccessHandler.java    From secrets-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Since we are using multiple {@link AuthenticationProvider}s, make sure to convert the
 * authentication principal to proper {@link OneOpsUser} type.
 *
 * @param req http request.
 * @param res http response.
 * @param authentication authentication object
 * @throws IOException
 * @throws ServletException
 */
@Override
public void onAuthenticationSuccess(
    HttpServletRequest req, HttpServletResponse res, Authentication authentication)
    throws IOException, ServletException {
  User principal = (User) authentication.getPrincipal();
  OneOpsUser user;
  if (principal instanceof OneOpsUser) {
    user = (OneOpsUser) principal;
  } else {
    user = getOneOpsUser(principal);
  }

  String token = tokenService.generateToken(user);
  auditLog.log(new Event(GENERATE_TOKEN, user.getUsername(), user.getDomain().getType(), "N/A"));

  LoginResponse loginResponse =
      new LoginResponse(token, tokenService.getTokenType(), tokenService.getExpiresInSec());
  res.setStatus(HttpStatus.CREATED.value());
  res.setContentType(APPLICATION_JSON_VALUE);
  mapper.writeValue(res.getWriter(), loginResponse);

  clearAuthenticationAttributes(req);
}
 
Example #8
Source File: KafkaServiceImpl.java    From metron with Apache License 2.0 6 votes vote down vote up
@Override
public boolean addACLToCurrentUser(String name){
  if(listTopics().contains(name)) {
    String zkServers = environment.getProperty(MetronRestConstants.ZK_URL_SPRING_PROPERTY);
    User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String user = principal.getUsername();
    List<String> cmd = new ArrayList<>();
    cmd.add("--add");
    cmd.add("--allow-principal");
    cmd.add("User:" + user);
    cmd.add("--topic");
    cmd.add(name);
    cmd.add("--authorizer-properties");
    cmd.add("zookeeper.connect=" + String.join(",", zkServers));
    AclCommand.main(cmd.toArray(new String[cmd.size()]));
  } else {
    return false;
  }
  return true;
}
 
Example #9
Source File: JwtAuthenticationFilter.java    From jwt-security with MIT License 6 votes vote down vote up
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                        FilterChain filterChain, Authentication authentication) {
    var user = ((User) authentication.getPrincipal());

    var roles = user.getAuthorities()
        .stream()
        .map(GrantedAuthority::getAuthority)
        .collect(Collectors.toList());

    var signingKey = SecurityConstants.JWT_SECRET.getBytes();

    var token = Jwts.builder()
        .signWith(Keys.hmacShaKeyFor(signingKey), SignatureAlgorithm.HS512)
        .setHeaderParam("typ", SecurityConstants.TOKEN_TYPE)
        .setIssuer(SecurityConstants.TOKEN_ISSUER)
        .setAudience(SecurityConstants.TOKEN_AUDIENCE)
        .setSubject(user.getUsername())
        .setExpiration(new Date(System.currentTimeMillis() + 864000000))
        .claim("rol", roles)
        .compact();

    response.addHeader(SecurityConstants.TOKEN_HEADER, SecurityConstants.TOKEN_PREFIX + token);
}
 
Example #10
Source File: CurrentUserHandlerMethodArgumentResolverTest.java    From spring-boot-security-saml-sample with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolveArgument() throws Exception {
    // given
    ModelAndViewContainer mavContainer = mock(ModelAndViewContainer.class);
    WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
    NativeWebRequest webRequest = mock(NativeWebRequest.class);
    User stubUser = new User(USER_NAME, "", Collections.emptyList());
    Principal stubPrincipal = new UsernamePasswordAuthenticationToken(stubUser, null);
    when(webRequest.getUserPrincipal()).thenReturn(stubPrincipal);

    // when/then
    assertEquals(stubUser,
            resolver.resolveArgument(validParam, mavContainer, webRequest,binderFactory));
    assertEquals(WebArgumentResolver.UNRESOLVED,
            resolver.resolveArgument(notAnnotatedParam, mavContainer, webRequest,binderFactory));
    assertEquals(WebArgumentResolver.UNRESOLVED,
            resolver.resolveArgument(wrongTypeParam, mavContainer, webRequest,binderFactory));
}
 
Example #11
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 #12
Source File: AccountResourceTest.java    From jhipster-microservices-example with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetExistingAccount() throws Exception {

    Authentication authentication = Mockito.mock(Authentication.class);
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);

    Set<GrantedAuthority> authorities = new HashSet<>();
    authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ADMIN));

    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    SecurityContextHolder.setContext(securityContext);
    Mockito.when(authentication.getPrincipal()).thenReturn(new User("user", "pass", authorities));

    mock.perform(get("/api/account")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.login").value("user"))
        .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
 
Example #13
Source File: UserDetailsServiceImpl.java    From spring-boot-cookbook with Apache License 2.0 6 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    CustomUserDetails userDetails = userRepository.getUser(username);
    if (userDetails == null) {
        LOGGER.warn("{} not exist.", username);
        throw new UsernameNotFoundException(username + " not exists");
    }

    return new User(
            userDetails.getUsername(),
            userDetails.getPassword(),
            userDetails.getAccountEnabled(),
            userDetails.generateAccountNonExpired(),
            userDetails.generateCredentialsNonExpired(),
            !userDetails.getAccountLocked(),
            userDetails.generateAuthorities());

}
 
Example #14
Source File: SecurityReactiveApplication.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Bean
public ReactiveUserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
    UserDetails admin = User
	      .withUsername("admin")
	      .password(passwordEncoder.encode("admin12345678"))
	      .roles("ADMIN", "MEMBER")
	      .build();

    UserDetails caterpillar = User
	      .withUsername("caterpillar")
	      .password(passwordEncoder.encode("12345678"))
	      .roles("MEMBER")
	      .build();
    
    return new MapReactiveUserDetailsService(admin, caterpillar);
}
 
Example #15
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 #16
Source File: SpringSecurityUserContext.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
/**
     * Get the {@link CalendarUser} by obtaining the currently logged in Spring Security user's
     * {@link Authentication#getName()} and using that to find the {@link CalendarUser} by email address (since for our
     * application Spring Security usernames are email addresses).
     */
    @Override
    public CalendarUser getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        if (authentication == null) {
            return null;
        }

        User user = (User)authentication.getPrincipal();
        String email = user.getUsername();
//        String email = user.getEmail();
        if (email == null) {
            return null;
        }
        CalendarUser result = calendarService.findUserByEmail(email);
        if (result == null) {
            throw new IllegalStateException(
                    "Spring Security is not in synch with CalendarUsers. Could not find user with email " + email);
        }
        return result;
    }
 
Example #17
Source File: JwtAuthenticationSuccessHandlerImpl.java    From quartz-manager with Apache License 2.0 6 votes vote down vote up
@Override
public void onLoginSuccess(Authentication authentication, HttpServletResponse response) throws IOException {
  log.debug("Login successed, generating jwtToken...");

  User user = (User) authentication.getPrincipal();
  String jwtToken = jwtTokenHelper.generateToken(user.getUsername());

  if(jwtSecurityProps.getCookieStrategy().isEnabled()) {
    Cookie authCookie = new Cookie(jwtSecurityProps.getCookieStrategy().getCookie(), jwtToken);
    authCookie.setHttpOnly(true);
    authCookie.setMaxAge((int) jwtSecurityProps.getExpirationInSec());
    authCookie.setPath(contextPath);
    response.addCookie(authCookie);
    log.debug("Set jwtToken into the cookie {}", jwtSecurityProps.getCookieStrategy().getCookie());
  }

  if(jwtSecurityProps.getHeaderStrategy().isEnabled()) {
    jwtTokenHelper.setHeader(response, jwtToken);
    log.debug("Set jwtToken into the response header {}", jwtSecurityProps.getHeaderStrategy().getHeader());
  }

  UserTokenState userTokenState = new UserTokenState(jwtToken, jwtSecurityProps.getExpirationInSec());
  String jwtResponse = objectMapper.writeValueAsString(userTokenState);
  response.setContentType("application/json");
  response.getWriter().write(jwtResponse);
}
 
Example #18
Source File: OauthClientApplication.java    From Spring with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/execute")
public String execute(Principal principal) throws URISyntaxException {
    final User user = (User) ((Authentication) principal).getPrincipal();
    final URI uri = new URI("http://localhost:7070/resource/endpoint");

    final RequestEntity<String> requestEntity = new RequestEntity<>(HttpMethod.GET, uri);
    final AccessTokenRequest accessTokenRequest = oAuth2RestTemplate.getOAuth2ClientContext().getAccessTokenRequest();
    accessTokenRequest.set("username", user.getUsername());
    accessTokenRequest.set("password", user.getPassword());

    return oAuth2RestTemplate.exchange(requestEntity, String.class).getBody();
}
 
Example #19
Source File: GossipApplication.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Bean
public ReactiveUserDetailsService userDetailsService(AccountDAO accountDAO, Scheduler scheduler) {
    return username -> {
    	return Mono.defer(() -> {
    		return Mono.justOrEmpty(accountDAO.accountByUsername(username))
    		    .map(acct -> {
    		    	return User.withUsername(username)
      		           .password(acct.getPassword())
      		           .roles("MEMBER")
      		           .build();
    		    });
    		    
    	}).subscribeOn(scheduler);
    };
}
 
Example #20
Source File: KylinUserService.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public KylinUserService(List<User> users) throws IOException {
    pwdEncoder = new BCryptPasswordEncoder();
    synchronized (KylinUserService.class) {
        KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv();
        if (!StringUtils.equals("testing", kylinConfig.getSecurityProfile())) {
            return;
        }
        List<ManagedUser> all = listUsers();
        configUsers = users;
        // old security.xml config user pwd sync to user metadata
        if (!configUsers.isEmpty()) {
            for (User cuser : configUsers) {
                try {
                    String username = cuser.getUsername();
                    ManagedUser userDetail = (ManagedUser) loadUserByUsername(username);
                    if (userDetail != null && new KylinVersion(userDetail.getVersion()).major < KylinVersion
                            .getCurrentVersion().major) {
                        updateUser(new ManagedUser(cuser.getUsername(), cuser.getPassword(), false,
                                cuser.getAuthorities()));
                    }
                } catch (UsernameNotFoundException e) {
                    // add new security user in security.xml if it is not in metadata
                    createUser(new ManagedUser(cuser.getUsername(), cuser.getPassword(), false,
                            cuser.getAuthorities()));
                }
            }
        }
        // add default user info in metadata
        if (all.isEmpty() && configUsers.isEmpty()) {
            createUser(new ManagedUser(ADMIN, pwdEncoder.encode(ADMIN_DEFAULT), true, Constant.ROLE_ADMIN,
                    Constant.GROUP_ALL_USERS));
            createUser(new ManagedUser(ANALYST, pwdEncoder.encode(ANALYST), true, Constant.GROUP_ALL_USERS));
            createUser(new ManagedUser(MODELER, pwdEncoder.encode(MODELER), true, Constant.GROUP_ALL_USERS));
        }
    }

}
 
Example #21
Source File: WebSecurityConfig.java    From spring-graalvm-native with Apache License 2.0 5 votes vote down vote up
@Bean
@Override
public UserDetailsService userDetailsService() {
	UserDetails user =
		 User.withDefaultPasswordEncoder()
			.username("user")
			.password("password")
			.roles("USER")
			.build();

	return new InMemoryUserDetailsManager(user);
}
 
Example #22
Source File: AccountResource.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
/**
 * GET  /account : get the current user.
 *
 * @return the ResponseEntity with status 200 (OK) and the current user in body, or status 500 (Internal Server
 * Error) if the user couldn't be returned
 */
@GetMapping("/account")
public ResponseEntity<UserVM> getAccount() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    try {
        String login;
        if (authentication.getPrincipal() instanceof User) {
            User user = (User) authentication.getPrincipal();
            login = user.getUsername();
            log.debug("The username `{}` has been found using JWT", login);
        } else if (authentication.getPrincipal() instanceof String) {
            login = (String) authentication.getPrincipal();
        } else if (authentication instanceof OAuth2AuthenticationToken) {
            login = ((OAuth2AuthenticationToken) authentication).getPrincipal().getName();
            log.debug("The username `{}` has been found using OpenID Connect", login);
        } else {
            log.debug("The username could not be found");
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        UserVM userVM = new UserVM(login,
            authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority).collect(Collectors.toSet()));
        return new ResponseEntity<>(userVM, HttpStatus.OK);
    } catch (NullPointerException | ClassCastException e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
 
Example #23
Source File: AuthServerConfig.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
	super.configure(endpoints);
	endpoints.authenticationManager(authenticationManagerBean);
	endpoints.tokenStore(tokenStore());
	endpoints.tokenEnhancer(new TokenEnhancer() {

		@Override
		public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
			if (authentication.getPrincipal() instanceof User) {
				final User user = (User) authentication.getPrincipal();

				final Set<String> scopes = new HashSet<String>();
				for (GrantedAuthority authority : user.getAuthorities()) {
					final String role = authority.getAuthority();

					if (role.startsWith("ROLE_")) {
						scopes.add(role.substring(5).toLowerCase());
					}
					else {
						scopes.add(role.toLowerCase());
					}
				}
				((DefaultOAuth2AccessToken) accessToken).setScope(scopes);

			}
			return accessToken;
		}
	});
}
 
Example #24
Source File: BasicApplication.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    return this.accountRepository.findByUsername(username)
            .map(account -> new User(account.getUsername(),
                    account.getPassword(),
                    account.isActive(), account.isActive(), account.isActive(), account.isActive(),
                    AuthorityUtils.createAuthorityList("ROLE_ADMIN", "ROLE_USER")
            ))
            .orElseThrow(() -> new UsernameNotFoundException("couldn't find " + username + "!"));
}
 
Example #25
Source File: FastCloudUserDetailsService.java    From fast-cloud-examples with Apache License 2.0 5 votes vote down vote up
private UserDetails buildUser(String userId) {
    // 根据用户名查找用户信息
    //根据查找到的用户信息判断用户是否被冻结
    //TODO
    FastCloudUser mermaidUser = new FastCloudUser();
    log.info("数据库密码是:" + mermaidUser.getPassword());
    return new User(mermaidUser.getUsername(),passwordEncoder.encode(mermaidUser.getPassword()),mermaidUser.getAuthorities());
}
 
Example #26
Source File: AppConfig.java    From smartling-keycloak-extras with Apache License 2.0 5 votes vote down vote up
@Bean
UserDetailsService userDetailsService() {
    Set<UserDetails> users = new HashSet<>();
    User user = new User(KNOWN_EMAIL, "does_not_matter", Arrays.asList(new SimpleGrantedAuthority("user")));
    users.add(user);
    return new InMemoryUserDetailsManager(Collections.unmodifiableCollection(users));
}
 
Example #27
Source File: DomainUserDetailsService.java    From cloud-project with Apache License 2.0 5 votes vote down vote up
/**
 * 根据用户名查找账户信息并返回用户信息实体
 * @param username 用户名
 * @return 用于身份认证的 UserDetails 用户信息实体
 * @throws UsernameNotFoundException
 */
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Account account = accountRepository.findByUserName(username);
    if (account!=null){
        return new User(account.getUserName(),account.getPassWord(), AuthorityUtils.createAuthorityList(account.getRoles()));
    }else {
        throw  new UsernameNotFoundException("用户["+username+"]不存在");
    }
}
 
Example #28
Source File: SysUserServiceImpl.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    SysUser sysUser = sysUserRepository.findFirstByUsername(username)
        .orElseThrow(() -> new UsernameNotFoundException("User not found!"));
    List<SimpleGrantedAuthority> roles = sysUser.getRoles().stream()
        .map(sysRole -> new SimpleGrantedAuthority(sysRole.getName()))
        .collect(Collectors.toList());
    // 在这里手动构建 UserDetails 的默认实现
    return new User(sysUser.getUsername(), sysUser.getPassword(), roles);
}
 
Example #29
Source File: SecurityConfig.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Bean
public MapReactiveUserDetailsService userDetailsService() {
    UserDetails user = User.builder().
            username(Objects.requireNonNull(env.getProperty("anonymousUser"))).
            password("{noop}" + env.getProperty("anonymousKey")).
            roles(IdRepoEntitlement.ANONYMOUS).
            build();
    return new MapReactiveUserDetailsService(user);
}
 
Example #30
Source File: SecurityConfig.java    From spring-5-examples with MIT License 5 votes vote down vote up
@Bean MapReactiveUserDetailsService userDetailsService() {
  return new MapReactiveUserDetailsService(
      User.withUsername("max")
          .password("max")
          .roles("USER")
          .build()
  );
}