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

The following examples show how to use org.springframework.security.core.GrantedAuthority. 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: e-commerce-microservice   Source File: TokenProvider.java    License: Apache License 2.0 7 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(key, SignatureAlgorithm.HS512)
        .setExpiration(validity)
        .compact();
}
 
Example 2
/**
 * Map authorities from "groups" or "roles" claim in ID Token.
 *
 * @return a {@link GrantedAuthoritiesMapper} that maps groups from
 * the IdP to Spring Security Authorities.
 */
@Bean
@SuppressWarnings("unchecked")
public GrantedAuthoritiesMapper userAuthoritiesMapper() {
    return (authorities) -> {
        Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

        authorities.forEach(authority -> {
            OidcUserAuthority oidcUserAuthority = (OidcUserAuthority) authority;
            OidcUserInfo userInfo = oidcUserAuthority.getUserInfo();
            Collection<String> groups = (Collection<String>) userInfo.getClaims().get("groups");
            if (groups == null) {
                groups = (Collection<String>) userInfo.getClaims().get("roles");
            }
            mappedAuthorities.addAll(groups.stream()
                .filter(group -> group.startsWith("ROLE_"))
                .map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        });

        return mappedAuthorities;
    };
}
 
Example 3
Source Project: tutorials   Source File: TokenProvider.java    License: MIT License 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 4
Source Project: jwala   Source File: AdminServiceRestImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Response getAuthorizationDetails() {
    return ResponseBuilder.ok(new ResponseContent() {
        private static final String TRUE = "true";
        private final String authEnabled = ApplicationProperties.get(JWALA_AUTHORIZATION, TRUE);

        public String getAuthorizationEnabled() {
            return authEnabled;
        }

        @SuppressWarnings("unchecked")
        public Collection<GrantedAuthority> getUserAuthorities() {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (authEnabled.equalsIgnoreCase(TRUE) && auth != null) {
                return (Collection<GrantedAuthority>) auth.getAuthorities();
            }
            return null;
        }
    });
}
 
Example 5
@Before
public void setUp() {
    mockCategoryRepository = createMock(CategoryRepository.class);
    defaultCategoryPermissionEvaluator = new DefaultCategoryPermissionEvaluator(mockCategoryRepository);
    mockAuthentication = createMock(Authentication.class);

    user = new UserImpl();
    user.setUsername(VALID_USERNAME);
    user.setId(VALID_USER_ID);
    user2 = new UserImpl();
    user2.setUsername(VALID_USERNAME2);

    category = new CategoryImpl();
    category.setId(VALID_WIDGET_CATEGORY_ID);
    category.setCreatedUserId(VALID_USER_ID);

    grantedAuthorities = new ArrayList<GrantedAuthority>();
    grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
}
 
Example 6
Source Project: joal   Source File: WebSocketAuthenticatorService.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("TypeMayBeWeakened")
public UsernamePasswordAuthenticationToken getAuthenticatedOrFail(final CharSequence username, final CharSequence authToken) throws AuthenticationException {
    if (StringUtils.isBlank(username)) {
        throw new AuthenticationCredentialsNotFoundException("Username was null or empty.");
    }
    if (StringUtils.isBlank(authToken)) {
        throw new AuthenticationCredentialsNotFoundException("Authentication token was null or empty.");
    }
    if (!appSecretToken.contentEquals(authToken)) {
        throw new BadCredentialsException("Authentication token does not match the expected token");
    }

    // Everything is fine, return an authenticated Authentication. (the constructor with grantedAuthorities auto set authenticated = true)
    // null credentials, we do not pass the password along to prevent security flaw
    return new UsernamePasswordAuthenticationToken(
            username,
            null,
            Collections.singleton((GrantedAuthority) () -> "USER")
    );
}
 
Example 7
Source Project: we-cmdb   Source File: CmdbUserDetailService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    List<AdmMenu> admMenus = admMenusRepository.findMenusByUserName(username);
    String password = getPassword(username);

    if (CollectionUtils.isNotEmpty(admMenus)) {
        List<GrantedAuthority> authorities = admMenus.stream()
                .map(AdmMenu::getName)
                .map(menuName -> new SimpleGrantedAuthority(ROLE_PREFIX + menuName))
                .collect(toList());
        logger.info("Menu permissions {} found for user {}", authorities, username);
        return new User(username, password, authorities);
    } else {
        logger.warn("No accessible menu found for user {}", username);
        return new User(username, password, emptyList());
    }
}
 
Example 8
Source Project: bbs   Source File: StaffServiceBean.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 得到用户权限
 *@param userAccount 用户账号
 *@return
 */
@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
public List<GrantedAuthority> loadUserAuthoritiesByName(String userAccount){

	try {
		List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		
		List<String> authorities = loadUserAuthorities(userAccount);
		if(authorities != null && authorities.size() >0){
			for (String roleName : authorities) {
				auths.add(new SimpleGrantedAuthority(roleName));  
			}
		}
		return auths;
	} catch (RuntimeException re) {
		if (logger.isErrorEnabled()) {
            logger.error("得到用户权限",re);
        }
		throw re;
	}
}
 
Example 9
Source Project: spring-auth-example   Source File: FooAuthenticationProvider.java    License: MIT License 6 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication)
    throws AuthenticationException {
  logger.debug(
      "==== Authenticating using FooAuthenticationProvider: " +
          authentication);

  // here goes username/password authentication for Foo
  Response response = userService
      .authenticateFoo(String.valueOf(authentication.getPrincipal()),
          String.valueOf(authentication.getCredentials()));

  if (response.isOk()) {
    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("FOO_READ"));
    authorities.add(new SimpleGrantedAuthority("FOO_WRITE"));
    return new FooUsernamePasswordAuthenticationToken(
        authentication.getPrincipal(), authentication.getCredentials(),
        authorities);
  } else {
    throw new BadCredentialsException("Authentication failed.");
  }
}
 
Example 10
@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 11
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    RemoteUser user = remoteIdmService.authenticateUser(authentication.getPrincipal().toString(), authentication.getCredentials().toString());
    if (user == null) {
        throw new FlowableException("user not found " + authentication.getPrincipal());
    }

    Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    for (String privilege : user.getPrivileges()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(privilege));
    }

    Authentication auth = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
            authentication.getCredentials(), grantedAuthorities);
    return auth;
}
 
Example 12
Source Project: spring-security   Source File: CustomUserDetailsService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 认证过程中 - 根据登录信息获取用户详细信息
 *
 * @param s 登录用户输入的用户名
 * @return
 * @throws UsernameNotFoundException
 */
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
    //根据用户输入的用户信息,查询数据库中已注册用户信息
    TUser user = userService.findByName(s);
    //如果用户不存在直接抛出UsernameNotFoundException异常
    if (user == null) throw new UsernameNotFoundException("用户名为" + s + "的用户不存在");
    List<TRole> roles = user.getRoleList();
    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

    for (TRole role:roles){
        List<TPermission> permissions = role.getPermissions();
        for (TPermission permission:permissions){
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getUrl());
            // 此处将权限信息添加到 GrantedAuthority 对象中,在后面进行权限验证时会使用GrantedAuthority 对象
            grantedAuthorities.add(grantedAuthority);
        }
    }
    return new CustomUserDetails(user, grantedAuthorities);
}
 
Example 13
@Override
public Authentication authenticate(Authentication authentication)
		throws AuthenticationException {
	String name = authentication.getName();
	String password = authentication.getCredentials().toString();
	AuthenticationRequest request = new AuthenticationRequest();
	request.setUsername(name);
	request.setPassword(password);
	try {
		Map<String, Object> params = service.login(request);
		if (params != null) {
			List<GrantedAuthority> grantedAuths = new ArrayList<>();
			grantedAuths.add(new SimpleGrantedAuthority("USER"));
			Authentication auth = new UsernamePasswordAuthenticationToken(
					name, password, grantedAuths);
			return auth;
		} else {
			throw new BadCredentialsException("Username not found");
		}
	} catch (HttpServerErrorException e) {
		throw new BadCredentialsException("Login failed!");
	}
}
 
Example 14
Source Project: govpay   Source File: AutorizzazioneUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static GovpayLdapUserDetails getUserDetail(String username, String password, String identificativo, List<GrantedAuthority> authorities) {
	GovpayLdapUserDetails details = new GovpayLdapUserDetails();

	LdapUserDetailsImpl.Essence essence = new LdapUserDetailsImpl.Essence();
	essence.setAccountNonExpired(true);
	essence.setAccountNonLocked(true);
	essence.setCredentialsNonExpired(true);
	essence.setEnabled(true);
	essence.setUsername(username);
	essence.setPassword(password);
	essence.setAuthorities(authorities);
	essence.setDn(identificativo);

	details.setLdapUserDetailsImpl(essence.createUserDetails());

	return details;
}
 
Example 15
@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 16
Source Project: alchemy   Source File: TokenProvider.java    License: Apache License 2.0 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(key, SignatureAlgorithm.HS512)
        .setExpiration(validity)
        .compact();
}
 
Example 17
public static List<GrantedAuthority> getAuthoritiesUtenzaAnonima() {
	List<GrantedAuthority> authFromPreauth = AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS");
	UserDetails utenzaAnonima = null;
	try {
		AutenticazioneUtenzeAnonimeDAO autenticazioneUtenzeAnonimeDAO = new AutenticazioneUtenzeAnonimeDAO(); 
		autenticazioneUtenzeAnonimeDAO.setApiName("API_PAGAMENTO");
		autenticazioneUtenzeAnonimeDAO.setAuthType("PUBLIC");
		utenzaAnonima = autenticazioneUtenzeAnonimeDAO.loadUserDetails("anonymousUser", authFromPreauth);
	} catch (UsernameNotFoundException e) {
	}
	
	if(utenzaAnonima != null) {
		List<GrantedAuthority> authorities = new ArrayList<>(); 
		authorities.addAll(utenzaAnonima.getAuthorities());
		return authorities;
	}
	
	return AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS");
}
 
Example 18
public UserDetails loadUserDetails(String username, Collection<? extends GrantedAuthority> authFromPreauth) throws UsernameNotFoundException {
	BasicBD bd = null;

	try {
		String transactionId = UUID.randomUUID().toString();
		this.debug(transactionId, "Caricamento informazioni dell'utenza ["+username+"] in corso...");
		bd = BasicBD.newInstance(transactionId, this.useCacheData);
		GovpayLdapUserDetails userDetailFromUtenzaAnonima = AutorizzazioneUtils.getUserDetailFromUtenzaAnonima(username, this.isCheckPassword(), this.isCheckSubject(), authFromPreauth, bd);
		userDetailFromUtenzaAnonima.setIdTransazioneAutenticazione(transactionId);
		this.debug(transactionId, "Caricamento informazioni dell'utenza ["+username+"] completato.");
		return userDetailFromUtenzaAnonima;
	} catch(Exception e){
		throw new RuntimeException("Errore interno, impossibile caricare le informazioni dell'utenza", e);
	}	finally {
		if(bd != null)
			bd.closeConnection();
	}
}
 
Example 19
Source Project: hawkbit   Source File: PermissionService.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Checks if at least on permission of the given {@code permissions}
 * contains in the . In case no {@code context} is available {@code false}
 * will be returned.
 *
 * @param permissions
 *            the permissions to check against the
 * @return {@code true} if a is available and contains the given
 *         {@code permission}, otherwise {@code false}.
 * @see SpPermission
 */
public boolean hasAtLeastOnePermission(final List<String> permissions) {
    final SecurityContext context = SecurityContextHolder.getContext();
    if (context == null) {
        return false;
    }

    final Authentication authentication = context.getAuthentication();
    if (authentication == null) {
        return false;
    }

    for (final GrantedAuthority authority : authentication.getAuthorities()) {
        for (final String permission : permissions) {
            if (authority.getAuthority().equals(permission)) {
                return true;
            }
        }
    }

    return false;
}
 
Example 20
Source Project: tutorials   Source File: TokenProvider.java    License: MIT License 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 21
Source Project: heimdall   Source File: HeimdallLdapAuthoritiesPopulator.java    License: Apache License 2.0 5 votes vote down vote up
private final List<GrantedAuthority> getGrantedAuthorities(final List<String> privileges) {

          final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
          for (final String privilege : privileges) {
               authorities.add(new SimpleGrantedAuthority(privilege));
          }
          return authorities;
     }
 
Example 22
@Test
public void testHasPermission_3args_administer_hasAdminRole() {
    grantedAuthorities.add(new SimpleGrantedAuthority(AuthenticationUtils.ROLE_ADMIN));
    EasyMock.<Collection<? extends GrantedAuthority>>expect(mockAuthentication.getAuthorities()).andReturn(grantedAuthorities);
    replay(mockAuthentication);
    assertThat(defaultCategoryPermissionEvaluator.hasPermission(mockAuthentication, category, ModelPermissionEvaluator.Permission.ADMINISTER), is(true));
    verify(mockAuthentication);
}
 
Example 23
Source Project: demo-spring-security-cas   Source File: AppUserDetails.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
	/*
	 * List<GrantedAuthority> l = new ArrayList<GrantedAuthority>(); l.add(new
	 * GrantedAuthority() { private static final long serialVersionUID = 1L;
	 * 
	 * @Override public String getAuthority() { return "ROLE_AUTHENTICATED"; } }); return l;
	 */
	return authorities;
}
 
Example 24
@Before
public void init() throws OrgNotFoundException, LineItemNotFoundException {
  MockitoAnnotations.initMocks(this);
  mockMvc = MockMvcBuilders.standaloneSetup(classController).build();
  
  classController = new ClassController(lineItemService,null,null,null,resultService,null);
  List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
  authorities.add(new SimpleGrantedAuthority("ROLE_TENANT_ADMIN"));
  UserContext context = UserContext.create(TestData.TENANT_1, "122", authorities);
  when(jwttoken.getPrincipal()).thenReturn(context);

  when(lineItemService.getLineItemsForClass("","","class123")).thenReturn(Collections.singletonList(li));
  when(lineItemService.save("","", li, true)).thenReturn(li);
}
 
Example 25
public static Collection<? extends GrantedAuthority> createAuthorities(CalendarUser calendarUser) {
    String username = calendarUser.getEmail();
    if (username.startsWith("admin")) {
        return ADMIN_ROLES;
    }
    return USER_ROLES;
}
 
Example 26
private Collection<GrantedAuthority> toGrantedAuthorities(List<String> roles) {
    List<GrantedAuthority> result = new ArrayList();
    for (String role : roles) {
        result.add(new SimpleGrantedAuthority(role));
    }
    return result;
}
 
Example 27
Source Project: eladmin   Source File: TokenProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 依据Token 获取鉴权信息
 *
 * @param token /
 * @return /
 */
Authentication getAuthentication(String token) {
    Claims claims = getClaims(token);

    // 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 28
Source Project: syncope   Source File: MultitenancyTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void setAuthContext() {
    List<GrantedAuthority> authorities = IdMEntitlement.values().stream().
            map(entitlement -> new SyncopeGrantedAuthority(entitlement, SyncopeConstants.ROOT_REALM)).
            collect(Collectors.toList());

    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
            new org.springframework.security.core.userdetails.User(
                    "admin", "FAKE_PASSWORD", authorities), "FAKE_PASSWORD", authorities);
    auth.setDetails(new SyncopeAuthenticationDetails("Two"));
    SecurityContextHolder.getContext().setAuthentication(auth);
}
 
Example 29
Source Project: paascloud-master   Source File: SecurityUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Set<String> getCurrentAuthorityUrl() {
	Set<String> path = Sets.newHashSet();
	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
	for (final GrantedAuthority authority : authorities) {
		String url = authority.getAuthority();
		if (StringUtils.isNotEmpty(url)) {
			path.add(url);
		}
	}
	path.add(AUTH_LOGIN_AFTER_URL);
	path.add(AUTH_LOGOUT_URL);
	return path;
}
 
Example 30
public static Collection<? extends GrantedAuthority> createAuthorities(CalendarUser calendarUser) {
    String username = calendarUser.getEmail();
    if (username.startsWith("admin")) {
        return ADMIN_ROLES;
    }
    return USER_ROLES;
}