public Authentication getAuthentication(String token) { Claims claims = Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(token) .getBody(); Collection<? extends GrantedAuthority> authorities = Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); User principal = new User(claims.getSubject(), "", authorities); return new UsernamePasswordAuthenticationToken(principal, "", authorities); }
public Authentication getAuthentication(String token) { Claims claims = Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(token) .getBody(); Collection<? extends GrantedAuthority> authorities = Arrays.asList(claims.get(AUTHORITIES_KEY).toString().split(",")).stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); User principal = new User(claims.getSubject(), "", authorities); return new UsernamePasswordAuthenticationToken(principal, "", authorities); }
/** * 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; }
@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)); }
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { //System.err.println("-----------MyUserDetailServiceImpl loadUserByUsername ----------- "); //取得用户的权限 Customer user = authService.findCustomer(userName); if (user==null) throw new UsernameNotFoundException(userName+" not exist!"); Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user); // 封装成spring security的user User userdetail = new User( user.getName(), user.getPassword(), true, true, true, true, grantedAuths //用户的权限 ); return userdetail; }
/** * Jwt资源令牌转换器 * @return accessTokenConverter */ @Bean public JwtAccessTokenConverter accessTokenConverter(){ return new JwtAccessTokenConverter(){ /** * 重写增强token的方法 * @param accessToken 资源令牌 * @param authentication 认证 * @return 增强的OAuth2AccessToken对象 */ @Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { String userName = authentication.getUserAuthentication().getName(); User user = (User) authentication.getUserAuthentication().getPrincipal(); Map<String,Object> infoMap = new HashMap<>(); infoMap.put("userName",userName); infoMap.put("roles",user.getAuthorities()); ((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(infoMap); return super.enhance(accessToken, authentication); } }; }
/** * Simulate a request with authenticated user with specified username for a * specified duration in nanoseconds. * * @param username * the username * @param durationInNanoseconds * the duration in nanoseconds */ protected void request(String username, long durationInNanoseconds) { long now = 1510373758000000000L; when(registry.getNanos()).thenReturn(now, now + durationInNanoseconds); if (username != null) { User user = new User(username, "", new ArrayList<GrantedAuthority>()); Authentication auth = new UsernamePasswordAuthenticationToken(user, null); SecurityContextHolder.getContext().setAuthentication(auth); } try { filter.doFilterInternal(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(FilterChain.class)); } catch (ServletException | IOException e) { e.printStackTrace(); } }
@Bean UserDetailsService userDetailsService() { return username -> { LOGGER.debug(String.format("Looking for user [%s]", username)); Account account = accountRepository.findByUsername(username); if (account != null) { LOGGER.info(String.format("Found user [%s]", username)); return new User(account.getUsername(), account.getPassword(), true, true, true, true, AuthorityUtils.createAuthorityList("USER")); } else { LOGGER.info(String.format("Couldn't find user [%s]", username)); throw new UsernameNotFoundException(String.format("couldn't find the user '%s'", username)); } }; }
@Bean public UserDetailsService userDetailsService() { return userName -> { UserDTO user = userAuthenticationProvider.userService.findByLogin(userName.toLowerCase()); if (user == null) { throw new UsernameNotFoundException(userName); } Set<SimpleGrantedAuthority> userAuthorities = new HashSet<>(); List<Role> roles = user.getRoles(); if (roles != null) { for (Role role : roles) { userAuthorities.add(new SimpleGrantedAuthority(role.toString())); } } return new User(userName, userName /* TODO use password */, userAuthorities); }; }
@Bean public UserDetailsService userDetailsService() { return new UserDetailsService() { @Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { // 通过用户名获取用户信息 Account account = accountRepository.findByName(name); if (account != null) { // 创建spring security安全用户 User user = new User(account.getName(), account.getPassword(), AuthorityUtils.createAuthorityList(account.getRoles())); return user; } else { throw new UsernameNotFoundException("用户[" + name + "]不存在"); } } }; }
protected UserDetails loadUserDetails(Assertion assertion) { String username = assertion.getPrincipal().getName(); if (!StringUtils.hasText(username)) { throw new UsernameNotFoundException("Unable to retrieve username from CAS assertion"); } List<GrantedAuthority> authorities = Arrays .stream(attributes) .map(a -> assertion.getPrincipal().getAttributes().get(a)) .filter(Objects::nonNull) .flatMap(v -> (v instanceof Collection) ? ((Collection<?>) v).stream() : Stream.of(v)) .map(v -> toUppercase ? v.toString().toUpperCase() : v.toString()) .map(r -> r.replaceFirst("^ROLE_", "")) .map(r -> new SimpleGrantedAuthority("ROLE_" + r)) .collect(Collectors.toList()); authorities.addAll(defaultGrantedAuthorities); return new User(username, NON_EXISTENT_PASSWORD_VALUE, authorities); }
@Autowired public void registerGlobalAuthentication(AuthenticationManagerBuilder auth) throws Exception { LOG.info("Registering global user details service"); auth.userDetailsService(username -> { try { BillingUser user = billingDao.loadUser(username); return new User( user.getUsername(), user.getPassword(), Collections.singletonList(() -> "AUTH") ); } catch (EmptyResultDataAccessException e) { LOG.warn("No such user: " + username); throw new UsernameNotFoundException(username); } }); }
public UserDetails loadUserByUsername(String username) { SysUser user = userRepository.findByUsername(username); if (user != null) { List<SysPermission> permissions = permissionRepository.findByAdminUserId(user.getId()); List<GrantedAuthority> grantedAuthorities = new ArrayList <>(); for (SysPermission permission : permissions) { if (permission != null && permission.getName()!=null) { GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName()); grantedAuthorities.add(grantedAuthority); } } return new User(user.getUsername(), user.getPassword(), grantedAuthorities); } else { throw new UsernameNotFoundException("admin: " + username + " do not exist!"); } }
public User parseUserFromToken(String token) { try { String username = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody() .getSubject(); String roleString = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token).getBody().get("roles", String.class); List<SimpleGrantedAuthority> roles = new ArrayList<>(); if (!StringUtils.isEmpty(roleString)) { String[] roleValues = StringUtils.split(roleString, ","); for (String roleValue : roleValues) { roles.add(new SimpleGrantedAuthority(roleValue)); } } return new User(username, token, roles); } catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException | SignatureException ex) { throw new BadCredentialsException("Invalid JWT token: ", ex); } catch (ExpiredJwtException expiredEx) { throw new JwtExpiredTokenException("JWT Token expired", expiredEx); } }
@Override public Mono<UserDetails> findByUsername(String username) { return userRepository.findByUsr(username) .flatMap(user -> Mono.just(User .withUsername(user.getUsr()) .password(user.getPwd()) .roles(user.getRole()) .authorities(user.getAuthorities()) .accountExpired(user.isAccountNonExpiredAlias()) .accountLocked(user.isAccountNonLockedAlias()) .credentialsExpired(user.isCredentialsNonExpiredAlias()) .disabled(user.isEnabledAlias()).build())); }
@Bean UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager( User .withUsername("user") .password("password") .roles("USER").build()); }
@Override public Mono<UserDetails> findByUsername(String username) { return repository.findByUsername(username) .map(user -> new User( user.getUsername(), user.getPassword(), AuthorityUtils.createAuthorityList(user.getRoles()) )); }
/** * Return the current user, or throws an exception, if the user is not * authenticated yet. * * @return the current user */ public static User getCurrentUser() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); if (authentication != null) { if (authentication.getPrincipal() instanceof User) { return (User) authentication.getPrincipal(); } } throw new IllegalStateException("User not found!"); }
/** * 根据用户名查找账户信息并返回用户信息实体 * @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+"]不存在"); } }
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return accountRepository .findByUsername(username) .map(account -> new User(account.getUsername(), account.getPassword(), AuthorityUtils.createAuthorityList("ROLE_USER"))) .orElseThrow(() -> new UsernameNotFoundException("Could not find " + username)); }
/** * Initialize {@link SecurityContextHolder} for given user. * * @param user * the user to set in the context. * @param authorities * the optional authorities name * @return The configured {@link SecurityContext}. */ @SuppressWarnings("unchecked") protected SecurityContext initSpringSecurityContext(final String user, final GrantedAuthority... authorities) { SecurityContextHolder.clearContext(); final SecurityContext context = Mockito.mock(SecurityContext.class); final Authentication authentication = Mockito.mock(Authentication.class); final List<GrantedAuthority> authoritiesAsList = Arrays.asList(authorities); final User userDetails = new User(user, USER_DETAILS_NA, authoritiesAsList); Mockito.when((List<GrantedAuthority>) authentication.getAuthorities()).thenReturn(authoritiesAsList); Mockito.when(context.getAuthentication()).thenReturn(authentication); Mockito.when(authentication.getPrincipal()).thenReturn(userDetails); Mockito.when(authentication.getName()).thenReturn(user); SecurityContextHolder.setContext(context); return context; }
/** * 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") @Timed public ResponseEntity<UserVM> getAccount() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); try{ User user = (User) authentication.getPrincipal(); UserVM userVM = new UserVM(user.getUsername(), user.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); } }
public Authentication getAuthentication(String token) { Claims claims = Jwts.parser() .setSigningKey(secretKey) .parseClaimsJws(token) .getBody(); Collection<? extends GrantedAuthority> authorities = Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); User principal = new User(claims.getSubject(), "", authorities); return new UsernamePasswordAuthenticationToken(principal, token, authorities); }
@Bean UserDetailsService userDetailsService() throws Exception { UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("password") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); }
/** * 获取用户信息,设置角色 */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 获取用户信息 MangoUser mangoUser = userService.getUserByName(username); if (mangoUser != null) { // 设置角色 return new User(mangoUser.getUserName(), mangoUser.getPassword(), AuthorityUtils.createAuthorityList(mangoUser.getRole())); } throw new UsernameNotFoundException("User '" + username + "' not found."); }
@RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET) public String welcome(Model model, HttpSession session) { User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Contexto contex = FactoriaComandos.getInstance().crearComando(EventosNegocio.BUSCAR_USUARIO_BY_EMAIL).execute(user.getUsername()); model.addAttribute("title", "EventSoft"); if(contex.getEvento() == EventosNegocio.BUSCAR_USUARIO_BY_EMAIL) { Usuario usuario = (Usuario) contex.getDatos(); session.setAttribute("usuario", usuario); if(usuario.getRoles().equalsIgnoreCase("ADMIN")) { session.setAttribute("rol", "Administrador"); model.addAttribute("pagina", "admin"); return "redirect:./administracion/admin"; } else if (usuario instanceof Cliente) { session.setAttribute("rol", "Cliente"); model.addAttribute("pagina", "perfil-usuario"); return "redirect:./usuarios/perfil-usuario"; } else if (usuario instanceof Organizador) { session.setAttribute("rol", "Organizador"); model.addAttribute("pagina", "timeline"); model.addAttribute("CategoriasEvento", Arrays.asList(Evento.CategoriasEvento.values())); model.addAttribute("listaTiposServicio", Servicio.TiposServicio.values()); return "timeline"; } else if (usuario instanceof Proveedor) { session.setAttribute("rol", "Proveedor"); model.addAttribute("pagina", "proveedores"); model.addAttribute("listaTiposServicio", Servicio.TiposServicio.values()); return "redirect:./servicios/buscar/por-proveedor/" + usuario.getId(); } } return "redirect:/500"; }
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { String password = userService.getUserCredentials(username); if(password == null){ throw new UsernameNotFoundException("Invalid User"); } UserDetails user = new User(username, password, true, true, true, true, getAuthorities(username)); return user; }
private UserDetails toUserDetails(UserEntity user) { return User.withUsername(user.getName()) .password(user.getPassword()) .authorities(Lists.newArrayList()) .disabled(!user.isEnabled()) .build(); }
@Override public UserDetails loadUserByUsername(final String username) { final Object[][] userAndRoles = userRepository.findByLoginFetchRoles(username); final SystemUser user; final Collection<GrantedAuthority> authorities; if (userAndRoles.length == 0) { user = new SystemUser(); user.setLogin(username); authorities = new ArrayList<>(); } else { user = (SystemUser) userAndRoles[0][0]; // Add all roles authorities = toSimpleRoles(userAndRoles, 1); } // Update last connection information only as needed for performance, delta is one minute final Date now = org.ligoj.bootstrap.core.DateUtils.newCalendar().getTime(); if (user.getLastConnection() == null || now.getTime() - user.getLastConnection().getTime() > DateUtils.MILLIS_PER_DAY) { user.setLastConnection(now); userRepository.saveAndFlush(user); } // Also add the default role as needed authorities.add(new SimpleGrantedAuthority(SystemRole.DEFAULT_ROLE)); return new User(username, "N/A", authorities); }