Java Code Examples for org.acegisecurity.context.SecurityContextHolder#setContext()
The following examples show how to use
org.acegisecurity.context.SecurityContextHolder#setContext() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AcegiSafeSessionFilter.java From Android_Code_Arbiter with GNU Lesser General Public License v3.0 | 6 votes |
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if(1 + 1 == 2) { SecurityContext oldCtx = SecurityContextHolder.getContext(); SecurityContextHolder.setContext(null); // try { super.doFilter(req, res, chain); } finally { SecurityContextHolder.setContext(oldCtx); } } else { super.doFilter(req, res, chain); } }
Example 2
Source File: CLICommandInvoker.java From jenkins-test-harness with MIT License | 6 votes |
private void restoreAuth() { if (originalSecurityRealm != null) { rule.jenkins.setSecurityRealm(originalSecurityRealm); originalSecurityRealm = null; } if (originalAuthorizationStrategy != null) { rule.jenkins.setAuthorizationStrategy(originalAuthorizationStrategy); originalAuthorizationStrategy = null; } if (originalSecurityContext != null) { SecurityContextHolder.setContext(originalSecurityContext); originalSecurityContext = null; } }
Example 3
Source File: BuildStatus.java From jenkins-status-badges-plugin with MIT License | 6 votes |
public Job<?, ?> getProject( String job, StaplerRequest req, StaplerResponse rsp ) throws HttpResponses.HttpResponseException { Job<?, ?> p; SecurityContext orig = ACL.impersonate( ACL.SYSTEM ); try { p = Jenkins.getInstance().getItemByFullName( job, Job.class ); } finally { SecurityContextHolder.setContext( orig ); } if ( p == null ) { throw org.kohsuke.stapler.HttpResponses.notFound(); } return p; }
Example 4
Source File: JwtAuthenticationFilter.java From blueocean-plugin with MIT License | 5 votes |
@Override public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; if(!shouldApply(request)) { chain.doFilter(req,rsp); return; } Authentication token = verifyToken(request); if(token==null) { // no JWT token found, which is fine --- we just assume the request is authenticated in other means // Some routes that require valid JWT token will check for the presence of JWT token during Stapler // request routing, not here. chain.doFilter(req,rsp); return; } // run the rest of the request with the new identity // create a new context and set it to holder to not clobber existing context SecurityContext sc = new SecurityContextImpl(); sc.setAuthentication(token); SecurityContext previous = SecurityContextHolder.getContext(); SecurityContextHolder.setContext(sc); request.setAttribute(JWT_TOKEN_VALIDATED,true); try { chain.doFilter(req,rsp); } finally { if(previous != null){ SecurityContextHolder.setContext(previous); }else { SecurityContextHolder.clearContext(); } } }
Example 5
Source File: GithubServerContainer.java From blueocean-plugin with MIT License | 4 votes |
public @CheckForNull ScmServerEndpoint create(@JsonBody JSONObject request) { List<ErrorMessage.Error> errors = Lists.newLinkedList(); // Validate name final String name = (String) request.get(GithubServer.NAME); if (StringUtils.isEmpty(name)) { errors.add(new ErrorMessage.Error(GithubServer.NAME, ErrorMessage.Error.ErrorCodes.MISSING.toString(), GithubServer.NAME + " is required")); } else { GithubServer byName = findByName(name); if (byName != null) { errors.add(new ErrorMessage.Error(GithubServer.NAME, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.NAME + " already exists for server at '" + byName.getApiUrl() + "'")); } } // Validate url final String url = (String) request.get(GithubServer.API_URL); if (StringUtils.isEmpty(url)) { errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.MISSING.toString(), GithubServer.API_URL + " is required")); } else { Endpoint byUrl = GitHubConfiguration.get().findEndpoint(url); if (byUrl != null) { errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.API_URL + " is already registered as '" + byUrl.getName() + "'")); } } if (StringUtils.isNotEmpty(url)) { // Validate that the URL represents a GitHub API endpoint try { HttpURLConnection connection = HttpRequest.get(url).connect(); if (connection.getHeaderField("X-GitHub-Request-Id") == null) { errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), ERROR_MESSAGE_INVALID_SERVER)); } else { boolean isGithubCloud = false; boolean isGithubEnterprise = false; try { InputStream inputStream; int code = connection.getResponseCode(); if (200 <= code && code < 300) { inputStream = HttpRequest.getInputStream(connection); } else { inputStream = HttpRequest.getErrorStream(connection); } TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>(){}; Map<String, String> responseBody = GithubScm.getMappingObjectReader().forType(typeRef).readValue(inputStream); isGithubCloud = code == 200 && responseBody.containsKey("current_user_url"); isGithubEnterprise = code == 401 && responseBody.containsKey("message"); } catch (IllegalArgumentException | IOException ioe) { LOGGER.log(Level.INFO, "Could not parse response body from Github"); } if (!isGithubCloud && !isGithubEnterprise) { errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), ERROR_MESSAGE_INVALID_APIURL)); } } } catch (Throwable e) { errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), e.toString())); LOGGER.log(Level.INFO, "Could not connect to Github", e); } } if (errors.isEmpty()) { SecurityContext old = null; try { // We need to escalate privilege to add user defined endpoint to old = ACL.impersonate(ACL.SYSTEM); GitHubConfiguration config = GitHubConfiguration.get(); String sanitizedUrl = discardQueryString(url); Endpoint endpoint = new Endpoint(sanitizedUrl, name); if (!config.addEndpoint(endpoint)) { errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.API_URL + " is already registered as '" + endpoint.getName() + "'")); } else { return new GithubServer(endpoint, getLink()); } }finally { //reset back to original privilege level if(old != null){ SecurityContextHolder.setContext(old); } } } ErrorMessage message = new ErrorMessage(400, "Failed to create GitHub server"); message.addAll(errors); throw new ServiceException.BadRequestException(message); }
Example 6
Source File: GogsPayloadProcessor.java From gogs-webhook-plugin with MIT License | 4 votes |
public GogsResults triggerJobs(String jobName, String deliveryID) { SecurityContext saveCtx = ACL.impersonate(ACL.SYSTEM); GogsResults result = new GogsResults(); try { BuildableItem project = GogsUtils.find(jobName, BuildableItem.class); if (project != null) { GogsTrigger gTrigger = null; Cause cause = new GogsCause(deliveryID); if (project instanceof ParameterizedJobMixIn.ParameterizedJob) { ParameterizedJobMixIn.ParameterizedJob pJob = (ParameterizedJobMixIn.ParameterizedJob) project; for (Trigger trigger : pJob.getTriggers().values()) { if (trigger instanceof GogsTrigger) { gTrigger = (GogsTrigger) trigger; break; } } } if (gTrigger != null) { SCMTriggerItem item = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(project); GogsPayload gogsPayload = new GogsPayload(this.payload); if (item != null) { item.scheduleBuild2(0, gogsPayload); } } else { project.scheduleBuild(0, cause); } result.setMessage(String.format("Job '%s' is executed", jobName)); } else { String msg = String.format("Job '%s' is not defined in Jenkins", jobName); result.setStatus(404, msg); LOGGER.warning(msg); } } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); LOGGER.severe(sw.toString()); } finally { SecurityContextHolder.setContext(saveCtx); } return result; }
Example 7
Source File: JobRunnerForCause.java From github-integration-plugin with MIT License | 4 votes |
/** * Cancel previous builds for specified PR id. */ public int cancelQueuedBuildByPrNumber(final int id) { int canceled = 0; SecurityContext old = impersonate(ACL.SYSTEM); try { final Queue queue = getJenkinsInstance().getQueue(); final Queue.Item[] items = queue.getItems(); //todo replace with stream? for (Queue.Item item : items) { if (!(item.task instanceof Job)) { LOGGER.debug("Item {} not instanceof job", item); continue; } final Job<?, ?> jobTask = (Job<?, ?>) item.task; if (!jobTask.getFullName().equals(job.getFullName())) { LOGGER.debug("{} != {}", jobTask.getFullName(), job.getFullName()); continue; } final CauseAction action = item.getAction(CauseAction.class); if (isNull(action)) { LOGGER.debug("Cause action is null for {}", jobTask.getFullName()); continue; } Optional<Cause> cause = from(action.getCauses()) .filter(instanceOf(GitHubPRCause.class)) .firstMatch(new CauseHasPRNum(id)); if (cause.isPresent()) { LOGGER.debug("Cancelling {}", item); queue.cancel(item); canceled++; } } } finally { SecurityContextHolder.setContext(old); } return canceled; }
Example 8
Source File: MongoRepositoryTest.java From DotCi with MIT License | 4 votes |
private GHRepository setupMockGHRepository() throws Exception { GHRepository ghRepository = PowerMockito.mock(GHRepository.class); PowerMockito.whenNew(GHRepository.class).withNoArguments().thenReturn(ghRepository); PowerMockito.when(ghRepository.getHooks()).thenReturn(new ArrayList<GHHook>()); PowerMockito.when(ghRepository.getHtmlUrl()).thenReturn(new URL("https://github.com/groupon/DotCi")); GHHook hook = PowerMockito.mock(GHHook.class); PowerMockito.when(ghRepository.createHook("web", new HashMap<String, String>() {{ put("url", "http://localhost/githook/"); }}, Arrays.asList(GHEvent.PUSH, GHEvent.PULL_REQUEST), true)).thenReturn(hook); PowerMockito.when(ghRepository.isPrivate()).thenReturn(true); PowerMockito.when(ghRepository.getDeployKeys()).thenReturn(new ArrayList<GHDeployKey>()); PowerMockito.when(ghRepository.addDeployKey("DotCi", null)).thenReturn(null); PowerMockito.when(ghRepository.getName()).thenReturn("repo_name"); GHUser ghUser = PowerMockito.mock(GHUser.class); PowerMockito.when(ghUser.getLogin()).thenReturn("theusername"); PowerMockito.when(ghRepository.getOwner()).thenReturn(ghUser); String dotCiYaml = "environment:\n language: ruby\n\nbuild:\n before: echo \"get out of here denton\"\n run:\n unit: echo \"Unit test\"\n integration: echo \"Integration test\"\n after: echo it works right\n"; GHContent content = PowerMockito.mock(GHContent.class); PowerMockito.when(content.getContent()).thenReturn(dotCiYaml); PowerMockito.when(ghRepository.getFileContent(".ci.yml", "thisisasha")).thenReturn(content); GHRef ghRef = PowerMockito.mock(GHRef.class); GHRef.GHObject ghObject = PowerMockito.mock(GHRef.GHObject.class); PowerMockito.when(ghObject.getSha()).thenReturn("thisisasha"); PowerMockito.when(ghRef.getObject()).thenReturn(ghObject); PowerMockito.when(ghRepository.getRef("heads/master")).thenReturn(ghRef); GHMyself myself = PowerMockito.mock(GHMyself.class); PowerMockito.when(myself.getLogin()).thenReturn("someloginstuff"); PowerMockito.mockStatic(GitHub.class); GitHub github = PowerMockito.mock(GitHub.class); //PowerMockito.when(GitHub.connectUsingOAuth("https://localhost/api/v3", "thisismytoken")).thenReturn(github); PowerMockito.when(github.getMyself()).thenReturn(myself); PowerMockito.when(github.getRepository("groupon/DotCi")).thenReturn(ghRepository); SecurityContext context = PowerMockito.mock(SecurityContext.class); // PowerMockito.when(context.getAuthentication()).thenReturn(token); SecurityContextHolder.setContext(context); return ghRepository; }