Java Code Examples for jenkins.model.Jenkins#getAuthentication()
The following examples show how to use
jenkins.model.Jenkins#getAuthentication() .
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: SSHStepExecution.java From ssh-steps-plugin with Apache License 2.0 | 6 votes |
@Override public final boolean start() { Authentication auth = Jenkins.getAuthentication(); task = getExecutorService().submit(() -> { threadName = Thread.currentThread().getName(); try { MDC.put("execution.id", UUID.randomUUID().toString()); T ret; try (ACLContext acl = ACL.as(auth)) { ret = run(); } getContext().onSuccess(ret); } catch (Throwable x) { if (stopCause == null) { getContext().onFailure(x); } else { stopCause.addSuppressed(x); } } finally { MDC.clear(); } }); return false; }
Example 2
Source File: AbstractPipelineCreateRequest.java From blueocean-plugin with MIT License | 6 votes |
protected @Nonnull TopLevelItem createProject(String name, String descriptorName, Class<? extends TopLevelItemDescriptor> descriptorClass, BlueOrganization organization) throws IOException { ModifiableTopLevelItemGroup p = getParent(organization); final ACL acl = (p instanceof AccessControlled) ? ((AccessControlled) p).getACL() : Jenkins.getInstance().getACL(); Authentication a = Jenkins.getAuthentication(); if(!acl.hasPermission(a, Item.CREATE)){ throw new ServiceException.ForbiddenException( String.format("Failed to create pipeline: %s. User %s doesn't have Job create permission", name, a.getName())); } TopLevelItemDescriptor descriptor = Items.all().findByName(descriptorName); if(descriptor == null || !(descriptorClass.isAssignableFrom(descriptor.getClass()))){ throw new ServiceException.BadRequestException(String.format("Failed to create pipeline: %s, descriptor %s is not found", name, descriptorName)); } if (!descriptor.isApplicableIn(p)) { throw new ServiceException.ForbiddenException( String.format("Failed to create pipeline: %s. Pipeline can't be created in Jenkins root folder", name)); } if (!acl.hasCreatePermission(a, p, descriptor)) { throw new ServiceException.ForbiddenException("Missing permission: " + Item.CREATE.group.title+"/"+Item.CREATE.name + " " + Item.CREATE + "/" + descriptor.getDisplayName()); } return p.createProject(descriptor, name, true); }
Example 3
Source File: ScmResourceImpl.java From blueocean-plugin with MIT License | 6 votes |
private @Nonnull User checkPermission(){ ACL acl; if(item.getParent() != null && item.getParent() instanceof OrganizationFolder){ acl = ((OrganizationFolder) item.getParent()).getACL(); }else{ acl = item.getACL(); } Authentication a = Jenkins.getAuthentication(); User user = User.get(a); if(user == null){ throw new ServiceException.UnauthorizedException("No logged in user found"); } if(!acl.hasPermission(a, Item.CONFIGURE)){ throw new ServiceException.ForbiddenException( String.format("User %s must have Job configure permission to access content", a.getName())); } return user; }
Example 4
Source File: GeneralNonBlockingStepExecution.java From pipeline-maven-plugin with MIT License | 6 votes |
/** * Initiate background work that should not block the CPS VM thread. * Call this from a CPS VM thread, such as from {@link #start} or {@link BodyExecutionCallback#onSuccess}. * The block may finish by calling {@link BodyInvoker#start}, {@link StepContext#onSuccess}, etc. * @param block some code to run in a utility thread */ protected final void run(Block block) { if (stopping) { return; } final Authentication auth = Jenkins.getAuthentication(); task = GeneralNonBlockingStepExecutionUtils.getExecutorService().submit(() -> { threadName = Thread.currentThread().getName(); try { try (ACLContext acl = ACL.as(auth)) { block.run(); } } catch (Throwable e) { if (!stopping) { getContext().onFailure(e); } } finally { threadName = null; task = null; } }); }
Example 5
Source File: LockableResourcesRootAction.java From lockable-resources-plugin with MIT License | 6 votes |
public void doUnreserve(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { Jenkins.get().checkPermission(RESERVE); String name = req.getParameter("resource"); LockableResource r = LockableResourcesManager.get().fromName(name); if (r == null) { rsp.sendError(404, "Resource not found " + name); return; } String userName = getUserName(); if ((userName == null || !userName.equals(r.getReservedBy())) && !Jenkins.get().hasPermission(Jenkins.ADMINISTER)) throw new AccessDeniedException2(Jenkins.getAuthentication(), RESERVE); List<LockableResource> resources = new ArrayList<>(); resources.add(r); LockableResourcesManager.get().unreserve(resources); rsp.forwardToPreviousPage(req); }
Example 6
Source File: BlueOceanRootAction.java From blueocean-plugin with MIT License | 5 votes |
@Override public Object getTarget() { StaplerRequest request = Stapler.getCurrentRequest(); if(request.getOriginalRestOfPath().startsWith("/rest/")) { /** * If JWT is enabled, authenticate request using JWT token and set authentication context */ if (enableJWT && !JwtAuthenticationFilter.didRequestHaveValidatedJwtToken()) { throw new ServiceException.UnauthorizedException("Unauthorized: Jwt token verification failed, no valid authentication instance found"); } /** * Check overall read permission. This will make sure we have all rest api protected in case request * doesn't carry overall read permission. * * @see Jenkins#getTarget() */ Authentication a = Jenkins.getAuthentication(); if(!Jenkins.getInstance().getACL().hasPermission(a,Jenkins.READ)){ throw new ServiceException.ForbiddenException("Forbidden"); } }else{ //If user doesn't have overall Jenkins read permission then return 403, which results in classic UI redirecting // user to login page Jenkins.getInstance().checkPermission(Jenkins.READ); } // frontend uses this to determine when to reload Stapler.getCurrentResponse().setHeader("X-Blueocean-Refresher", Jenkins.SESSION_HASH); return app; }
Example 7
Source File: UserImpl.java From blueocean-plugin with MIT License | 5 votes |
@Override public BlueUserPermission getPermission() { Authentication authentication = Jenkins.getAuthentication(); String name = authentication.getName(); if(isAnonymous(name)){ return null; } User loggedInUser = User.get(name, false, Collections.EMPTY_MAP); if(loggedInUser == null){ return null; } // If this user is not logged in, we do not show it's permissions // XXX: This is done to avoid impersonation which has performance // implications, e.g. github oauth plugin might do a network // round trip to fetch user and authorizations if(!loggedInUser.getId().equals(user.getId())){ return null; } return new BlueUserPermission() { @Override public boolean isAdministration() { return isAdmin(); } @Override public Map<String, Boolean> getPipelinePermission() { return UserImpl.this.getPipelinePermissions(); } @Override public Map<String, Boolean> getCredentialPermission() { return UserImpl.this.getCredentialPermissions(); } }; }
Example 8
Source File: AbstractPipelineCreateRequest.java From blueocean-plugin with MIT License | 5 votes |
protected User checkUserIsAuthenticatedAndHasItemCreatePermission(BlueOrganization organization) { ModifiableTopLevelItemGroup p = getParent(organization); User authenticatedUser = User.current(); if (authenticatedUser == null) { throw new ServiceException.UnauthorizedException("Must be logged in to create a pipeline"); } Authentication authentication = Jenkins.getAuthentication(); ACL acl = (p instanceof AccessControlled) ? ((AccessControlled) p).getACL() : Jenkins.getInstance().getACL(); if(!acl.hasPermission(authentication, Item.CREATE)){ throw new ServiceException.ForbiddenException( String.format("User %s doesn't have Job create permission", authenticatedUser.getId())); } return authenticatedUser; }
Example 9
Source File: JwtAuthenticationServiceImpl.java From blueocean-plugin with MIT License | 4 votes |
@Override public JwtToken getToken(@Nullable @QueryParameter("expiryTimeInMins") Integer expiryTimeInMins, @Nullable @QueryParameter("maxExpiryTimeInMins") Integer maxExpiryTimeInMins) { long expiryTime= Long.getLong("EXPIRY_TIME_IN_MINS",DEFAULT_EXPIRY_IN_SEC); int maxExpiryTime = Integer.getInteger("MAX_EXPIRY_TIME_IN_MINS",DEFAULT_MAX_EXPIRY_TIME_IN_MIN); if(maxExpiryTimeInMins != null){ maxExpiryTime = maxExpiryTimeInMins; } if(expiryTimeInMins != null){ if(expiryTimeInMins > maxExpiryTime) { throw new ServiceException.BadRequestException( String.format("expiryTimeInMins %s can't be greater than %s", expiryTimeInMins, maxExpiryTime)); } expiryTime = expiryTimeInMins * 60; } Authentication authentication = Jenkins.getAuthentication(); String userId = authentication.getName(); User user = User.get(userId, false, Collections.emptyMap()); String email = null; String fullName = null; if(user != null) { fullName = user.getFullName(); userId = user.getId(); Mailer.UserProperty p = user.getProperty(Mailer.UserProperty.class); if(p!=null) email = p.getAddress(); } Plugin plugin = Jenkins.getInstance().getPlugin("blueocean-jwt"); String issuer = "blueocean-jwt:"+ ((plugin!=null) ? plugin.getWrapper().getVersion() : ""); JwtToken jwtToken = new JwtToken(); jwtToken.claim.put("jti", UUID.randomUUID().toString().replace("-","")); jwtToken.claim.put("iss", issuer); jwtToken.claim.put("sub", userId); jwtToken.claim.put("name", fullName); long currentTime = System.currentTimeMillis()/1000; jwtToken.claim.put("iat", currentTime); jwtToken.claim.put("exp", currentTime+expiryTime); jwtToken.claim.put("nbf", currentTime - DEFAULT_NOT_BEFORE_IN_SEC); //set claim JSONObject context = new JSONObject(); JSONObject userObject = new JSONObject(); userObject.put("id", userId); userObject.put("fullName", fullName); userObject.put("email", email); JwtAuthenticationStore authenticationStore = getJwtStore(authentication); authenticationStore.store(authentication, context); context.put("user", userObject); jwtToken.claim.put("context", context); return jwtToken; }
Example 10
Source File: PipelineStepImpl.java From blueocean-plugin with MIT License | 4 votes |
private Object parseValue(InputStepExecution execution, JSONArray parameters, StaplerRequest request) throws IOException, InterruptedException { Map<String, Object> mapResult = new HashMap<String, Object>(); InputStep input = execution.getInput(); for(Object o: parameters){ JSONObject p = (JSONObject) o; String name = (String) p.get(NAME_ELEMENT); if(name == null){ throw new ServiceException.BadRequestException("name is required parameter element"); } ParameterDefinition d=null; for (ParameterDefinition def : input.getParameters()) { if (def.getName().equals(name)) d = def; } if (d == null) throw new ServiceException.BadRequestException("No such parameter definition: " + name); ParameterValue v = d.createValue(request, p); if (v == null) { continue; } mapResult.put(name, convert(name, v)); } // If a destination value is specified, push the submitter to it. String valueName = input.getSubmitterParameter(); if (valueName != null && !valueName.isEmpty()) { Authentication a = Jenkins.getAuthentication(); mapResult.put(valueName, a.getName()); } switch (mapResult.size()) { case 0: return null; // no value if there's no parameter case 1: return mapResult.values().iterator().next(); default: return mapResult; } }