org.springframework.security.core.Authentication.getAuthorities()方法的使用及代码示例

x33g5p2x  于2022-01-15 转载在 其他  
字(10.1k)|赞(0)|评价(0)|浏览(135)

本文整理了Java中org.springframework.security.core.Authentication.getAuthorities()方法的一些代码示例,展示了Authentication.getAuthorities()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Authentication.getAuthorities()方法的具体详情如下:
包路径:org.springframework.security.core.Authentication
类名称:Authentication
方法名:getAuthorities

Authentication.getAuthorities介绍

[英]Set by an AuthenticationManager to indicate the authorities that the principal has been granted. Note that classes should not rely on this value as being valid unless it has been set by a trusted AuthenticationManager.

Implementations should ensure that modifications to the returned collection array do not affect the state of the Authentication object, or use an unmodifiable instance.
[中]由AuthenticationManager设置,表示委托人已被授予的权限。请注意,类不应依赖此值作为有效值,除非它已由受信任的AuthenticationManager设置。
实现应该确保对返回的集合数组的修改不会影响身份验证对象的状态,或者使用不可修改的实例。

代码示例

代码示例来源:origin: spring-projects/spring-security

Collection<? extends GrantedAuthority> extractAuthorities(
      Authentication authentication) {
    return authentication.getAuthorities();
  }
}

代码示例来源:origin: spring-projects/spring-security-oauth

public Map<String, ?> convertUserAuthentication(Authentication authentication) {
  Map<String, Object> response = new LinkedHashMap<String, Object>();
  response.put(USERNAME, authentication.getName());
  if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
    response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
  }
  return response;
}

代码示例来源:origin: spring-projects/spring-security-oauth

@Override
public Set<GrantedAuthority> getAuthorities() {
  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  if (authentication == null) {
    return Collections.emptySet();
  }
  return Collections.unmodifiableSet(new HashSet<GrantedAuthority>(authentication.getAuthorities()));
}

代码示例来源:origin: spring-projects/spring-security-oauth

/**
 * Construct an OAuth 2 authentication. Since some grant types don't require user authentication, the user
 * authentication may be null.
 * 
 * @param storedRequest The authorization request (must not be null).
 * @param userAuthentication The user authentication (possibly null).
 */
public OAuth2Authentication(OAuth2Request storedRequest, Authentication userAuthentication) {
  super(userAuthentication == null ? storedRequest.getAuthorities() : userAuthentication.getAuthorities());
  this.storedRequest = storedRequest;
  this.userAuthentication = userAuthentication;
}

代码示例来源:origin: spring-projects/spring-security

/**
   * Calls the <tt>RoleHierarchy</tt> to obtain the complete set of user authorities.
   */
  @Override
  Collection<? extends GrantedAuthority> extractAuthorities(
      Authentication authentication) {
    return roleHierarchy.getReachableGrantedAuthorities(authentication
        .getAuthorities());
  }
}

代码示例来源:origin: spring-projects/spring-security

public Collection<? extends GrantedAuthority> attemptAuthentication(String username,
    String password) throws RemoteAuthenticationException {
  UsernamePasswordAuthenticationToken request = new UsernamePasswordAuthenticationToken(
      username, password);
  try {
    return authenticationManager.authenticate(request).getAuthorities();
  }
  catch (AuthenticationException authEx) {
    throw new RemoteAuthenticationException(authEx.getMessage());
  }
}

代码示例来源:origin: spring-projects/spring-security

public List<Sid> getSids(Authentication authentication) {
    Collection<? extends GrantedAuthority> authorities = roleHierarchy
        .getReachableGrantedAuthorities(authentication.getAuthorities());
    List<Sid> sids = new ArrayList<>(authorities.size() + 1);

    sids.add(new PrincipalSid(authentication));

    for (GrantedAuthority authority : authorities) {
      sids.add(new GrantedAuthoritySid(authority));
    }

    return sids;
  }
}

代码示例来源:origin: spring-projects/spring-security

private Set<String> getAuthoritySet() {
  if (roles == null) {
    roles = new HashSet<>();
    Collection<? extends GrantedAuthority> userAuthorities = authentication
        .getAuthorities();
    if (roleHierarchy != null) {
      userAuthorities = roleHierarchy
          .getReachableGrantedAuthorities(userAuthorities);
    }
    roles = AuthorityUtils.authorityListToSet(userAuthorities);
  }
  return roles;
}

代码示例来源:origin: apache/kylin

private boolean checkExternalPermission(ExternalAclProvider eap, Authentication authentication, String entityType,
    String entityUuid, Object permission) {
  String currentUser = authentication.getName();
  List<String> authorities = AclPermissionUtil.transformAuthorities(authentication.getAuthorities());
  List<Permission> kylinPermissions = resolveKylinPermission(permission);
  for (Permission p : kylinPermissions) {
    if (eap.checkPermission(currentUser, authorities, entityType, entityUuid, p))
      return true;
  }
  return false;
}

代码示例来源:origin: spring-projects/spring-security

@GetMapping("/roles")
public String roles(@AuthenticationPrincipal Authentication authentication) {
  return authentication.getAuthorities().stream()
      .map(GrantedAuthority::getAuthority)
      .collect(Collectors.joining(","));
}

代码示例来源:origin: spring-projects/spring-security

@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, T object) {
  return authentication
    .filter(a -> a.isAuthenticated())
    .flatMapIterable( a -> a.getAuthorities())
    .map(g -> g.getAuthority())
    .any(a -> this.authorities.contains(a))
    .map( hasAuthority -> new AuthorizationDecision(hasAuthority))
    .defaultIfEmpty(new AuthorizationDecision(false));
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void checkWhenHasAuthorityAndAuthenticatedAndNoAuthoritiesThenReturnFalse() {
  when(authentication.isAuthenticated()).thenReturn(true);
  when(authentication.getAuthorities()).thenReturn(Collections.emptyList());
  boolean granted = manager.check(Mono.just(authentication), null).block().isGranted();
  assertThat(granted).isFalse();
}

代码示例来源:origin: spring-projects/spring-security

@Test
  public void securityContextDeserializeTest() throws IOException {
    SecurityContext context = mapper.readValue(SECURITY_CONTEXT_JSON, SecurityContextImpl.class);
    assertThat(context).isNotNull();
    assertThat(context.getAuthentication()).isNotNull().isInstanceOf(UsernamePasswordAuthenticationToken.class);
    assertThat(context.getAuthentication().getPrincipal()).isEqualTo("admin");
    assertThat(context.getAuthentication().getCredentials()).isEqualTo("1234");
    assertThat(context.getAuthentication().isAuthenticated()).isTrue();
    Collection authorities = context.getAuthentication().getAuthorities();
    assertThat(authorities).hasSize(1);
    assertThat(authorities).contains(new SimpleGrantedAuthority("ROLE_USER"));
  }
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void authenticateSuccess() throws Exception {
  Authentication auth = provider.authenticate(token);
  assertThat(auth.getPrincipal()).isEqualTo(token.getPrincipal());
  assertThat(auth.getCredentials()).isEqualTo(token.getCredentials());
  assertThat(auth.isAuthenticated()).isEqualTo(true);
  assertThat(auth.getAuthorities().isEmpty()).isEqualTo(false);
  verify(publisher).publishEvent(isA(JaasAuthenticationSuccessEvent.class));
  verifyNoMoreInteractions(publisher);
}

代码示例来源:origin: spring-projects/spring-security

@Test
  public void authenticateWhenJwtThenSuccess() {
    BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1");
    when(this.jwtDecoder.decode(token.getToken())).thenReturn(Mono.just(this.jwt));

    Authentication authentication = this.manager.authenticate(token).block();

    assertThat(authentication).isNotNull();
    assertThat(authentication.isAuthenticated()).isTrue();
    assertThat(authentication.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("SCOPE_message:read", "SCOPE_message:write");
  }
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void getAuthenticationManagerWhenProtectedPasswordEncoderBeanThenUsed() throws Exception {
  this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
  AuthenticationManager manager = this.spring.getContext()
    .getBean(AuthenticationConfiguration.class).getAuthenticationManager();
  Authentication auth = manager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
  assertThat(auth.getName()).isEqualTo("user");
  assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("ROLE_USER");
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void getAuthenticationManagerWhenGlobalPasswordEncoderBeanThenUsed() throws Exception {
  this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
  AuthenticationManager manager = this.spring.getContext()
    .getBean(AuthenticationConfiguration.class).getAuthenticationManager();
  Authentication auth = manager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
  assertThat(auth.getName()).isEqualTo("user");
  assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("ROLE_USER");
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void testNullDefaultAuthorities() {
  UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
      "user", "password");
  assertThat(jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
  Authentication auth = jaasProvider.authenticate(token);
  assertThat(auth
      .getAuthorities()).withFailMessage("Only ROLE_TEST1 and ROLE_TEST2 should have been returned").hasSize(2);
}

代码示例来源:origin: spring-projects/spring-security

@Test
public void testSuccessfulAuthenticationCreatesObject() {
  RemoteAuthenticationProvider provider = new RemoteAuthenticationProvider();
  provider.setRemoteAuthenticationManager(
      new MockRemoteAuthenticationManager(true));
  Authentication result = provider
      .authenticate(new UsernamePasswordAuthenticationToken("rod", "password"));
  assertThat(result.getPrincipal()).isEqualTo("rod");
  assertThat(result.getCredentials()).isEqualTo("password");
  assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())).contains("foo");
}

代码示例来源:origin: spring-projects/spring-security

@Test
@WithMockUser
public void methodSecurityWhenCustomRunAsManagerThenRunAsWrapsAuthentication() {
  this.spring.register(CustomRunAsManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
  assertThat(service.runAs().getAuthorities())
    .anyMatch(authority -> "ROLE_RUN_AS_SUPER".equals(authority.getAuthority()));
}

相关文章