org.hamcrest.collection.IsCollectionWithSize#org.springframework.security.core.GrantedAuthority源码实例Demo

下面列出了org.hamcrest.collection.IsCollectionWithSize#org.springframework.security.core.GrantedAuthority 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: e-commerce-microservice   文件: TokenProvider.java
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();
}
 
/**
 * 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;
    };
}
 
源代码3 项目: tutorials   文件: TokenProvider.java
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();
}
 
源代码4 项目: jwala   文件: AdminServiceRestImpl.java
@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;
        }
    });
}
 
@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"));
}
 
源代码6 项目: joal   文件: WebSocketAuthenticatorService.java
@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")
    );
}
 
源代码7 项目: we-cmdb   文件: CmdbUserDetailService.java
@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());
    }
}
 
源代码8 项目: bbs   文件: StaffServiceBean.java
/**
 * 得到用户权限
 *@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;
	}
}
 
@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.");
  }
}
 
@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;
}
 
@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;
}
 
源代码12 项目: spring-security   文件: CustomUserDetailsService.java
/**
 * 认证过程中 - 根据登录信息获取用户详细信息
 *
 * @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);
}
 
@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!");
	}
}
 
源代码14 项目: govpay   文件: AutorizzazioneUtils.java
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;
}
 
@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);
}
 
源代码16 项目: alchemy   文件: TokenProvider.java
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();
}
 
源代码17 项目: govpay   文件: AnonymousAuthenticationFilter.java
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");
}
 
源代码18 项目: govpay   文件: AutenticazioneUtenzeAnonimeDAO.java
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();
	}
}
 
源代码19 项目: hawkbit   文件: PermissionService.java
/**
 * 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;
}
 
源代码20 项目: tutorials   文件: TokenProvider.java
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();
}
 
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;
     }
 
@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);
}
 
源代码23 项目: demo-spring-security-cas   文件: AppUserDetails.java
@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;
}
 
源代码24 项目: OpenLRW   文件: ClassControllerTest.java
@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);
}
 
public static Collection<? extends GrantedAuthority> createAuthorities(CalendarUser calendarUser) {
    String username = calendarUser.getEmail();
    if (username.startsWith("admin")) {
        return ADMIN_ROLES;
    }
    return USER_ROLES;
}
 
private Collection<GrantedAuthority> toGrantedAuthorities(List<String> roles) {
    List<GrantedAuthority> result = new ArrayList();
    for (String role : roles) {
        result.add(new SimpleGrantedAuthority(role));
    }
    return result;
}
 
源代码27 项目: eladmin   文件: TokenProvider.java
/**
 * 依据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);
}
 
源代码28 项目: syncope   文件: MultitenancyTest.java
@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);
}
 
源代码29 项目: paascloud-master   文件: SecurityUtils.java
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;
}
 
public static Collection<? extends GrantedAuthority> createAuthorities(CalendarUser calendarUser) {
    String username = calendarUser.getEmail();
    if (username.startsWith("admin")) {
        return ADMIN_ROLES;
    }
    return USER_ROLES;
}