hudson.model.User.impersonate()方法的使用及代码示例

x33g5p2x  于2022-01-31 转载在 其他  
字(12.2k)|赞(0)|评价(0)|浏览(114)

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

User.impersonate介绍

[英]Creates an Authentication object that represents this user.

This method checks with SecurityRealm if the user is a valid user that can login to the security realm. If SecurityRealm is a kind that does not support querying information about other users, this will use LastGrantedAuthoritiesProperty to pick up the granted authorities as of the last time the user has logged in.
[中]创建代表此用户的身份验证对象。
此方法使用SecurityRealm检查用户是否是可以登录到安全领域的有效用户。如果SecurityRealm不支持查询有关其他用户的信息,则将使用LastGrantedAuthorities属性获取用户上次登录时授予的权限。

代码示例

代码示例来源:origin: jenkinsci/jenkins

/**
 * Creates an {@link Authentication} object that represents this user.
 * <p>
 * This method checks with {@link SecurityRealm} if the user is a valid user that can login to the security realm.
 * If {@link SecurityRealm} is a kind that does not support querying information about other users, this will
 * use {@link LastGrantedAuthoritiesProperty} to pick up the granted authorities as of the last time the user has
 * logged in.
 *
 * @throws UsernameNotFoundException If this user is not a valid user in the backend {@link SecurityRealm}.
 * @since 1.419
 */
public @Nonnull
Authentication impersonate() throws UsernameNotFoundException {
  return this.impersonate(this.getUserDetailsForImpersonation());
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Changes the {@link Authentication} associated with the current thread to the specified one and returns an
 * {@link AutoCloseable} that restores the previous security context.
 *
 * <p>
 * This makes impersonation much easier within code as it can now be used using the try with resources construct:
 * <pre>
 *     try (ACLContext ctx = ACL.as(auth)) {
 *        ...
 *     }
 * </pre>
 *
 * @param user the user to impersonate.
 * @return the previous authentication context
 * @since 2.14
 */
@Nonnull
public static ACLContext as(@CheckForNull User user) {
  return as(user == null ? Jenkins.ANONYMOUS : user.impersonate());
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Note: if the token does not exist or does not match, we do not use {@link SecurityListener#fireFailedToAuthenticate(String)}
 * because it will be done in the {@link BasicHeaderRealPasswordAuthenticator} in the case the password is not valid either
 */
@Override
public Authentication authenticate(HttpServletRequest req, HttpServletResponse rsp, String username, String password) throws ServletException {
  User u = BasicApiTokenHelper.isConnectingUsingApiToken(username, password);
  if(u != null) {
    Authentication auth;
    try {
      UserDetails userDetails = u.getUserDetailsForImpersonation();
      auth = u.impersonate(userDetails);
      SecurityListener.fireAuthenticated(userDetails);
    } catch (UsernameNotFoundException x) {
      // The token was valid, but the impersonation failed. This token is clearly not his real password,
      // so there's no point in continuing the request processing. Report this error and abort.
      LOGGER.log(WARNING, "API token matched for user " + username + " but the impersonation failed", x);
      throw new ServletException(x);
    } catch (DataAccessException x) {
      throw new ServletException(x);
    }
    req.setAttribute(BasicHeaderApiTokenAuthenticator.class.getName(), true);
    return auth;
  }
  return null;
}

代码示例来源:origin: jenkinsci/jenkins

Authentication authentication;
try {
  authentication = impersonate();
} catch (UsernameNotFoundException x) {
  LOGGER.log(Level.FINE, "cannot look up authorities for " + id, x);

代码示例来源:origin: jenkinsci/jenkins

if(u != null){
  UserDetails userDetails = u.getUserDetailsForImpersonation();
  Authentication auth = u.impersonate(userDetails);

代码示例来源:origin: jenkinsci/workflow-cps-plugin

@Override public Authentication getAuthentication() {
  if (user == null) {
    return ACL.SYSTEM;
  }
  try {
    User u = User.getById(user, true);
    if (u == null) {
      return Jenkins.ANONYMOUS;
    } else {
      return u.impersonate();
    }
  } catch (UsernameNotFoundException x) {
    LOGGER.log(Level.WARNING, "could not restore authentication", x);
    // Should not expose this to callers.
    return Jenkins.ANONYMOUS;
  }
}

代码示例来源:origin: org.jenkins-ci.main/jenkins-core

/**
 * Changes the {@link Authentication} associated with the current thread to the specified one and returns an
 * {@link AutoCloseable} that restores the previous security context.
 *
 * <p>
 * This makes impersonation much easier within code as it can now be used using the try with resources construct:
 * <pre>
 *     try (ACLContext ctx = ACL.as(auth)) {
 *        ...
 *     }
 * </pre>
 *
 * @param user the user to impersonate.
 * @return the previous authentication context
 * @since 2.14
 */
@Nonnull
public static ACLContext as(@CheckForNull User user) {
  return as(user == null ? Jenkins.ANONYMOUS : user.impersonate());
}

代码示例来源:origin: jenkinsci/instant-messaging-plugin

@Override
  public Authentication getAuthentication() {
    if (authentication != null) {
      return authentication;
    }
    
    User u = User.get(descriptor.getHudsonUserName());
    return u.impersonate();
  }
};

代码示例来源:origin: jenkinsci/jenkins-test-harness

/**
 * Run the command as a given username.
 * Test setup should have first defined a meaningful security realm and authorization strategy.
 * @see Jenkins#setSecurityRealm
 * @see JenkinsRule#createDummySecurityRealm
 * @see Jenkins#setAuthorizationStrategy
 * @see MockAuthorizationStrategy
 */
public CLICommandInvoker asUser(String user) {
  command.setTransportAuth(User.get(user).impersonate());
  return this;
}

代码示例来源:origin: org.jenkins-ci.main/jenkins-core

@Override
public Authentication authenticate(HttpServletRequest req, HttpServletResponse rsp, String username, String password) throws ServletException {
  // attempt to authenticate as API token
  User u = User.getById(username, true);
  ApiTokenProperty t = u.getProperty(ApiTokenProperty.class);
  if (t!=null && t.matchesPassword(password)) {
    try {
      return u.impersonate();
    } catch (UsernameNotFoundException x) {
      // The token was valid, but the impersonation failed. This token is clearly not his real password,
      // so there's no point in continuing the request processing. Report this error and abort.
      LOGGER.log(WARNING, "API token matched for user "+username+" but the impersonation failed",x);
      throw new ServletException(x);
    } catch (DataAccessException x) {
      throw new ServletException(x);
    }
  }
  return null;
}

代码示例来源:origin: org.jenkins-ci.plugins/security-inspector

@Override
public void forRow(User user, Runnable runnable) {
  final Authentication auth;
  try {
    auth = user.impersonate();
  } catch (UsernameNotFoundException ex) {
    fillRowByResult(user, Boolean.FALSE);
    return;
  }
  
  SecurityContext initialContext = null;
  try {
    initialContext = hudson.security.ACL.impersonate(auth);
    runnable.run();
  } finally {
    if (initialContext != null) {
      SecurityContextHolder.setContext(initialContext);
    }
  }
}

代码示例来源:origin: jenkinsci/mercurial-plugin

private void assertCredentials(String user, final Job<?,?> owner, Credentials... expected) {
  final List<String> expectedNames = new ArrayList<String>();
  for (Credentials c : expected) {
    expectedNames.add(CredentialsNameProvider.name(c));
  }
  ACL.impersonate(User.get(user).impersonate(), new Runnable() {
    @Override public void run() {
      List<String> actualNames = new ArrayList<String>();
      for (ListBoxModel.Option o : r.jenkins.getDescriptorByType(MercurialSCM.DescriptorImpl.class).doFillCredentialsIdItems(owner, "http://nowhere.net/")) {
        if (o.value.isEmpty()) {
          continue; // AbstractIdCredentialsListBoxModel.EmptySelection
        }
        actualNames.add(o.name);
      }
      assertEquals(expectedNames, actualNames);
    }
  });
}

代码示例来源:origin: jenkinsci/pipeline-model-definition-plugin

private static boolean canRestart(WorkflowRun b, String user) {
  final RestartDeclarativePipelineAction a = b.getAction(RestartDeclarativePipelineAction.class);
  return ACL.impersonate(User.get(user).impersonate(), new NotReallyRoleSensitiveCallable<Boolean,RuntimeException>() {
    @Override public Boolean call() throws RuntimeException {
      return a.isRestartEnabled();
    }
  });
}

代码示例来源:origin: jenkinsci/workflow-multibranch-plugin

private static boolean canReplay(WorkflowRun b, String user) {
  final ReplayAction a = b.getAction(ReplayAction.class);
  return ACL.impersonate(User.get(user).impersonate(), new NotReallyRoleSensitiveCallable<Boolean,RuntimeException>() {
    @Override public Boolean call() throws RuntimeException {
      return a.isEnabled();
    }
  });
}

代码示例来源:origin: jenkinsci/jenkins-test-harness

private void setAuth() {
  if (permissions.isEmpty()) return;
  JenkinsRule.DummySecurityRealm realm = rule.createDummySecurityRealm();
  realm.addGroups(username, "group");
  originalSecurityRealm = rule.jenkins.getSecurityRealm();
  rule.jenkins.setSecurityRealm(realm);
  originalAuthorizationStrategy = rule.jenkins.getAuthorizationStrategy();
  rule.jenkins.setAuthorizationStrategy(new GrantPermissions(username, permissions));
  command.setTransportAuth(user().impersonate());
  // Otherwise it is SYSTEM, which would be relevant for a command overriding main:
  originalSecurityContext = ACL.impersonate(Jenkins.ANONYMOUS);
}

代码示例来源:origin: org.jenkins-ci.plugins/security-inspector

@Override
protected Boolean getEntryReport(Computer column, Permission item) {
  
  final Authentication auth;
  try {
    auth = user4report.impersonate();
  } catch (UsernameNotFoundException ex) {
    return Boolean.FALSE;
  }
  
  SecurityContext initialContext = null;
  AuthorizationStrategy strategy = JenkinsHelper.getInstanceOrFail().getAuthorizationStrategy();
  try {
    initialContext = hudson.security.ACL.impersonate(auth);
    return strategy.getACL(column).hasPermission(item);
  } finally {
    if (initialContext != null) {
      SecurityContextHolder.setContext(initialContext);
    }
  }
}

代码示例来源:origin: jenkinsci/mercurial-plugin

@Test public void doFillCredentialsIdItemsWithoutJobWhenAdmin() throws Exception {
  r.jenkins.setSecurityRealm(r.createDummySecurityRealm());
  ProjectMatrixAuthorizationStrategy as = new ProjectMatrixAuthorizationStrategy();
  as.add(Jenkins.ADMINISTER, "alice");
  r.jenkins.setAuthorizationStrategy(as);
  final UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null, "test", "bob", "s3cr3t");
  CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c);
  ACL.impersonate(User.get("alice").impersonate(), new Runnable() {
    @Override public void run() {
      ListBoxModel options = r.jenkins.getDescriptorByType(MercurialSCM.DescriptorImpl.class).doFillCredentialsIdItems(null, "http://nowhere.net/");
      assertEquals(CredentialsNameProvider.name(c), options.get(1).name);
    }
  });
}

代码示例来源:origin: jenkinsci/pipeline-model-definition-plugin

@Test
public void invalidUser() throws Exception {
  File testPath = writeJenkinsfileToTmpFile("simplePipeline");
  j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
  j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy()
      .grant(Jenkins.ADMINISTER).everywhere().to("bob")
      .grant(Jenkins.READ,
          Item.READ,
          Item.EXTENDED_READ).everywhere().to("alice"));
  final CLICommandInvoker.Result result = command.withStdin(FileUtils.openInputStream(testPath)).invoke();
  assertThat(result, not(succeeded()));
  assertThat(result.stderr(), containsString("ERROR: anonymous is missing the Overall/Read permission"));
  declarativeLinterCommand.setTransportAuth(User.get("alice").impersonate());
  final CLICommandInvoker.Result result2 = command.withStdin(FileUtils.openInputStream(testPath)).invoke();
  assertThat(result2, succeeded());
  assertThat(result2, hasNoErrorOutput());
  assertThat(result2.stdout(), containsString("Jenkinsfile successfully validated."));
}

代码示例来源:origin: jenkinsci/workflow-cps-plugin

@Override public void evaluate() throws Throwable {
    jenkins().setSecurityRealm(story.j.createDummySecurityRealm());
    jenkins().save();
    QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new MockQueueItemAuthenticator(Collections.singletonMap("demo", User.getById("someone", true).impersonate())));
    p = jenkins().createProject(WorkflowJob.class, "demo");
    p.setDefinition(new CpsFlowDefinition("echo \"ran as ${auth()}\"", true));
    b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0));
    story.j.assertLogContains("ran as someone", b);
  }
});

代码示例来源:origin: jenkinsci/workflow-cps-plugin

@Override public void evaluate() throws Throwable {
    jenkins().setSecurityRealm(story.j.createDummySecurityRealm());
    jenkins().save();
    QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new MockQueueItemAuthenticator(Collections.singletonMap("demo", User.getById("someone", true).impersonate())));
    p = jenkins().createProject(WorkflowJob.class, "demo");
    p.setDefinition(new CpsFlowDefinition("checkAuth()", false));
    ScriptApproval.get().preapproveAll();
    startBuilding();
    waitForWorkflowToSuspend();
    assertTrue(b.isBuilding());
    story.j.waitForMessage("running as someone", b);
    CheckAuth.finish(false);
    waitForWorkflowToSuspend();
    assertTrue(b.isBuilding());
    story.j.waitForMessage("still running as someone", b);
  }
});

相关文章