hudson.security.ACL.impersonate()方法的使用及代码示例

x33g5p2x  于11个月前 转载在 其他  
字(10.4k)|赞(0)|评价(0)|浏览(37)

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

ACL.impersonate介绍

[英]Changes the Authentication associated with the current thread to the specified one, and returns the previous security context.

When the impersonation is over, be sure to restore the previous authentication via SecurityContextHolder.setContext(returnValueFromThisMethod); or just use #impersonate(Authentication,Runnable).

We need to create a new SecurityContext instead of SecurityContext#setAuthentication(Authentication)because the same SecurityContext object is reused for all the concurrent requests from the same session.
[中]将与当前线程关联的身份验证更改为指定的身份验证,并返回以前的安全上下文。
模拟结束后,请确保通过SecurityContextHolder恢复以前的身份验证。setContext(returnValueFromThisMethod);或者只使用#模拟(身份验证,可运行)。
我们需要创建一个新的SecurityContext,而不是SecurityContext#setAuthentication(身份验证),因为同一个SecurityContext对象可用于来自同一会话的所有并发请求。

代码示例

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

/**
 * Safer variant of {@link #impersonate(Authentication)} that does not require a finally-block.
 * @param auth authentication, such as {@link #SYSTEM}
 * @param body an action to run with this alternate authentication in effect
 * @since 1.509
 * @deprecated use try with resources and {@link #as(Authentication)}
 */
@Deprecated
public static void impersonate(@Nonnull Authentication auth, @Nonnull Runnable body) {
  SecurityContext old = impersonate(auth);
  try {
    body.run();
  } finally {
    SecurityContextHolder.setContext(old);
  }
}

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

protected void success(HttpServletRequest req, HttpServletResponse rsp, FilterChain chain, Authentication auth) throws IOException, ServletException {
  rememberMeServices.loginSuccess(req, rsp, auth);
  SecurityContext old = ACL.impersonate(auth);
  try {
    chain.doFilter(req,rsp);
  } finally {
    SecurityContextHolder.setContext(old);
  }
}

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

public final void run() {
  // background activity gets system credential,
  // just like executors get it.
  SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM);
  try {
    doRun();
  } catch(Throwable t) {
    LOGGER.log(Level.SEVERE, "Timer task "+this+" failed",t);
  } finally {
    SecurityContextHolder.setContext(oldContext);
  }
}

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

@Override
  public void run() {
    try {
      ACL.impersonate(ACL.SYSTEM);
      LOGGER.info(String.format("Shutting down VM as requested by %s from %s",
                    exitUser, exitAddr));
      // Wait 'til we have no active executors.
      doQuietDown(true, 0);
      // Make sure isQuietingDown is still true.
      if (isQuietingDown) {
        cleanUp();
        System.exit(0);
      }
    } catch (Exception e) {
      LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e);
    }
  }
}.start();

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

@Override
  public void run() {
    try {
      ACL.impersonate(ACL.SYSTEM);
      // give some time for the browser to load the "reloading" page
      Thread.sleep(5000);
      LOGGER.info(String.format("Restarting VM as requested by %s",exitUser));
      for (RestartListener listener : RestartListener.all())
        listener.onRestart();
      lifecycle.restart();
    } catch (InterruptedException | IOException e) {
      LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
    }
  }
}.start();

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

/**
 * Safer variant of {@link #impersonate(Authentication)} that does not require a finally-block.
 * @param auth authentication, such as {@link #SYSTEM}
 * @param body an action to run with this alternate authentication in effect (try {@link NotReallyRoleSensitiveCallable})
 * @since 1.587
 * @deprecated use try with resources and {@link #as(Authentication)}
 */
@Deprecated
public static <V,T extends Exception> V impersonate(Authentication auth, Callable<V,T> body) throws T {
  SecurityContext old = impersonate(auth);
  try {
    return body.call();
  } finally {
    SecurityContextHolder.setContext(old);
  }
}

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

@Override
  public void run() {
    try {
      ACL.impersonate(ACL.SYSTEM);
      LOGGER.info(String.format("Shutting down VM as requested by %s from %s",
          getAuthentication().getName(), req != null ? req.getRemoteAddr() : "???"));
      cleanUp();
      System.exit(0);
    } catch (Exception e) {
      LOGGER.log(Level.WARNING, "Failed to shut down Jenkins", e);
    }
  }
}.start();

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

@Override
  public void run() {
    try {
      ACL.impersonate(ACL.SYSTEM);
      reload();
    } catch (Exception e) {
      LOGGER.log(SEVERE,"Failed to reload Jenkins config",e);
      new JenkinsReloadFailed(e).publish(servletContext,root);
    }
  }
}.start();

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

@Override
  public void run() {
    try {
      ACL.impersonate(ACL.SYSTEM);
      // Wait 'til we have no active executors.
      doQuietDown(true, 0);
      // Make sure isQuietingDown is still true.
      if (isQuietingDown) {
        servletContext.setAttribute("app",new HudsonIsRestarting());
        // give some time for the browser to load the "reloading" page
        LOGGER.info("Restart in 10 seconds");
        Thread.sleep(10000);
        LOGGER.info(String.format("Restarting VM as requested by %s",exitUser));
        for (RestartListener listener : RestartListener.all())
          listener.onRestart();
        lifecycle.restart();
      } else {
        LOGGER.info("Safe-restart mode cancelled");
      }
    } catch (Throwable e) {
      LOGGER.log(Level.WARNING, "Failed to restart Jenkins",e);
    }
  }
}.start();

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

/**
 * Sets the thread name to the task for better diagnostics.
 */
@Override
protected void runTask(Task task) throws Exception {
  if (is!=null && is.skipInitTask(task))  return;
  ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
  String taskName = InitReactorRunner.getDisplayName(task);
  Thread t = Thread.currentThread();
  String name = t.getName();
  if (taskName !=null)
    t.setName(taskName);
  try {
    long start = System.currentTimeMillis();
    super.runTask(task);
    if(LOG_STARTUP_PERFORMANCE)
      LOGGER.info(String.format("Took %dms for %s by %s",
          System.currentTimeMillis()-start, taskName, name));
  } catch (Exception | Error x) {
    if (containsLinkageError(x)) {
      LOGGER.log(Level.WARNING, taskName + " failed perhaps due to plugin dependency issues", x);
    } else {
      throw x;
    }
  } finally {
    t.setName(name);
    SecurityContextHolder.clearContext();
  }
}
private boolean containsLinkageError(Throwable x) {

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

public static <T> T impersonate(Authentication auth, final Function<T> function) {
  final ObjectHolder<T> holder = new ObjectHolder<T>();
  ACL.impersonate(auth, new Runnable() {
    public void run() {
      holder.setValue(function.invoke());
    }
  });
  return holder.getValue();
}

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

public void run() {
  SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM);
  try {
    Set<AbstractProject> topLevelProjects = new HashSet<AbstractProject>();
    // Get all top-level projects
    LOGGER.fine("assembling top level projects");
    for (AbstractProject p : Jenkins.getInstance().allItems(AbstractProject.class))
      if (p.getUpstreamProjects().size() == 0) {
        LOGGER.fine("adding top level project " + p.getName());
        topLevelProjects.add(p);
      } else {
        LOGGER.fine("skipping project since not a top level project: " + p.getName());
      }
    populate(topLevelProjects);
    for (AbstractProject p : polledProjects) {
        LOGGER.fine("running project in correct dependency order: " + p.getName());
      runnable.run(p);
    }
  } finally {
    SecurityContextHolder.setContext(oldContext);
  }
}

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

private static void remove(Saveable obj, boolean isDelete) {
  Jenkins j = Jenkins.getInstance();
  OldDataMonitor odm = get(j);
  SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM);
  try {
    odm.data.remove(referTo(obj));
    if (isDelete && obj instanceof Job<?, ?>) {
      for (Run r : ((Job<?, ?>) obj).getBuilds()) {
        odm.data.remove(referTo(r));
      }
    }
  } finally {
    SecurityContextHolder.setContext(oldContext);
  }
}

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

public void run() {
    logger.log(getNormalLoggingLevel(), "Started {0}", name);
    long startTime = System.currentTimeMillis();
    long stopTime;
    StreamTaskListener l = createListener();
    try {
      l.getLogger().printf("Started at %tc%n", new Date(startTime));
      ACL.impersonate(ACL.SYSTEM);
      execute(l);
    } catch (IOException e) {
      Functions.printStackTrace(e, l.fatalError(e.getMessage()));
    } catch (InterruptedException e) {
      Functions.printStackTrace(e, l.fatalError("aborted"));
    } finally {
      stopTime = System.currentTimeMillis();
      try {
        l.getLogger().printf("Finished at %tc. %dms%n", new Date(stopTime), stopTime - startTime);
      } finally {
        l.closeQuietly();
      }
    }
    logger.log(getNormalLoggingLevel(), "Finished {0}. {1,number} ms",
        new Object[]{name, stopTime - startTime});
  }
},name+" thread");

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

public void run() {
    logger.log(getNormalLoggingLevel(), "Started {0}", name);
    long startTime = System.currentTimeMillis();
    long stopTime;
    StreamTaskListener l = createListener();
    try {
      l.getLogger().printf("Started at %tc%n", new Date(startTime));
      ACL.impersonate(ACL.SYSTEM);
      execute(l);
    } catch (IOException e) {
      Functions.printStackTrace(e, l.fatalError(e.getMessage()));
    } catch (InterruptedException e) {
      Functions.printStackTrace(e, l.fatalError("aborted"));
    } finally {
      stopTime = System.currentTimeMillis();
      try {
        l.getLogger().printf("Finished at %tc. %dms%n", new Date(stopTime), stopTime - startTime);
      } finally {
        l.closeQuietly();
      }
    }
    logger.log(getNormalLoggingLevel(), "Finished {0}. {1,number} ms",
        new Object[]{name, stopTime - startTime});
  }
},name+" thread");

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

@Override
public void run() {
  ACL.impersonate(ACL.SYSTEM);
  StreamTaskListener listener = null;
  try {
    listener = new StreamTaskListener(getLogFile());
    try {
      doRun(listener);
    } finally {
      listener.close();
    }
  } catch (IOException ex) {
    if (listener == null) {
      LOGGER.log(Level.SEVERE, "Cannot create listener for " + getName(), ex);
      //TODO: throw IllegalStateException?
    } else {
      LOGGER.log(Level.WARNING, "Cannot close listener for " + getName(), ex);
    }
  }
 }

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

void execute() {
  if (!(project instanceof Job<?, ?>)) {
    throw HttpResponses.errorWithoutStack(409, "Pipeline Hook is not supported for this project");
  }
  ACL.impersonate(ACL.SYSTEM, new TriggerNotifier(project, secretToken, Jenkins.getAuthentication()) {
    @Override
    protected void performOnPost(GitLabPushTrigger trigger) {
      trigger.onPost(pipelineBuildHook);
    }
  });
  throw HttpResponses.ok();
}

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

public void build() {
  // Set full privileges while computing to avoid missing any projects the current user cannot see.
  SecurityContext saveCtx = ACL.impersonate(ACL.SYSTEM);
  try {
    this.computationalData = new HashMap<Class<?>, Object>();
    for( AbstractProject p : Jenkins.getInstance().allItems(AbstractProject.class) )
      p.buildDependencyGraph(this);
    forward = finalize(forward);
    backward = finalize(backward);
    topologicalDagSort();
    this.computationalData = null;
    built = true;
  } finally {
    SecurityContextHolder.setContext(saveCtx);
  }
}

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

SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM);
try {
  pw.doPin();

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

Authentication auth = Tasks.getAuthenticationOf((Queue.Task) job);
SecurityContext orig = ACL.impersonate(auth);
Item authUpstream = null;
try {

相关文章