Java Code Examples for org.acegisecurity.Authentication#getName()

The following examples show how to use org.acegisecurity.Authentication#getName() . 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: UserImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@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 2
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 3
Source File: JwtAuthenticationServiceImpl.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@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 4
Source File: WCTAuthenticationProcessingFilter.java    From webcurator with Apache License 2.0 4 votes vote down vote up
/** @see org.acegisecurity.ui.AbstractProcessingFilter#onSuccessfulAuthentication(HttpServletRequest,HttpServletResponse, Authentication) . */
  protected void onSuccessfulAuthentication(HttpServletRequest request,
          HttpServletResponse response, Authentication authResult)
          throws IOException {
      
      log.debug("calling onSuccessfulAuthentication for WCT");
      String userName = authResult.getName();
      
      User wctUser = authDAO.getUserByName(userName);
      
      if (wctUser != null) {
       log.debug("loaded WCT User object "+wctUser.getUsername()+" from database");
       UsernamePasswordAuthenticationToken auth =  (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
       auth.setDetails(wctUser);
       log.debug("pushing back upat into SecurityContext with populated WCT User");
       SecurityContextHolder.getContext().setAuthentication(auth);
      
       //audit successful login event
       auditor.audit(User.class.getName(), wctUser.getOid(), Auditor.ACTION_LOGIN_SUCCESS, "Successful Login for username: "+wctUser.getUsername());
	
       // Get the Spring Application Context.
	WebApplicationContext ctx = ApplicationContextFactory.getWebApplicationContext();

	// set or re-set the page size cookie..
	// ..first get the value of the page size cookie
	String currentPageSize = CookieUtils.getPageSize(request);
	// ..then refresh the page size cookie, to expire in a year
	CookieUtils.setPageSize(response, currentPageSize);

       // set login for duration
       String sessionId = request.getSession().getId();
       LogonDurationDAO logonDurationDAO = (LogonDurationDAO) ctx.getBean(Constants.BEAN_LOGON_DURATION_DAO);
      	logonDurationDAO.setLoggedIn(sessionId, new Date(), wctUser.getOid(), wctUser.getUsername(), wctUser.getNiceName());
      	
	// Check previous records of duration
      	logonDurationDAO.setProperLoggedoutForCurrentUser(wctUser.getOid(), sessionId);
      	
}  else {
          
          //audit successful login but unsucessful load of WCT User event
          auditor.audit(User.class.getName(), Auditor.ACTION_LOGIN_FAILURE_NO_USER, "Un-successful login for username: "+userName+" as user doesn't exist in the WCT System.");

      }
  }
 
Example 5
Source File: AcegiLogoutListener.java    From webcurator with Apache License 2.0 4 votes vote down vote up
public void sessionDestroyed(HttpSessionEvent event) {
    // Log the logout to the console.
       log.info("Detected Logout Event");
       
	// Get the Spring Application Context.
	WebApplicationContext ctx = ApplicationContextFactory.getWebApplicationContext();
       
	// We need to get the authentication context out of the 
       // event, as it doesn't necessarily exist through the
       // standard Acegi tools.
       String remoteUser = null;
       Authentication auth = null;        
       SecurityContext acegiCtx = (SecurityContext) event.getSession().getAttribute("ACEGI_SECURITY_CONTEXT");
       if( acegiCtx != null) {
           auth = acegiCtx.getAuthentication();
           if (auth != null) {
               remoteUser = auth.getName();
           }
       }
               
       if (remoteUser == null) {
           remoteUser = "[UNKNOWN]";
       }
	
	// Actions to perform on logout.
	lockManager = (LockManager) ctx.getBean("lockManager");
	lockManager.releaseLocksForOwner(remoteUser);
	
       if (auth != null) {
           Object blob = auth.getDetails();
           if (blob instanceof User) {
               User user = (User) auth.getDetails();
               Auditor auditor = (Auditor) ctx.getBean(Constants.BEAN_AUDITOR);
               auditor.audit(user, User.class.getName(), user.getOid(), Auditor.ACTION_LOGOUT, "User " + remoteUser + " has logged out.");        
           }
       
       
           SecurityContextHolder.clearContext();
           
           // logout for duration
           String sessionId = event.getSession().getId();
           LogonDurationDAO logonDurationDAO = (LogonDurationDAO) ctx.getBean(Constants.BEAN_LOGON_DURATION_DAO);
           logonDurationDAO.setLoggedOut(sessionId, new Date());
       }
               
       // Log the logout to the console.
       log.info("Detected Logout Event for: " + remoteUser);
}
 
Example 6
Source File: ReportEmailController.java    From webcurator with Apache License 2.0 4 votes vote down vote up
@Override
protected ModelAndView processFormSubmission(HttpServletRequest req,
		HttpServletResponse resp, Object comm, BindException exc)
		throws Exception {
	
	ReportEmailCommand com = (ReportEmailCommand) comm;
	ModelAndView mav = new ModelAndView();
	
	if(com.getActionCmd().equals(ACTION_EMAIL)){
	
		OperationalReport operationalReport = (OperationalReport) req.getSession().getAttribute("operationalReport");

		// Get user's email address 
		// ...user
        String remoteUser = null;
        Authentication auth = null;        
        SecurityContext acegiCtx = (SecurityContext) req.getSession().getAttribute("ACEGI_SECURITY_CONTEXT");
        if( acegiCtx != null) {
            auth = acegiCtx.getAuthentication();
            if (auth != null) {
                remoteUser = auth.getName();
            }
        }
        // ...email address
        User user = (User) auth.getDetails();
        String userEmailAddress = user.getEmail(); 
				
        // Build attachment content
		String dataAttachment = operationalReport.getRendering(com.getFormat());
		
		// E-mail
		Mailable email = new Mailable();
		email.setRecipients(com.getRecipient());
		email.setSender(userEmailAddress);
		email.setSubject(com.getSubject());
		email.setMessage(com.getMessage());
		mailServer.send(email, 
				"report" + FileFactory.getFileExtension(com.getFormat()),
				FileFactory.getMIMEType(com.getFormat()),
				dataAttachment );
		
		log.debug("email sent:");
		log.debug("  from:" + userEmailAddress);
		log.debug("  format=" + com.getFormat());
		log.debug("  to=" + com.getRecipient());
		log.debug("  subject=" + com.getSubject());
		log.debug("  msg=" + com.getMessage());
	
		mav.setViewName("reporting-preview");
		
	} else {
		log.error("Did not get send request: " + com.getActionCmd());
		mav.setViewName("reporting-preview");
	}
	
	return mav;
			
}