protected void resetPreviousAuthentication(Authentication previousAuthentication) { SecurityContextHolder.getContext().setAuthentication(previousAuthentication); }
/** * Gets the {@link Authentication} object that represents the user * associated with the current request. */ public static Authentication getAuthentication() { Authentication a = SecurityContextHolder.getContext().getAuthentication(); // on Tomcat while serving the login page, this is null despite the fact // that we have filters. Looking at the stack trace, Tomcat doesn't seem to // run the request through filters when this is the login request. // see http://www.nabble.com/Matrix-authorization-problem-tp14602081p14886312.html if (a == null) { a = ANONYMOUS; } return a; }
@Override public void run() { try { SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); reload(); } catch (IOException e) { LOGGER.log(java.util.logging.Level.SEVERE, "Failed to reload Hudson config", e); } catch (ReactorException e) { LOGGER.log(java.util.logging.Level.SEVERE, "Failed to reload Hudson config", e); } catch (InterruptedException e) { LOGGER.log(java.util.logging.Level.SEVERE, "Failed to reload Hudson config", e); } } }.start();
private boolean isSAMLInSecurityContext(){ AbstractAuthenticationToken cat = (AbstractAuthenticationToken)SecurityContextHolder.getContext().getAuthentication(); if(cat.getDetails() instanceof SAMLAssertion){ return true; } return false; }
public final void run() { // background activity gets system credential, // just like executors get it. SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); try { doRun(); } catch(Throwable t) { LOGGER.log(Level.SEVERE, "Timer task "+this+" failed",t); } finally { SecurityContextHolder.clearContext(); } }
/** * Return currently logged in user */ public static WsecUser getLoggedInUser() { Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (obj instanceof UserDetails) { WsecUserDetails wsecUserDetails = (WsecUserDetails) obj; return wsecUserDetails.getWsecUser(); } throw new IllegalStateException("No one logged in!!!"); }
@Override public void run() { try { SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); // give some time for the browser to load the "reloading" page Thread.sleep(5000); LOGGER.severe(String.format("Restarting VM as requested by %s", exitUser)); for (RestartListener listener : RestartListener.all()) { listener.onRestart(); } lifecycle.restart(); } catch (InterruptedException e) { LOGGER.log(Level.WARNING, "Failed to restart Hudson", e); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to restart Hudson", e); } } }.start();
@Override public void run() { try { SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); LOGGER.severe(String.format("Shutting down VM as requested by %s from %s", exitUser, exitAddr)); // Wait 'til we have no active executors. while (isQuietingDown && (overallLoad.computeTotalExecutors() > overallLoad.computeIdleExecutors())) { Thread.sleep(5000); } // Make sure isQuietingDown is still true. if (isQuietingDown) { cleanUp(); System.exit(0); } } catch (InterruptedException e) { LOGGER.log(Level.WARNING, "Failed to shutdown Hudson", e); } } }.start();
public void run() { logger.log(Level.INFO, "Started "+name); long startTime = System.currentTimeMillis(); StreamTaskListener l = createListener(); try { SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); execute(l); } catch (IOException e) { e.printStackTrace(l.fatalError(e.getMessage())); } catch (InterruptedException e) { e.printStackTrace(l.fatalError("aborted")); } finally { l.closeQuietly(); } logger.log(Level.INFO, "Finished "+name+". "+ (System.currentTimeMillis()-startTime)+" ms"); } },name+" thread");
protected void onValidSignature(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException { //signature is verified; create the token, send the response. ConsumerAuthentication authentication = (ConsumerAuthentication) SecurityContextHolder.getContext().getAuthentication(); OAuthProviderToken authToken = createOAuthToken(authentication); if (!authToken.getConsumerKey().equals(authentication.getConsumerDetails().getConsumerKey())) { throw new IllegalStateException("The consumer key associated with the created auth token is not valid for the authenticated consumer."); } String tokenValue = authToken.getValue(); StringBuilder responseValue = new StringBuilder(OAuthProviderParameter.oauth_token.toString()) .append('=') .append(OAuthCodec.oauthEncode(tokenValue)) .append('&') .append(OAuthProviderParameter.oauth_token_secret.toString()) .append('=') .append(OAuthCodec.oauthEncode(authToken.getSecret())); response.setContentType(getResponseContentType()); response.getWriter().print(responseValue.toString()); response.flushBuffer(); }
/** * This can be used to get the current user's principal name from security context * * @return principal name */ public static String getCurrentPrincipalName(){ String username = "unknown"; Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { Object obj = auth.getPrincipal(); if (obj instanceof UserDetails) { username = ((UserDetails)obj).getUsername(); } else { username = obj.toString(); } } return username; }
public void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (requiresLogout(request, response)) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (logger.isDebugEnabled()) { logger.debug("Logging out user '" + auth + "' and redirecting to logout page"); } for (int i = 0; i < handlers.length; i++) { handlers[i].logout(request, response, auth); } String targetUrl = determineTargetUrl(request, response); sendRedirect(request, response, targetUrl); return; } chain.doFilter(request, response); }
protected void onValidSignature(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException { //signature is verified; create the token, send the response. ConsumerAuthentication authentication = (ConsumerAuthentication) SecurityContextHolder.getContext().getAuthentication(); OAuthProviderToken authToken = createOAuthToken(authentication); if (!authToken.getConsumerKey().equals(authentication.getConsumerDetails().getConsumerKey())) { throw new IllegalStateException("The consumer key associated with the created auth token is not valid for the authenticated consumer."); } String tokenValue = authToken.getValue(); String callback = authentication.getOAuthParameters().get(OAuthConsumerParameter.oauth_callback.toString()); StringBuilder responseValue = new StringBuilder(OAuthProviderParameter.oauth_token.toString()) .append('=') .append(OAuthCodec.oauthEncode(tokenValue)) .append('&') .append(OAuthProviderParameter.oauth_token_secret.toString()) .append('=') .append(OAuthCodec.oauthEncode(authToken.getSecret())); if (callback != null) { responseValue.append('&') .append(OAuthProviderParameter.oauth_callback_confirmed.toString()) .append("=true"); } response.setContentType(getResponseContentType()); response.getWriter().print(responseValue.toString()); response.flushBuffer(); }
/** * This can be used to get the current user's principal id from security context * * @return principal id */ public static String getCurrentPrincipalId() { String principalID=null; Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if(auth!=null){ Object obj = auth.getPrincipal(); if(obj instanceof UserWithId){ //This is actually the user's Principal Id principalID = ((UserWithId)obj).getUserId(); } } return principalID; }
private boolean isCurrentUserLoggedInWithKey(UserIndexKey key) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) return false; Object principal = authentication.getPrincipal(); if (!(principal instanceof IndexedUserDetails)) return false; IndexedUserDetails details = (IndexedUserDetails) principal; UserIndexKey indexKey = details.getUserIndexKey(); return indexKey.equals(key); } }
private boolean isTokenExpired() { SecurityContext context = SecurityContextHolder.getContext(); boolean detectExpiredTokens = federationConfig != null && federationConfig.getFedizContext().isDetectExpiredTokens(); if (context != null && detectExpiredTokens) { Authentication authentication = context.getAuthentication(); if (authentication instanceof FederationAuthenticationToken) { Date tokenExpires = ((FederationAuthenticationToken)authentication).getResponse().getTokenExpires(); if (tokenExpires == null) { return false; } Date currentTime = new Date(); if (currentTime.after(tokenExpires)) { return true; } } } return false; }
/** * Lets the current user silently login as the given user and report back accordingly. */ private void loginAndTakeBack(StaplerRequest req, StaplerResponse rsp, User u) throws ServletException, IOException { // ... and let him login Authentication a = new UsernamePasswordAuthenticationToken(u.getId(),req.getParameter("password1")); a = this.getSecurityComponents().manager.authenticate(a); SecurityContextHolder.getContext().setAuthentication(a); // then back to top req.getView(this,"success.jelly").forward(req,rsp); }
@Override public void _run() throws IOException { super._run(); // if this is a bundled plugin, make sure it won't get overwritten PluginWrapper pw = plugin.getInstalled(); if (pw!=null && pw.isBundled()) try { SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); pw.doPin(); } finally { SecurityContextHolder.clearContext(); } }
@Override public String intercept(ActionInvocation invocation) throws Exception { ActionContext context = invocation.getInvocationContext(); Map<String, Object> params = context.getParameters(); String phoneNumber = getPhoneNumber(params); phoneNumber = PhoneNumberLibrary.normalizePhoneNumber(phoneNumber); if (phoneNumber != null && phoneNumber.length() > 0) { UserIndexKey key = new UserIndexKey(UserIndexTypes.PHONE_NUMBER, phoneNumber); if( params.containsKey(RESET_USER)) _indexedUserDetailsService.resetUserForIndexKey(key); // Ensure that we have authentication, even if it's anonymous if (!isCurrentUserLoggedInWithKey(key)) { IndexedUserDetails userDetails = _indexedUserDetailsService.getOrCreateUserForIndexKey( key, "", false); DefaultUserAuthenticationToken token = new DefaultUserAuthenticationToken( userDetails); SecurityContextHolder.getContext().setAuthentication(token); } } return invocation.invoke(); }
public Authentication attemptAuthentication(HttpServletRequest request) throws AuthenticationException { String requestToken = request.getParameter(getTokenParameterName()); if (requestToken == null) { throw new InvalidOAuthParametersException("An OAuth token id is required."); } OAuthProviderToken token = getTokenServices().getToken(requestToken); if (token == null) { throw new InvalidOAuthTokenException("Invalid token: " + requestToken); } String callbackURL = token.getCallbackUrl(); if (isRequire10a() && callbackURL == null) { throw new InvalidOAuthTokenException("No callback value has been provided for request token " + requestToken + "."); } if (callbackURL != null) { request.setAttribute(CALLBACK_ATTRIBUTE, callbackURL); } Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (!authentication.isAuthenticated()) { throw new InsufficientAuthenticationException("User must be authenticated before authorizing a request token."); } String verifier = getVerifierServices().createVerifier(); request.setAttribute(VERIFIER_ATTRIBUTE, verifier); getTokenServices().authorizeRequestToken(requestToken, verifier, authentication); return authentication; }