Java Code Examples for org.springframework.security.core.userdetails.UserDetails
The following examples show how to use
org.springframework.security.core.userdetails.UserDetails. 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
Source Project: Spring-Security-Third-Edition Source File: UserDetailsServiceImpl.java License: MIT License | 6 votes |
@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 2
Source Project: DAFramework Source File: SysUserDetailsServiceTest.java License: MIT License | 6 votes |
@Test public void testLoadUserByUsername() { //test found user String username = "watano"; UserDetails ud = userDetailsService.loadUserByUsername(username); notNull(ud, "UserDetails is not null"); notNull(ud.getUsername(), "Username is not null"); isTrue(username.equals(ud.getUsername()), "Username is not " + username); notNull(ud.getPassword(), "Password is not null"); //UsernameNotFoundException try { username = "watano1"; ud = userDetailsService.loadUserByUsername(username); fail("UserDetails is not null"); } catch (UsernameNotFoundException e) {} }
Example 3
Source Project: Spring-Boot-2-Fundamentals Source File: HomePageController.java License: MIT License | 6 votes |
@GetMapping("/") public String homePage(Model model) { // Fill in authorities for the model val authentication = SecurityContextHolder.getContext().getAuthentication(); model.addAttribute("authorities", authentication.getAuthorities()); // Fill in username (from principal) for the model Object principal = authentication.getPrincipal(); String username = principal instanceof UserDetails ? ((UserDetails) principal).getUsername() : principal.toString(); model.addAttribute("username", username); // Fill in the messages for the model List<ShortMessage> shortMessages = sms.findAll(); model.addAttribute("shortMessages", shortMessages); return "index"; }
Example 4
Source Project: java-microservices-examples Source File: SecurityUtils.java License: Apache License 2.0 | 6 votes |
/** * Get the login of the current user. * * @return the login of the current user. */ public static Optional<String> getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); return Optional.ofNullable(securityContext.getAuthentication()) .map(authentication -> { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); return springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof DefaultOidcUser) { Map<String, Object> attributes = ((DefaultOidcUser) authentication.getPrincipal()).getAttributes(); if (attributes.containsKey("preferred_username")) { return (String) attributes.get("preferred_username"); } } else if (authentication.getPrincipal() instanceof String) { return (String) authentication.getPrincipal(); } return null; }); }
Example 5
Source Project: Spring-Security-Third-Edition Source File: UserDetailsServiceImpl.java License: MIT License | 6 votes |
@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 6
Source Project: Spring-Security-Third-Edition Source File: UserDetailsServiceImpl.java License: MIT License | 6 votes |
@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 7
Source Project: ExamStack Source File: UserDetailsServiceImpl2.java License: GNU General Public License v2.0 | 6 votes |
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // TODO Auto-generated method stub User user = userMapper.getUserByName(username); if(user == null) throw new UsernameNotFoundException("user not found!"); //roles=角色代码 List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()); userInfo = new UserInfo(username,"",user.isEnabled(),true,true,true,authorities); userInfo.setUserid(user.getUserId()); userInfo.setRolesName(user.getRoles()); userInfo.setTrueName(user.getTrueName()); userInfo.setEmail(user.getEmail()); userInfo.setPhoneNum(user.getPhoneNum()); userInfo.setNationalId(user.getNationalId()); userInfo.setDepId(user.getDepId()); return userInfo; }
Example 8
Source Project: SpringAll Source File: UserDetailService.java License: MIT License | 6 votes |
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 模拟一个用户,替代数据库获取逻辑 MyUser user = new MyUser(); user.setUserName(username); user.setPassword(this.passwordEncoder.encode("123456")); // 输出加密后的密码 System.out.println(user.getPassword()); List<GrantedAuthority> authorities = new ArrayList<>(); if (StringUtils.equalsIgnoreCase("mrbird", username)) { authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin"); } else { authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("test"); } return new User(username, user.getPassword(), user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(), user.isAccountNonLocked(), authorities); }
Example 9
Source Project: Building-Web-Apps-with-Spring-5-and-Angular Source File: CustomAuthenticationProvider.java License: MIT License | 6 votes |
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 10
Source Project: syhthems-platform Source File: UserUtils.java License: MIT License | 6 votes |
/** * 从 Spring Security Context中获取 username 再获取 CustomUserDetails,若找不到则返回 null * * @return */ public CustomUserDetails getCustomUserDetailsFromSecurityContextHolderWithUsername() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null || authentication instanceof AnonymousAuthenticationToken) { return null; } String username; if (authentication instanceof JwtAuthenticationToken) { username = ((JwtAuthenticationToken) authentication).getTokenAttributes().get("user_name").toString(); } else { username = authentication.getName(); } try { UserDetails userDetails = userDetailsService.loadUserByUsername(username); if (userDetails instanceof CustomUserDetails) { return ((CustomUserDetails) userDetails).erasePassword(); } return null; } catch (IllegalArgumentException e) { return null; } }
Example 11
Source Project: Spring-Boot-Blog-REST-API Source File: JwtAuthenticationFilter.java License: GNU Affero General Public License v3.0 | 6 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try{ String jwt = getJwtFromRequest(request); if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)){ Long userId = tokenProvider.getUserIdFromJWT(jwt); UserDetails userDetails = customUserDetailsService.loadUserById(userId); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } } catch (Exception ex){ LOGGER.error("Could not set user authentication in security context", ex); } filterChain.doFilter(request, response); }
Example 12
Source Project: spring-boot-cookbook Source File: UserDetailsServiceImpl.java License: Apache License 2.0 | 6 votes |
@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 13
Source Project: tutorials Source File: WebFluxSecurityConfig.java License: MIT License | 6 votes |
@Bean public MapReactiveUserDetailsService userDetailsService() { UserDetails admin = User .withUsername("admin") .password(encoder().encode("password")) .roles("ADMIN") .build(); UserDetails user = User .withUsername("user") .password(encoder().encode("password")) .roles("USER") .build(); return new MapReactiveUserDetailsService(admin, user); }
Example 14
Source Project: kylin-on-parquet-v2 Source File: UserServiceTest.java License: Apache License 2.0 | 6 votes |
@Test public void testBasics() throws IOException { userService.deleteUser("MODELER"); Assert.assertTrue(!userService.userExists("MODELER")); List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); authorities.add(new SimpleGrantedAuthority(Constant.ROLE_ADMIN)); ManagedUser user = new ManagedUser("MODELER", "PWD", false, authorities); userService.createUser(user); Assert.assertTrue(userService.userExists("MODELER")); UserDetails ud = userService.loadUserByUsername("MODELER"); Assert.assertEquals("MODELER", ud.getUsername()); Assert.assertEquals("PWD", ud.getPassword()); Assert.assertEquals(Constant.ROLE_ADMIN, ud.getAuthorities().iterator().next().getAuthority()); Assert.assertEquals(2, ud.getAuthorities().size()); }
Example 15
Source Project: MovieApp Source File: JwtAuthenticationFilter.java License: MIT License | 6 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { // Get jwt token String jwt = getJwtFromRequest(request); // Validate the token if (StringUtils.hasText(jwt) && tokenValidator.validateToken(jwt)) { // Build userDetails UserDetails userDetails = tokenValidator.getUserPrincipalFromJWT(jwt); // Crate auth object UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); // Authenticate the user SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (Exception ex) { logger.error("Could not set user authentication in security context", ex); // In case of failure. Make sure it's clear; so guarantee user won't be authenticated. SecurityContextHolder.clearContext(); } filterChain.doFilter(request, response); }
Example 16
Source Project: web-qq Source File: User.java License: Apache License 2.0 | 6 votes |
@Override public boolean equals(Object obj) { if(obj == null){ return false; } if(obj == this){ return true; } if(obj instanceof User){ if(obj instanceof UserDetails){ UserDetails userDetails = (UserDetails)obj; if(this.getUsername().equals(userDetails.getUsername())){ return true; } }else{ User user = (User)obj; if(this.getUsername().equals(user.getUsername())){ return true; } } } return false; }
Example 17
Source Project: artifact-listener Source File: Pac4jAuthenticationSuccessHandler.java License: Apache License 2.0 | 6 votes |
private ClientAuthenticationToken getAuthenticationTokenWithUserDetails(Authentication authentication) { Collection<? extends GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); ClientAuthenticationToken token = getAuthenticationToken(authentication); if (token != null) { UserDetails userDetails = pac4jUserDetailsService.loadUserDetails(token); if (userDetails != null) { this.userDetailsChecker.check(userDetails); authorities = userDetails.getAuthorities(); } ClientAuthenticationToken result = new ClientAuthenticationToken((Credentials) token.getCredentials(), token.getClientName(), token.getUserProfile(), authorities); result.setDetails(userDetails); return result; } return null; }
Example 18
Source Project: syhthems-platform Source File: CustomDeviceUserDetailsServiceImpl.java License: MIT License | 6 votes |
@Override @Cacheable(cacheNames = "DeviceUserDetails", unless = "#username == null", cacheManager = "JDKCacheManager") public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Device device; try { device = deviceService.selectByPrimaryKey(Long.valueOf(username)); } catch (NumberFormatException e) { throw new UsernameNotFoundException("用户名必须为设备ID"); } if (device == null) { throw new UsernameNotFoundException("该设备不存在"); } if (device.getProductId() == null) { throw new ServiceException("设备没有绑定产品"); } Product product = productService.selectByPrimaryKey(device.getProductId()); if (product == null) { throw new ServiceException("设备没有绑定产品"); } // List<DataStream> dataStreams = dataStreamService.selectByDeviceId(device.getDeviceId()); List<DataStream> dataStreams = dataStreamService.selectByProductId(product.getProductId()); return new CustomDeviceUserDetails(username, device.getDeviceSecret(), Collections.singletonList(new SimpleGrantedAuthority("ROLE_DEVICE")), product, device, dataStreams); }
Example 19
Source Project: java-tutorial Source File: UserAuthenticationProvider.java License: MIT License | 6 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { // 获取认证的用户名 & 密码 String name = authentication.getName(); String password = authentication.getCredentials().toString(); UserDetails userDetails = authUserService.loadUserByUsername(name); //认证逻辑 if (null != userDetails) { //检查密码是否匹配 if (bCryptPasswordEncoder.matches(password, userDetails.getPassword())) { // 这里设置权限和角色 // 生成令牌 这里令牌里面存入了:name,password,authorities, 当然你也可以放其他内容 Authentication auth = new UsernamePasswordAuthenticationToken(name, password, emptyList()); return auth; } else { throw new BizException("密码错误"); } } else { throw new BizException("用户不存在"); } }
Example 20
Source Project: spring-security-mybatis-demo Source File: AuthenticationController.java License: Apache License 2.0 | 6 votes |
@RequestMapping(value = "${jwt.route.authentication.path}/personal", method = RequestMethod.POST) public ResponseEntity<?> createPersonalAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException { authenticationRequest.setUsername(authenticationRequest.getPhone()); // Perform the security Authentication authentication = null; try { authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( authenticationRequest.getUsername(), authenticationRequest.getPassword() ) ); } catch (AuthenticationException e) { System.out.println(e.getMessage()); } SecurityContextHolder.getContext().setAuthentication(authentication); // Reload password post-security so we can generate token final UserDetails userDetails = userDetailsService.loadUserByPhone(authenticationRequest.getPhone()); final String token = jwtTokenUtil.generateToken(userDetails, device); // Return the token return ResponseEntity.ok(new JwtAuthenticationResponse(token)); }
Example 21
Source Project: cloud-service Source File: UserDetailServiceImpl.java License: MIT License | 6 votes |
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 为了支持多类型登录,这里username后面拼装上登录类型,如username|type String[] params = username.split("\\|"); username = params[0];// 真正的用户名 LoginAppUser loginAppUser = userClient.findByUsername(username); if (loginAppUser == null) { throw new AuthenticationCredentialsNotFoundException("用户不存在"); } else if (!loginAppUser.isEnabled()) { throw new DisabledException("用户已作废"); } if (params.length > 1) { // 登录类型 CredentialType credentialType = CredentialType.valueOf(params[1]); if (CredentialType.PHONE == credentialType) {// 短信登录 handlerPhoneSmsLogin(loginAppUser, params); } else if (CredentialType.WECHAT_OPENID == credentialType) {// 微信登陆 handlerWechatLogin(loginAppUser, params); } } return loginAppUser; }
Example 22
Source Project: hawkbit Source File: DefaultRolloutApprovalStrategy.java License: Eclipse Public License 1.0 | 5 votes |
private UserDetails getActor(Rollout rollout) { final String actor = rollout.getLastModifiedBy() != null ? rollout.getLastModifiedBy() : rollout.getCreatedBy(); return systemSecurityContext.runAsSystem(() -> { UserPrincipal userPrincipal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if(userPrincipal.getUsername().equals(actor)) { return userPrincipal; } else { return this.userDetailsService.loadUserByUsername(actor); } }); }
Example 23
Source Project: SpringAll Source File: SmsAuthenticationProvider.java License: MIT License | 5 votes |
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication; UserDetails userDetails = userDetailService.loadUserByUsername((String) authenticationToken.getPrincipal()); if (userDetails == null) throw new InternalAuthenticationServiceException("未找到与该手机号对应的用户"); SmsAuthenticationToken authenticationResult = new SmsAuthenticationToken(userDetails, userDetails.getAuthorities()); authenticationResult.setDetails(authenticationToken.getDetails()); return authenticationResult; }
Example 24
Source Project: spring-react-boilerplate Source File: AuthenticationRestController.java License: MIT License | 5 votes |
@RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST) public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest) throws AuthenticationException { authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword()); // Reload password post-security so we can generate the token final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername()); final String token = jwtTokenUtil.generateToken(userDetails); // Return the token return ResponseEntity.ok(new JwtAuthenticationResponse(token)); }
Example 25
Source Project: Spring-Security-Third-Edition Source File: SpringSecurityUserContext.java License: MIT License | 5 votes |
@Override public void setCurrentUser(CalendarUser user) { if (user == null) { throw new IllegalArgumentException("user cannot be null"); } UserDetails userDetails = userDetailsService.loadUserByUsername(user.getEmail()); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, user.getPassword(), userDetails.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(authentication); }
Example 26
Source Project: gpmr Source File: SecurityUtils.java License: Apache License 2.0 | 5 votes |
/** * Get the login of the current user. * * @return the login of the current user */ public static String getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); String userName = null; if (authentication != null) { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); userName = springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof String) { userName = (String) authentication.getPrincipal(); } } return userName; }
Example 27
Source Project: Spring-Security-Third-Edition Source File: CalendarUserDetailsService.java License: MIT License | 5 votes |
/** * Lookup a {@link CalendarUser} by the username representing the email address. Then, convert the * {@link CalendarUser} into a {@link UserDetails} to conform to the {@link UserDetails} interface. */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { CalendarUser user = calendarUserDao.findUserByEmail(username); if (user == null) { throw new UsernameNotFoundException("Invalid username/password."); } return new CalendarUserDetails(user); }
Example 28
Source Project: kylin-on-parquet-v2 Source File: UserControllerTest.java License: Apache License 2.0 | 5 votes |
@Test public void testLoginAsAnotherUser() throws IOException { logInWithUser(userModeler); UserDetails userDetail = userController.authenticate(); ManagedUser user = (ManagedUser) userDetail; Assert.assertTrue(user.equals(userModeler)); }
Example 29
Source Project: flowable-engine Source File: CustomPersistentRememberMeServices.java License: Apache License 2.0 | 5 votes |
@Override @Transactional protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) { Token token = getPersistentToken(cookieTokens); // Refresh token if refresh period has been passed if (new Date().getTime() - token.getTokenDate().getTime() > tokenRefreshDurationInMilliseconds) { // log.info("Refreshing persistent login token for user '{}', series '{}'", token.getUserId(), token.getSeries()); try { // Refreshing: creating a new token to be used for subsequent calls token = persistentTokenService.createToken(identityService.createUserQuery().userId(token.getUserId()).singleResult(), request.getRemoteAddr(), request.getHeader("User-Agent")); addCookie(token, request, response); } catch (DataAccessException e) { LOGGER.error("Failed to update token: ", e); throw new RememberMeAuthenticationException("Autologin failed due to data access problem: " + e.getMessage()); } } return customUserDetailService.loadByUserId(token.getUserId()); }
Example 30
Source Project: spring-boot-demo Source File: SecurityUtil.java License: MIT License | 5 votes |
/** * 获取当前登录用户信息 * * @return 当前登录用户信息,匿名登录时,为null */ public static UserPrincipal getCurrentUser() { Object userInfo = SecurityContextHolder.getContext() .getAuthentication() .getPrincipal(); if (userInfo instanceof UserDetails) { return (UserPrincipal) userInfo; } return null; }