org.springframework.security.core.Authentication类的使用及代码示例

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

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

Authentication介绍

[英]Represents the token for an authentication request or for an authenticated principal once the request has been processed by the AuthenticationManager#authenticate(Authentication) method.

Once the request has been authenticated, the Authentication will usually be stored in a thread-local SecurityContext managed by the SecurityContextHolder by the authentication mechanism which is being used. An explicit authentication can be achieved, without using one of Spring Security's authentication mechanisms, by creating an Authentication instance and using the code:

SecurityContextHolder.getContext().setAuthentication(anAuthentication);

Note that unless the Authentication has the authenticated property set to true, it will still be authenticated by any security interceptor (for method or web invocations) which encounters it.

In most cases, the framework transparently takes care of managing the security context and authentication objects for you.
[中]表示身份验证请求或身份验证主体的令牌,一旦该请求已由AuthenticationManager#authentication(身份验证)方法处理。
一旦请求通过身份验证,身份验证通常将存储在由SecurityContextHolder通过正在使用的身份验证机制管理的线程本地SecurityContext中。通过创建身份验证实例并使用以下代码,无需使用Spring Security的身份验证机制,即可实现显式身份验证:

SecurityContextHolder.getContext().setAuthentication(anAuthentication);

请注意,除非身份验证将authenticated属性设置为true,否则遇到它的任何安全拦截器(用于方法或web调用)仍将对其进行身份验证。
在大多数情况下,框架透明地为您管理安全上下文和身份验证对象。

代码示例

代码示例来源:origin: ctripcorp/apollo

private String getCurrentUsername() {
 Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
 if (principal instanceof UserDetails) {
  return ((UserDetails) principal).getUsername();
 }
 if (principal instanceof Principal) {
  return ((Principal) principal).getName();
 }
 return String.valueOf(principal);
}

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

@RequestMapping(value = "/query/{queryId}/stop", method = RequestMethod.PUT)
@ResponseBody
public void stopQuery(@PathVariable String queryId) {
  final String user = SecurityContextHolder.getContext().getAuthentication().getName();
  logger.info("{} tries to stop the query: {}, but not guaranteed to succeed.", user, queryId);
  QueryContextFacade.stopQuery(queryId, "stopped by " + user);
}

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

private List<String> getGroupsFromCurrentUser() {
  List<String> groups = new ArrayList<>();
  Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication()
      .getAuthorities();
  for (GrantedAuthority auth : authorities) {
    groups.add(auth.getAuthority());
  }
  return groups;
}

代码示例来源: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: alibaba/nacos

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  String username = (String) authentication.getPrincipal();
  String password = (String) authentication.getCredentials();
  UserDetails userDetails = userDetailsService.loadUserByUsername(username);
  if (!password.equals(userDetails.getPassword())) {
    return new UsernamePasswordAuthenticationToken(username, null, null);
  }
  return null;
}

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

protected Authentication createNewAuthentication(Authentication currentAuth,
    String newPassword) {
  UserDetails user = loadUserByUsername(currentAuth.getName());
  UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(
      user, null, user.getAuthorities());
  newAuthentication.setDetails(currentAuth.getDetails());
  return newAuthentication;
}

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

/**
 * Get the indicated resource set
 * @param rsid
 * @param m
 * @param auth
 * @return
 */
@RequestMapping(value = "/{rsid}", method = RequestMethod.GET, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String getResourceSet(@PathVariable (value = "rsid") Long rsid, Model m, Authentication auth) {
  ResourceSet rs = resourceSetService.getById(rsid);
  if (rs == null) {
    m.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
    return HttpCodeView.VIEWNAME;
  }
  if (!rs.getOwner().equals(auth.getName())) {
    logger.warn("Unauthorized resource set request from bad user; expected " + rs.getOwner() + " got " + auth.getName());
    // authenticated user didn't match the owner of the resource set
    m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
    return HttpCodeView.VIEWNAME;
  }
  m.addAttribute(JsonEntityView.ENTITY, rs);
  return JsonEntityView.VIEWNAME;
}

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

@Secured("IS_AUTHENTICATED_FULLY")
 @RequestMapping(path = "/whoami/roles", method = RequestMethod.GET)
 public List<String> user() {
  UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().
    getAuthentication().getPrincipal();
  return userDetails.getAuthorities().stream().map(ga -> ga.getAuthority()).collect(Collectors.toList());
 }
}

代码示例来源:origin: kbastani/spring-cloud-event-sourcing-example

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
        new UsernamePasswordAuthenticationToken(request.getParameter("username"),
            request.getParameter("password"), authorities);
    SecurityContextHolder.getContext()
        .setAuthentication(authenticationManager.authenticate(auth));
    if(!authenticationManager.authenticate(auth).isAuthenticated())
      throw new CredentialException("User could not be authenticated");
  sessionRepository.saveContext(SecurityContextHolder.getContext(), responseHolder.getRequest(), responseHolder.getResponse());
  model.addAttribute("authorizationRequest", authRequest);

代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server

/**
 * List all resource sets for the current user
 * @param m
 * @param auth
 * @return
 */
@RequestMapping(value = "", method = RequestMethod.GET, produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public String getResourceSetsForCurrentUser(Model m, Authentication auth) {
  Collection<ResourceSet> resourceSets = resourceSetService.getAllForOwner(auth.getName());
  m.addAttribute(JsonEntityView.ENTITY, resourceSets);
  return JsonEntityView.VIEWNAME;
}

代码示例来源:origin: cloudfoundry/uaa

@RequestMapping(value = "/oauth/token/list", method = GET)
public ResponseEntity<List<RevocableToken>> listUserTokens(OAuth2Authentication authentication) {
  UaaPrincipal principal = (UaaPrincipal) authentication.getUserAuthentication().getPrincipal();
  String userId = principal.getId();
  String clientId = authentication.getOAuth2Request().getClientId();
  logger.debug("Listing revocable tokens access token userId:"+ userId +" clientId:"+ clientId);
  List<RevocableToken> result = tokenProvisioning.getUserTokens(userId, clientId, IdentityZoneHolder.get().getId());
  removeTokenValues(result);
  return new ResponseEntity<>(result, OK);
}

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth == null || !auth.isAuthenticated()) {
  throw new AuthenticationCredentialsNotFoundException("Authentication was null, not authenticated, or not logged in.");
  UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), auth.getAuthorities());
  SecurityContextHolder.getContext().setAuthentication(token);

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

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  byte[] hashKey = hf.hashString(authentication.getName() + authentication.getCredentials()).asBytes();
  String userKey = Arrays.toString(hashKey);
    SecurityContextHolder.getContext().setAuthentication(authed);
  } else {
    try {
      if (authed.getDetails() == null) {
      if (authed.getDetails() instanceof UserDetails) {
        UserDetails details = (UserDetails) authed.getDetails();
        user = new ManagedUser(details.getUsername(), details.getPassword(), false,
            details.getAuthorities());
      } else {
        user = new ManagedUser(authentication.getName(), "skippped-ldap", false, authed.getAuthorities());
      logger.error("Failed to auth user: " + authentication.getName(), e);
      throw e;

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

@Test
public void changePasswordSucceedsWithIfReAuthenticationSucceeds() {
  insertJoe();
  Authentication currentAuth = authenticateJoe();
  AuthenticationManager am = mock(AuthenticationManager.class);
  when(am.authenticate(currentAuth)).thenReturn(currentAuth);
  manager.setAuthenticationManager(am);
  manager.changePassword("password", "newPassword");
  UserDetails newJoe = manager.loadUserByUsername("joe");
  assertThat(newJoe.getPassword()).isEqualTo("newPassword");
  // The password in the context should also be altered
  Authentication newAuth = SecurityContextHolder.getContext().getAuthentication();
  assertThat(newAuth.getName()).isEqualTo("joe");
  assertThat(newAuth.getDetails()).isEqualTo(currentAuth.getDetails());
  assertThat(newAuth.getCredentials()).isNull();
  assertThat(cache.getUserMap().containsKey("joe")).isFalse();
}

代码示例来源:origin: macrozheng/mall

@Override
public UmsMember getCurrentMember() {
  SecurityContext ctx = SecurityContextHolder.getContext();
  Authentication auth = ctx.getAuthentication();
  MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
  return memberDetails.getUmsMember();
}

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

/**
 * Determines if a user is already authenticated.
 * @return
 */
private boolean authenticated() {
  Authentication authentication = SecurityContextHolder.getContext()
      .getAuthentication();
  return authentication != null && authentication.isAuthenticated()
      && !(authentication instanceof AnonymousAuthenticationToken);
}

代码示例来源: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

private String principal() {
    if ( SecurityContextHolder.getContext().getAuthentication() != null ) {
      return SecurityContextHolder.getContext().getAuthentication().getName();
    }
    return null;
  }
}

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

/**
   * @see org.springframework.ldap.core.AuthenticationSource#getCredentials()
   */
  public String getCredentials() {
    Authentication authentication = SecurityContextHolder.getContext()
        .getAuthentication();

    if (authentication == null) {
      log.warn("No Authentication object set in SecurityContext - returning empty String as Credentials");
      return "";
    }

    return (String) authentication.getCredentials();
  }
}

代码示例来源: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"));
  }
}

相关文章