public Authentication getAuthentication(HttpServletRequest request) { String token = request.getHeader(HEADER_STRING); if (token != null) { // parse the token. String user = getUsername(token); String roles = getBody(token).get("roles", String.class); List<GrantedAuthority> grantedAuths = AuthorityUtils.commaSeparatedStringToAuthorityList(roles); return user != null ? new UsernamePasswordAuthenticationToken(user, null, grantedAuths) : null; } return null; }
@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 Authentication authenticate(Authentication auth){ Usuario user = userRepository.findByEmail(auth.getName()); if (user == null) { throw new BadCredentialsException("User not found"); } String password = (String) auth.getCredentials(); if (!new BCryptPasswordEncoder().matches(password, user.getContraseña())) { throw new BadCredentialsException("Wrong password"); } List<GrantedAuthority> roles = new ArrayList<>(); for (String role : user.getRol()) { roles.add(new SimpleGrantedAuthority(role)); } return new UsernamePasswordAuthenticationToken(user.getEmail(), password, roles); }
public static List<String> getAuthorities() { Authentication authentication = getAuthentication(); if (authentication == null) { return Collections.EMPTY_LIST; } Collection<? extends GrantedAuthority> grantedAuthorityList = authentication .getAuthorities(); List<String> authorities = new ArrayList<String>(); for (GrantedAuthority grantedAuthority : grantedAuthorityList) { authorities.add(grantedAuthority.getAuthority()); } return authorities; }
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { if (StringUtils.isBlank(username)) { throw new UsernameNotFoundException("用户名为空"); } String password; TUser tUser = iUserService.getByUsername(username); if(tUser==null){ throw new UsernameNotFoundException("登录账号不存在"); }else{ password=tUser.getPassword(); } Set<GrantedAuthority> authorities = new HashSet<>(); authorities.add(new SimpleGrantedAuthority("USER")); return new org.springframework.security.core.userdetails.User( username, password, true, true, true, true, authorities); }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; String email = token.getName(); CalendarUser user = email == null ? null : calendarService.findUserByEmail(email); if(user == null) { throw new UsernameNotFoundException("Invalid username/password"); } // Database Password already encrypted: String password = user.getPassword(); boolean passwordsMatch = passwordEncoder.matches(token.getCredentials().toString(), password); if(!passwordsMatch) { throw new BadCredentialsException("Invalid username/password"); } Collection<? extends GrantedAuthority> authorities = CalendarUserAuthorityUtils.createAuthorities(user); UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, password, authorities); return usernamePasswordAuthenticationToken; }
public String createToken(Authentication authentication, Boolean rememberMe) { String authorities = authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.joining(",")); long now = (new Date()).getTime(); Date validity; if (rememberMe) { validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe); } else { validity = new Date(now + this.tokenValidityInMilliseconds); } return Jwts.builder() .setSubject(authentication.getName()) .claim(AUTHORITIES_KEY, authorities) .signWith(SignatureAlgorithm.HS512, secretKey) .setExpiration(validity) .compact(); }
public static UserContext create(String tenantId, String orgId, List<GrantedAuthority> authorities) { if (authorities == null || authorities.isEmpty()) { throw new IllegalArgumentException("No authorities"); } Optional<GrantedAuthority> maybeSuperAdmin = authorities.stream() .filter(authority -> authority.getAuthority().equals("ROLE_SUPER_ADMIN")).findAny(); if (maybeSuperAdmin.isPresent()) { return new UserContext("*", "*", authorities); } Optional<GrantedAuthority> maybeTenantAdmin = authorities.stream() .filter(authority -> authority.getAuthority().equals("ROLE_TENANT_ADMIN")).findAny(); if (maybeTenantAdmin.isPresent()) { return new UserContext(tenantId, "*", authorities); } return new UserContext(tenantId, orgId, authorities); }
private List<Resource> doGetGrantedResources(List<? extends Resource> existedResources, List<GrantedAuthority> roles) { List<Resource> result = new ArrayList<>(); //always return the open resource existedResources.stream().filter(res -> res.isOpen()).forEach(res -> result.add(res)); //and return the granted resource existedResources.stream().filter(res -> !res.isOpen()).forEach(resource -> { for (GrantedAuthority role : roles) { ResourceRoleRelationship resourceRoleRelationship = resourceRoleRelationshipRepository.findByResourceCodeAndRoleCode( resource.getCode(), RbacUtils.buildRoleCode(role)); if (resourceRoleRelationship != null) { result.add(resource); break; } } }); return result; }
public JwtUser( Long id, String username, String firstname, String lastname, String email, String password, Collection<? extends GrantedAuthority> authorities, boolean enabled, Date lastPasswordResetDate ) { this.id = id; this.username = username; this.firstname = firstname; this.lastname = lastname; this.email = email; this.password = password; this.authorities = authorities; this.enabled = enabled; this.lastPasswordResetDate = lastPasswordResetDate; }
@Override @Transactional public UserDetails loadUserByUsername(final String login) { log.debug("Authenticating {}", login); String lowercaseLogin = login.toLowerCase(Locale.ENGLISH); Optional<User> userFromDatabase = userRepository.findOneWithAuthoritiesByLogin(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")); }
@Override public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) { Collection<? extends GrantedAuthority> authorities = delegate.getGrantedAuthorities(userData, username); if (authorities != null) { return authorities.stream() .map(GrantedAuthority::getAuthority) .map(a -> authorityToPermissionMap.get(a)) .filter(Objects::nonNull) .filter(a -> !a.isEmpty()) .map(SimpleGrantedAuthority::new) .collect(Collectors.toSet()); } else { return null; } }
@Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal(); String roles = ""; List<GrantedAuthority> grantedAuthorities = (List<GrantedAuthority>) customUserDetails.getAuthorities(); for (GrantedAuthority grantedAuthority : grantedAuthorities) { roles = roles.concat(" " + grantedAuthority.getAuthority()); } roles = roles.trim(); Map<String, Object> additionalInfo = new HashMap<>(); additionalInfo.put("uuid", customUserDetails.getId()); additionalInfo.put("role", roles); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo); return accessToken; }
/** * Check the authorization */ private boolean isAuthorized(final Collection<? extends GrantedAuthority> authorities, final String request, final HttpMethod method) { final Map<String, Map<HttpMethod, List<Pattern>>> authorizationsCache = authorizationResource.getAuthorizations().get( AuthorizationType.API); // Check the authorization if (authorizationsCache != null) { for (final GrantedAuthority authority : authorities) { final Map<HttpMethod, List<Pattern>> authorizations = authorizationsCache.get(authority.getAuthority()); if (authorizations != null && match(authorizations.get(method), request)) { // Granted access return true; } } } // No authorization found return false; }
public Set<String> getCurrentRoles() { Set<String> roles = new HashSet<String>(); try { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth!=null && auth.isAuthenticated()) { Object principal = auth.getPrincipal(); if (principal instanceof UserDetails) { for (GrantedAuthority ga : ((UserDetails)principal).getAuthorities()) { roles.add(ga.getAuthority()); } } } } catch (Exception e) { log.error("Can't get roles", e); } return roles; }
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; }
@Override @RequestMapping(value = USER_GET_SVC, method = RequestMethod.POST) public @ResponseBody MobileClient getMobileClient( @RequestBody String gcmToken, Principal p) { System.out.println("GCM Token: " + gcmToken); MobileClient mc = null; List<String> roles = Lists.newArrayList(); try { Authentication auth = (Authentication) p; for (GrantedAuthority role : auth.getAuthorities()) { roles.add(role.getAuthority()); } mc = mobileclients.findByUsername(auth.getName()); // Remove the token's quotation marks gcmToken = gcmToken.substring(1, gcmToken.length() - 1); // Update token and roles of the client mc.setGcmToken(gcmToken); mc.setRoles(roles); } catch (ClassCastException e) { e.printStackTrace(); } return mobileclients.save(mc); }
public static Authentication getAuthentication(HttpServletRequest request) { // 从Header中拿到token String token = request.getHeader(HEADER_STRING); if (token == null) { token = getTokenFromCookis(request); } if (token != null && !token.isEmpty()) { // 解析 Token Claims claims = Jwts.parser().setSigningKey(SECRET) .parseClaimsJws(token).getBody(); // 获取用户名 String user = claims.get("UserId").toString(); // 获取权限(角色) List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities")); // 返回验证令牌 return user != null ? new UsernamePasswordAuthenticationToken(user, null, authorities) : null; } return null; }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { // 获取认证的用户名 & 密码 String name = authentication.getName(); String password = authentication.getCredentials().toString(); User user = userRepository.findByUserName(name); if (user == null) throw new UsernameNotFoundException("username not found!"); if (!user.isEnable()) throw new AuthenticationException("user has been disabled!") {}; // 认证逻辑 if (user.validatePassword(password)) { // 这里设置权限和角色 ArrayList<GrantedAuthority> authorities = new ArrayList<>(); // authorities.add( new GrantedAuthorityImpl("ROLE_ADMIN") ); // authorities.add( new GrantedAuthorityImpl("AUTH_WRITE") ); // 生成令牌 Authentication auth = new UsernamePasswordAuthenticationToken(name, password, authorities); return auth; }else { throw new BadCredentialsException("密码错误~"); } }
@Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { final Map<String, Object> additionalInfo = new HashMap<>(); Collection<GrantedAuthority> authorities = authentication.getAuthorities(); Object[] ga = authorities.toArray(); SimpleGrantedAuthority sga = (SimpleGrantedAuthority) ga[0]; String role = sga.getAuthority(); additionalInfo.put("role", role); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo); return accessToken; }
public static Collection<? extends GrantedAuthority> createAuthorities(CalendarUser calendarUser) { String username = calendarUser.getEmail(); if (username.startsWith("admin")) { return ADMIN_ROLES; } return USER_ROLES; }
@Override @Transactional(readOnly = true) public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserAccount userAccount = userRepository.findByUsername(username); Set<GrantedAuthority> grantedAuthorities = new HashSet<>(); for (Role role : userAccount.getRoles()) { grantedAuthorities.add(new SimpleGrantedAuthority(role.getRole())); } return new User(userAccount.getUsername(), userAccount.getPassword(), grantedAuthorities); }
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); }
@Override public List<Resource> getGrantedResources(List<GrantedAuthority> roles) { return roles.stream() .filter(role -> SysRole.ROLE_ADMIN == role) .findFirst() .map(role -> resourceService.getFlattenResources()) .orElseGet(() -> doGetGrantedResources(resourceService.getFlattenResources(), roles)); }
@Test public void testAnonymousIsNotAuthenticated() { SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities)); SecurityContextHolder.setContext(securityContext); boolean isAuthenticated = SecurityUtils.isAuthenticated(); assertThat(isAuthenticated).isFalse(); }