Java Code Examples for org.springframework.security.core.GrantedAuthority

The following are top voted examples for showing how to use org.springframework.security.core.GrantedAuthority. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: MicroServiceDemo   File: JwtTokenUtil.java   View source code 13 votes vote down vote up
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;
}
 
Example 2
Project: Spring-Security-Third-Edition   File: UserDetailsServiceImpl.java   View source code 7 votes vote down vote up
@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 3
Project: Spring-Security-Third-Edition   File: UserDetailsServiceImpl.java   View source code 7 votes vote down vote up
@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 4
Project: FCat   File: GateUserDetailsService.java   View source code 7 votes vote down vote up
@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);
}
 
Example 5
Project: SaleWeb   File: UsuarioRepositoryAuthenticationProvider.java   View source code 6 votes vote down vote up
@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);
}
 
Example 6
Project: lemon   File: SpringSecurityUtils.java   View source code 6 votes vote down vote up
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;
}
 
Example 7
Project: Spring-Security-Third-Edition   File: UserDetailsServiceImpl.java   View source code 6 votes vote down vote up
@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 8
Project: Spring-Security-Third-Edition   File: CalendarUserAuthenticationProvider.java   View source code 6 votes vote down vote up
@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;
}
 
Example 9
Project: jhipster-microservices-example   File: TokenProvider.java   View source code 6 votes vote down vote up
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();
}
 
Example 10
Project: OpenLRW   File: UserContext.java   View source code 6 votes vote down vote up
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);
}
 
Example 11
Project: Spring-Security-Third-Edition   File: CalendarUserAuthenticationProvider.java   View source code 6 votes vote down vote up
@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;
}
 
Example 12
Project: spring-backend-boilerplate   File: PermissionServiceImpl.java   View source code 6 votes vote down vote up
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;
}
 
Example 13
Project: rest-api-jwt-spring-security   File: JwtUser.java   View source code 6 votes vote down vote up
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;
}
 
Example 14
Project: Spring-Security-Third-Edition   File: UserDetailsServiceImpl.java   View source code 6 votes vote down vote up
@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 15
Project: Spring-Security-Third-Edition   File: CalendarUserAuthenticationProvider.java   View source code 6 votes vote down vote up
@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;
}
 
Example 16
Project: spring-io   File: DomainUserDetailsService.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 17
Project: ARCLib   File: RewriteAuthoritiesPopulator.java   View source code 6 votes vote down vote up
@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;
    }
}
 
Example 18
Project: spring-oauth2-jwt   File: JWTTokenEnhancer.java   View source code 6 votes vote down vote up
@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;
}
 
Example 19
Project: bootstrap   File: AuthorizingFilter.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 20
Project: yadaframework   File: YadaSecurityUtil.java   View source code 6 votes vote down vote up
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;
}
 
Example 21
Project: Fetax-AI   File: MainUserDetailServiceImpl.java   View source code 6 votes vote down vote up
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;
}
 
Example 22
Project: Spring-Security-Third-Edition   File: CalendarUserAuthenticationProvider.java   View source code 6 votes vote down vote up
@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;
}
 
Example 23
Project: Spring-Security-Third-Edition   File: CalendarUserAuthenticationProvider.java   View source code 6 votes vote down vote up
@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;
}
 
Example 24
Project: devoxxus-jhipster-microservices-demo   File: TokenProvider.java   View source code 6 votes vote down vote up
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();
}
 
Example 25
Project: generator-spring-rest-jwt   File: _JwtUser.java   View source code 6 votes vote down vote up
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;
}
 
Example 26
Project: Android_watch_magpie   File: MobileClientController.java   View source code 6 votes vote down vote up
@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);
}
 
Example 27
Project: hauth-java   File: JwtService.java   View source code 6 votes vote down vote up
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;
    }
 
Example 28
Project: fish-admin   File: JwtAuthenticationProvider.java   View source code 6 votes vote down vote up
@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("密码错误~");
    }
}
 
Example 29
Project: Spring-Security-Third-Edition   File: UserDetailsServiceImpl.java   View source code 6 votes vote down vote up
@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 30
Project: Spring-Security-Third-Edition   File: UserDetailsServiceImpl.java   View source code 6 votes vote down vote up
@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 31
Project: Building-Web-Apps-with-Spring-5-and-Angular   File: CustomTokenEnhancer.java   View source code 5 votes vote down vote up
@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;
}
 
Example 32
Project: Spring-Security-Third-Edition   File: CalendarUserAuthorityUtils.java   View source code 5 votes vote down vote up
public static Collection<? extends GrantedAuthority> createAuthorities(CalendarUser calendarUser) {
    String username = calendarUser.getEmail();
    if (username.startsWith("admin")) {
        return ADMIN_ROLES;
    }
    return USER_ROLES;
}
 
Example 33
Project: Spring-Security-Third-Edition   File: UserDetailsServiceImpl.java   View source code 5 votes vote down vote up
@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 34
Project: Spring-Security-Third-Edition   File: UserDetailsServiceImpl.java   View source code 5 votes vote down vote up
@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 35
Project: va-vedem-api   File: UserDetailsServiceImpl.java   View source code 5 votes vote down vote up
@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);
}
 
Example 36
Project: Spring-Security-Third-Edition   File: CalendarUserAuthorityUtils.java   View source code 5 votes vote down vote up
public static Collection<? extends GrantedAuthority> createAuthorities(CalendarUser calendarUser) {
    String username = calendarUser.getEmail();
    if (username.startsWith("admin")) {
        return ADMIN_ROLES;
    }
    return USER_ROLES;
}
 
Example 37
Project: Microservices-with-JHipster-and-Spring-Boot   File: TokenProvider.java   View source code 5 votes vote down vote up
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);
}
 
Example 38
Project: spring-backend-boilerplate   File: PermissionServiceImpl.java   View source code 5 votes vote down vote up
@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));
}
 
Example 39
Project: Spring-Security-Third-Edition   File: CalendarUserAuthorityUtils.java   View source code 5 votes vote down vote up
public static Collection<? extends GrantedAuthority> createAuthorities(CalendarUser calendarUser) {
    String username = calendarUser.getEmail();
    if (username.startsWith("admin")) {
        return ADMIN_ROLES;
    }
    return USER_ROLES;
}
 
Example 40
Project: Code4Health-Platform   File: SecurityUtilsUnitTest.java   View source code 5 votes vote down vote up
@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();
}