org.acegisecurity.context.SecurityContextHolder Java Examples

The following examples show how to use org.acegisecurity.context.SecurityContextHolder. 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: GithubWebhook.java    From DotCi with MIT License 6 votes vote down vote up
public void processGitHubPayload(final String eventType, final String payloadData) {
    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
    final WebhookPayload payload = makePayload(eventType, payloadData);
    LOGGER.info("Received kicking off build for " + payload.getProjectUrl());
    for (final DynamicProject job : makeDynamicProjectRepo().getJobsFor(payload.getProjectUrl())) {

        if (payload.needsBuild(job)) {
            LOGGER.info("starting job " + job.getName());
            this.queue.execute(() -> {
                try {
                    job.scheduleBuild(0, payload.getCause(), new NoDuplicatesParameterAction(getParametersValues(job, payload.getBranch())));
                } catch (final Exception e) {
                    LOGGER.log(Level.INFO, "Error scheduling build for " + payload.getProjectUrl(), e);
                }
            });
        }
    }
}
 
Example #2
Source File: BuildStatus.java    From jenkins-status-badges-plugin with MIT License 6 votes vote down vote up
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 #3
Source File: KualiDistributedSessionFilter.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * This method retrieves the Distributed Session Ticket
 * 
 * @return the Distributed Session Ticket if valid or null
 */
private String getDST() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String sDST = null;
    
    if (authentication != null) {
        GrantedAuthority[] authorities = authentication.getAuthorities();
        if (logger.isDebugEnabled()) {
            logger.debug("Granted Authority Count:" + authorities.length);
        }
        
        for (int i = 0; i < authorities.length; i++) {
            if (logger.isDebugEnabled()) {
                logger.debug("Authority:" + authorities[i]);
            }
            if (authorities[i].toString().startsWith(DistributedSession.getPrefix())) {
                sDST = authorities[0].toString();
            }
        }
    }
    else {
        logger.debug("Authentication is NULL");            
    }
    
    return sDST;
}
 
Example #4
Source File: AcegiUnSafeSessionFilter.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    Authentication old = SecurityContextHolder.getContext().getAuthentication();

    if(1 + 1 == 2) {
        try {
            SecurityContextHolder.getContext().setAuthentication(null);
            super.doFilter(req, res, chain);
        } finally {
            SecurityContextHolder.getContext().setAuthentication(old);
        }
    }
    else {
        super.doFilter(req, res, chain);
    }
}
 
Example #5
Source File: AcegiSafeSessionFilter.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #6
Source File: CLICommandInvoker.java    From jenkins-test-harness with MIT License 6 votes vote down vote up
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 #7
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void userCurrentTest() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

    SecurityContextHolder.getContext().setAuthentication(j.jenkins.ANONYMOUS);

    Assert.assertNull(User.current());

    List<Map> l = new RequestBuilder(baseUrl)
        .get("/organizations/jenkins/pipelines/")
        .authAlice()
        .build(List.class);

    assertEquals(0, l.size());
    Assert.assertNull(User.current());
}
 
Example #8
Source File: KualiDistributedSessionFilter.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * This overridden method gets called if requiresAuthentication is true.  
 * If Session is Invalid, throw a {@link KualiDistribtedSessionExpiredException}.  
 * The session is determined invalid if the authentication is of type 
 * {@link KualiDistribtedSessionExpiredAuthentication}.  Otherwise it 
 * would have to verify if the DST is valid twice. 
 *
 * @return the authentication result of the super method
 * @see org.acegisecurity.ui.cas.CasProcessingFilter#attemptAuthentication(javax.servlet.http.HttpServletRequest)
 */
public Authentication attemptAuthentication(final HttpServletRequest request)
    throws AuthenticationException { 
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    
    if (authentication instanceof KualiDistributedSessionExpiredAuthentication) {
        logger.debug("Authentication is dead in attemptAuthentication, setting authentication to null and throwing KualiDistributedSessionExpiredException");
        SecurityContextHolder.getContext().setAuthentication(null);

        throw new KualiDistributedSessionExpiredException("Session Expired");
    }
   
    return super.attemptAuthentication(request);
}
 
Example #9
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
public HttpResponse doEscapeHatch(@QueryParameter("j_username") String username, @QueryParameter("j_password") String password) {
    randomWait(); // to slowdown brute forcing
    if(!isEscapeHatchEnabled()) {
        return HttpResponses.redirectViaContextPath("loginError");
    }
    if(this.escapeHatchUsername == null || this.escapeHatchSecret == null) {
        return HttpResponses.redirectViaContextPath("loginError");
    }
    if(escapeHatchUsername.equalsIgnoreCase(username) && escapeHatchSecret.getPlainText().equals(password)) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(SecurityRealm.AUTHENTICATED_AUTHORITY);
        if(isNotBlank(escapeHatchGroup)) {
            authorities.add(new GrantedAuthorityImpl(escapeHatchGroup));
        }
        String userName = "escape-hatch-admin";
        GrantedAuthority[] grantedAuthorities = authorities.toArray(new GrantedAuthority[authorities.size()]);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
        		userName,
                "",
                grantedAuthorities
        );
        SecurityContextHolder.getContext().setAuthentication(token);
        OicUserDetails userDetails = new OicUserDetails(userName, grantedAuthorities);
        SecurityListener.fireAuthenticated(userDetails);
        return HttpRedirect.CONTEXT_ROOT;
    }
    return HttpResponses.redirectViaContextPath("loginError");
}
 
Example #10
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
private UsernamePasswordAuthenticationToken loginAndSetUserData(String userName, IdToken idToken, GenericJson userInfo) throws IOException {

        GrantedAuthority[] grantedAuthorities = determineAuthorities(idToken, userInfo);
        if(LOGGER.isLoggable(Level.FINEST)) {
		    StringBuilder grantedAuthoritiesAsString = new StringBuilder("(");
		    for(GrantedAuthority grantedAuthority : grantedAuthorities) {
		        grantedAuthoritiesAsString.append(" ").append(grantedAuthority.getAuthority());
            }
            grantedAuthoritiesAsString.append(" )");
		    LOGGER.finest("GrantedAuthorities:" + grantedAuthoritiesAsString);
        }

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, "", grantedAuthorities);

        SecurityContextHolder.getContext().setAuthentication(token);

        User user = User.get(token.getName());
        // Store the list of groups in a OicUserProperty so it can be retrieved later for the UserDetails object.
        user.addProperty(new OicUserProperty(userName, grantedAuthorities));

        if(emailFieldName!=null) {
	        String email = userInfo == null ? getField(idToken, emailFieldName) : (String) getField(userInfo, emailFieldName);
	        if (email != null) {
	            user.addProperty(new Mailer.UserProperty(email));
	        }
        }

        if(fullNameFieldName!=null) {
		    String fullName = userInfo == null ? getField(idToken, fullNameFieldName) : (String) getField(userInfo, fullNameFieldName);
		    if (fullName != null) {
		        user.setFullName(fullName);
		    }
        }

        OicUserDetails userDetails = new OicUserDetails(userName, grantedAuthorities);
        SecurityListener.fireAuthenticated(userDetails);

        return token;
    }
 
Example #11
Source File: WCTForcePasswordChange.java    From webcurator with Apache License 2.0 5 votes vote down vote up
/** @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */
public void doFilter(ServletRequest aRequest, ServletResponse aResponse, FilterChain aChain) throws IOException, ServletException {
    if (log.isDebugEnabled()) {
        log.debug("Checking forced password change action.");
    }
    
    if (!(aRequest instanceof HttpServletRequest)) {
      throw new ServletException("Can only process HttpServletRequest");
  }

  if (!(aResponse instanceof HttpServletResponse)) {
      throw new ServletException("Can only process HttpServletResponse");
  }

  HttpServletRequest httpRequest = (HttpServletRequest) aRequest;
  
  Authentication auth =  SecurityContextHolder.getContext().getAuthentication();      
  if (auth != null) {            
    if (auth.isAuthenticated()) {
        User authUser = (User)auth.getDetails();

        if (authUser != null) {
          if (authUser.isForcePasswordChange() == true && authUser.isExternalAuth() == false) {
                                
              RequestDispatcher reqDisp = httpRequest.getRequestDispatcher("/"+Constants.CNTRL_RESET_PWD);
              reqDisp.forward(aRequest, aResponse);  
              auditor.audit(User.class.getName(),authUser.getOid(),Auditor.ACTION_FORCE_PWD_CHANGE,"User has been forced to change password");
          }
        }
    }
    else {
        throw new AccessControlException("The user is not authenticated correctly.");
    }
  }
 
  aChain.doFilter(aRequest, aResponse);
}
 
Example #12
Source File: ResetPasswordController.java    From webcurator with Apache License 2.0 5 votes vote down vote up
/**
 * Process the change password command. 
 */
private ModelAndView processPasswordChange(HttpServletRequest aReq,HttpServletResponse aResp, ResetPasswordCommand aCmd, BindException aErrors) throws Exception {
    ModelAndView mav = new ModelAndView();
    if (aErrors.hasErrors()) {
        mav.addObject(Constants.GBL_CMD_DATA, aErrors.getTarget());
        mav.addObject(Constants.GBL_ERRORS, aErrors);
        mav.setViewName(Constants.VIEW_RESET_PWD);

        return mav;
    }

    try {
                    
        UsernamePasswordAuthenticationToken upat = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        
        User userAccount = (User) authDAO.getUserByName(upat.getName());
        
        String sysSalt = salt.getSystemWideSalt();
        String encodedPwd = encoder.encodePassword(aCmd.getNewPwd(),sysSalt);
        
        userAccount.setPassword(encodedPwd);
        //userAccount.setPwdFailedAttempts(0);
        userAccount.setForcePasswordChange(false);

        authDAO.saveOrUpdate(userAccount);
        
        upat.setDetails(userAccount);
        
        SecurityContextHolder.getContext().setAuthentication(upat);
        
        mav.addObject(Constants.MESSAGE_TEXT, "Your password has been changed.");
        mav.setViewName(Constants.VIEW_PASSWORD_RESET_SUCCESS);

        return mav;
    }
    catch (Exception e) {
        throw new Exception("Persistance Error occurred during password change", e);
    }
}
 
Example #13
Source File: AuthUtil.java    From webcurator with Apache License 2.0 5 votes vote down vote up
/**
 * obtains the logged in Username as populated by the acegi security framework
 * @return the logged in username
 */
public static String getRemoteUser() {
    Authentication auth =  SecurityContextHolder.getContext().getAuthentication();      
    if (auth != null) {            
        return auth.getName();
    }
    return null;
}
 
Example #14
Source File: AuthUtil.java    From webcurator with Apache License 2.0 5 votes vote down vote up
/**
 * obtains the fully populated User object and its relationship to
 * Roles and privileges.
 * @return a fully populated wct User object, null is returned if no object found
 */
public static User getRemoteUserObject() {
	if(user!=null) {
		return user;
	}
    Authentication auth =  SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        return (User)auth.getDetails();
    }
    return null;
}
 
Example #15
Source File: RESTRequestParameterProcessingFilter.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
private RESTController.ErrorCode authenticate(String username, String password, String salt, String token, Authentication previousAuth) {

        // Previously authenticated and username not overridden?
        if (username == null && previousAuth != null) {
            return null;
        }

        if (salt != null && token != null) {
            User user = securityService.getUserByName(username);
            if (user == null) {
                return RESTController.ErrorCode.NOT_AUTHENTICATED;
            }
            String expectedToken = DigestUtils.md5Hex(user.getPassword() + salt);
            if (!expectedToken.equals(token)) {
                return RESTController.ErrorCode.NOT_AUTHENTICATED;
            }

            password = user.getPassword();
        }

        if (password != null) {
            try {
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                Authentication authResult = authenticationManager.authenticate(authRequest);
                SecurityContextHolder.getContext().setAuthentication(authResult);
                return null;
            } catch (AuthenticationException x) {
                return RESTController.ErrorCode.NOT_AUTHENTICATED;
            }
        }

        return RESTController.ErrorCode.MISSING_PARAMETER;
    }
 
Example #16
Source File: KualiDistributedSessionFilter.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * This overridden method checks if the DST is valid.  If it's not, the 
 * authentication is set to a new, non-authenticated, 
 * {@link KualiDistributedSessionExpiredAuthentication} which is the 
 * indication for {@link attemptAuthentication} that the session has 
 * expired 
 * 
 * @return true if DST is inValid or if super method returns true
 * @see org.acegisecurity.ui.AbstractProcessingFilter#requiresAuthentication(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
    boolean bSesnValid = this.isSesnValid();
    
    if (!bSesnValid) {
        if (this.getDST() != null) {
            logger.debug("session invalid, setting dead authentication, and pushing through to attemptAuthentication");
            SecurityContextHolder.getContext().setAuthentication(new KualiDistributedSessionExpiredAuthentication());
            return true;
        }
    }
    
    return super.requiresAuthentication(request, response);
}
 
Example #17
Source File: GithubWebhookTest.java    From DotCi with MIT License 5 votes vote down vote up
@Test
public void should_authenticate_as_SYSTEM() throws IOException, InterruptedException {
    final StaplerRequest request = mock(StaplerRequest.class);
    final DynamicProject project = mock(DynamicProject.class);
    when(request.getParameter("payload")).thenReturn("payload");
    kickOffBuildTrigger(request, project);
    Assert.assertEquals(ACL.SYSTEM, SecurityContextHolder.getContext().getAuthentication());
}
 
Example #18
Source File: GitLabSecurityRealm.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
/**
 *
 * @param groupName
 * @return
 * @throws UsernameNotFoundException
 * @throws DataAccessException
 */
@Override
public GroupDetails loadGroupByGroupname(String groupName) throws UsernameNotFoundException, DataAccessException {

    GitLabAuthenticationToken authToken = (GitLabAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

    if (authToken == null) {
        throw new UsernameNotFoundException("No known group: " + groupName);
    }

    GitlabGroup gitlabGroup = authToken.loadOrganization(groupName);
    return new GitLabOAuthGroupDetails(gitlabGroup);

}
 
Example #19
Source File: GitLabSecurityRealm.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
@Override
public SecurityComponents createSecurityComponents() {
    return new SecurityComponents(new AuthenticationManager() {

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            if (authentication instanceof GitLabAuthenticationToken) {
                return authentication;
            }
            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                try {
                    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
                    GitLabAuthenticationToken gitlab = new GitLabAuthenticationToken(token.getCredentials().toString(), getGitlabApiUri(), TokenType.PRIVATE_TOKEN);
                    SecurityContextHolder.getContext().setAuthentication(gitlab);
                    return gitlab;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            throw new BadCredentialsException("Unexpected authentication type: " + authentication);
        }
    }, new UserDetailsService() {
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
            return GitLabSecurityRealm.this.loadUserByUsername(username);
        }
    });
}
 
Example #20
Source File: LoginExecutor.java    From ramus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object invoke(RemoteInvocation invocation, Object arg1)
        throws NoSuchMethodException, IllegalAccessException,
        InvocationTargetException {
    Object object = super.invoke(invocation, arg1);
    UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(
            invocation.getArguments()[0].toString(), invocation
            .getArguments()[1].toString());
    Authentication auth = daoAuthenticationProvider.authenticate(userToken);
    SecurityContextHolder.getContext().setAuthentication(auth);
    return object;
}
 
Example #21
Source File: TestImpl.java    From ramus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void test() {
    SecurityContext sc = SecurityContextHolder.getContext();
    if (sc.getAuthentication() != null)
        System.out.println(sc.getAuthentication().getName()
                + " logged by test");

}
 
Example #22
Source File: JwtAuthenticationFilter.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@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 #23
Source File: RESTRequestParameterProcessingFilter.java    From subsonic with GNU General Public License v3.0 4 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("Can only process HttpServletRequest");
    }
    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("Can only process HttpServletResponse");
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String username = StringUtils.trimToNull(httpRequest.getParameter("u"));
    String password = decrypt(StringUtils.trimToNull(httpRequest.getParameter("p")));
    String salt = StringUtils.trimToNull(httpRequest.getParameter("s"));
    String token = StringUtils.trimToNull(httpRequest.getParameter("t"));
    String version = StringUtils.trimToNull(httpRequest.getParameter("v"));
    String client = StringUtils.trimToNull(httpRequest.getParameter("c"));

    RESTController.ErrorCode errorCode = null;

    // The username and credentials parameters are not required if the user
    // was previously authenticated, for example using Basic Auth.
    boolean passwordOrTokenPresent = password != null || (salt != null && token != null);
    Authentication previousAuth = SecurityContextHolder.getContext().getAuthentication();
    boolean missingCredentials = previousAuth == null && (username == null || !passwordOrTokenPresent);
    if (missingCredentials || version == null || client == null) {
        errorCode = RESTController.ErrorCode.MISSING_PARAMETER;
    }

    if (errorCode == null) {
        errorCode = checkAPIVersion(version);
    }

    if (errorCode == null) {
        errorCode = authenticate(username, password, salt, token, previousAuth);
    }

    if (errorCode == null) {
        errorCode = checkLicense(client);
    }

    if (errorCode == null) {
        chain.doFilter(request, response);
    } else {
        if (errorCode == RESTController.ErrorCode.NOT_AUTHENTICATED) {
            loginFailureLogger.log(request.getRemoteAddr(), username);
        }
        SecurityContextHolder.getContext().setAuthentication(null);
        sendErrorXml(httpRequest, httpResponse, errorCode);
    }
}
 
Example #24
Source File: GlobalRoleBenchmark.java    From folder-auth-plugin with MIT License 4 votes vote down vote up
@Setup(Level.Iteration)
public void setup() {
    SecurityContext holder = SecurityContextHolder.getContext();
    holder.setAuthentication(Objects.requireNonNull(User.getById("user3", true)).impersonate());
}
 
Example #25
Source File: MongoRepositoryTest.java    From DotCi with MIT License 4 votes vote down vote up
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;
    }
 
Example #26
Source File: OrganizationContainer.java    From DotCi with MIT License 4 votes vote down vote up
private void authenticate() {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Jenkins.getInstance().getSecurityRealm().getSecurityComponents().manager.authenticate(authentication);
}
 
Example #27
Source File: AuthenticationMixin.java    From DotCi with MIT License 4 votes vote down vote up
public void authenticate() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Jenkins.getInstance().getSecurityRealm().createSecurityComponents().manager.authenticate(authentication);
}
 
Example #28
Source File: UserProviderImpl.java    From ramus with GNU General Public License v3.0 4 votes vote down vote up
protected String getLogin() {
    SecurityContext sc = SecurityContextHolder.getContext();
    if (sc.getAuthentication() == null)
        return null;
    return sc.getAuthentication().getName();
}
 
Example #29
Source File: ServerAccessRules.java    From ramus with GNU General Public License v3.0 4 votes vote down vote up
private SecurityContext getSecurityContext() {
    return SecurityContextHolder.getContext();
}
 
Example #30
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void testPermissionOfOtherUser() throws IOException {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

    hudson.model.User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));


    hudson.model.User bob = User.get("bob");
    bob.setFullName("Bob Cooper");
    bob.addProperty(new Mailer.UserProperty("[email protected]"));

    UserDetails d = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(bob.getId());

    SecurityContextHolder.getContext().setAuthentication(new PrincipalAcegiUserToken(bob.getId(),bob.getId(),bob.getId(), d.getAuthorities(), bob.getId()));

    Assert.assertNull(new UserImpl(Iterables.getFirst(OrganizationFactory.getInstance().list(), null), alice).getPermission());
}