Search in sources :

Example 91 with Authentication

use of org.springframework.security.core.Authentication in project spring-security by spring-projects.

the class SwitchUserFilter method doFilter.

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    // check for switch or exit request
    if (requiresSwitchUser(request)) {
        // if set, attempt switch and store original
        try {
            Authentication targetUser = attemptSwitchUser(request);
            // update the current context to the new target user
            SecurityContextHolder.getContext().setAuthentication(targetUser);
            // redirect to target url
            this.successHandler.onAuthenticationSuccess(request, response, targetUser);
        } catch (AuthenticationException e) {
            this.logger.debug("Switch User failed", e);
            this.failureHandler.onAuthenticationFailure(request, response, e);
        }
        return;
    } else if (requiresExitUser(request)) {
        // get the original authentication object (if exists)
        Authentication originalUser = attemptExitUser(request);
        // update the current context back to the original user
        SecurityContextHolder.getContext().setAuthentication(originalUser);
        // redirect to target url
        this.successHandler.onAuthenticationSuccess(request, response, originalUser);
        return;
    }
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(org.springframework.security.core.AuthenticationException) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 92 with Authentication

use of org.springframework.security.core.Authentication in project spring-security by spring-projects.

the class SwitchUserFilter method getSourceAuthentication.

/**
	 * Find the original <code>Authentication</code> object from the current user's
	 * granted authorities. A successfully switched user should have a
	 * <code>SwitchUserGrantedAuthority</code> that contains the original source user
	 * <code>Authentication</code> object.
	 *
	 * @param current The current <code>Authentication</code> object
	 *
	 * @return The source user <code>Authentication</code> object or <code>null</code>
	 * otherwise.
	 */
private Authentication getSourceAuthentication(Authentication current) {
    Authentication original = null;
    // iterate over granted authorities and find the 'switch user' authority
    Collection<? extends GrantedAuthority> authorities = current.getAuthorities();
    for (GrantedAuthority auth : authorities) {
        // check for switch user type of authority
        if (auth instanceof SwitchUserGrantedAuthority) {
            original = ((SwitchUserGrantedAuthority) auth).getSource();
            this.logger.debug("Found original switch user granted authority [" + original + "]");
        }
    }
    return original;
}
Also used : Authentication(org.springframework.security.core.Authentication) GrantedAuthority(org.springframework.security.core.GrantedAuthority)

Example 93 with Authentication

use of org.springframework.security.core.Authentication in project spring-security by spring-projects.

the class SwitchUserFilter method attemptExitUser.

/**
	 * Attempt to exit from an already switched user.
	 *
	 * @param request The http servlet request
	 *
	 * @return The original <code>Authentication</code> object or <code>null</code>
	 * otherwise.
	 *
	 * @throws AuthenticationCredentialsNotFoundException If no
	 * <code>Authentication</code> associated with this request.
	 */
protected Authentication attemptExitUser(HttpServletRequest request) throws AuthenticationCredentialsNotFoundException {
    // need to check to see if the current user has a SwitchUserGrantedAuthority
    Authentication current = SecurityContextHolder.getContext().getAuthentication();
    if (null == current) {
        throw new AuthenticationCredentialsNotFoundException(this.messages.getMessage("SwitchUserFilter.noCurrentUser", "No current user associated with this request"));
    }
    // check to see if the current user did actual switch to another user
    // if so, get the original source user so we can switch back
    Authentication original = getSourceAuthentication(current);
    if (original == null) {
        this.logger.debug("Could not find original user Authentication object!");
        throw new AuthenticationCredentialsNotFoundException(this.messages.getMessage("SwitchUserFilter.noOriginalAuthentication", "Could not find original Authentication object"));
    }
    // get the source user details
    UserDetails originalUser = null;
    Object obj = original.getPrincipal();
    if ((obj != null) && obj instanceof UserDetails) {
        originalUser = (UserDetails) obj;
    }
    // publish event
    if (this.eventPublisher != null) {
        this.eventPublisher.publishEvent(new AuthenticationSwitchUserEvent(current, originalUser));
    }
    return original;
}
Also used : AuthenticationCredentialsNotFoundException(org.springframework.security.authentication.AuthenticationCredentialsNotFoundException) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication)

Example 94 with Authentication

use of org.springframework.security.core.Authentication in project spring-security by spring-projects.

the class AbstractPreAuthenticatedProcessingFilter method requiresAuthentication.

private boolean requiresAuthentication(HttpServletRequest request) {
    Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();
    if (currentUser == null) {
        return true;
    }
    if (!checkForPrincipalChanges) {
        return false;
    }
    if (!principalChanged(request, currentUser)) {
        return false;
    }
    logger.debug("Pre-authenticated principal has changed and will be reauthenticated");
    if (invalidateSessionOnPrincipalChange) {
        SecurityContextHolder.clearContext();
        HttpSession session = request.getSession(false);
        if (session != null) {
            logger.debug("Invalidating existing session");
            session.invalidate();
            request.getSession();
        }
    }
    return true;
}
Also used : Authentication(org.springframework.security.core.Authentication) HttpSession(javax.servlet.http.HttpSession)

Example 95 with Authentication

use of org.springframework.security.core.Authentication in project spring-security by spring-projects.

the class AuthenticationPrincipalArgumentResolver method resolveArgument.

/*
	 * (non-Javadoc)
	 *
	 * @see org.springframework.web.method.support.HandlerMethodArgumentResolver#
	 * resolveArgument (org.springframework.core.MethodParameter,
	 * org.springframework.web.method.support.ModelAndViewContainer,
	 * org.springframework.web.context.request.NativeWebRequest,
	 * org.springframework.web.bind.support.WebDataBinderFactory)
	 */
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
        return null;
    }
    Object principal = authentication.getPrincipal();
    AuthenticationPrincipal authPrincipal = findMethodAnnotation(AuthenticationPrincipal.class, parameter);
    String expressionToParse = authPrincipal.expression();
    if (StringUtils.hasLength(expressionToParse)) {
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setRootObject(principal);
        context.setVariable("this", principal);
        context.setBeanResolver(beanResolver);
        Expression expression = this.parser.parseExpression(expressionToParse);
        principal = expression.getValue(context);
    }
    if (principal != null && !parameter.getParameterType().isAssignableFrom(principal.getClass())) {
        if (authPrincipal.errorOnInvalidType()) {
            throw new ClassCastException(principal + " is not assignable to " + parameter.getParameterType());
        } else {
            return null;
        }
    }
    return principal;
}
Also used : StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) Expression(org.springframework.expression.Expression) Authentication(org.springframework.security.core.Authentication) AuthenticationPrincipal(org.springframework.security.core.annotation.AuthenticationPrincipal)

Aggregations

Authentication (org.springframework.security.core.Authentication)498 Test (org.junit.Test)192 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)114 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)98 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)75 SecurityContext (org.springframework.security.core.context.SecurityContext)63 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)57 GrantedAuthority (org.springframework.security.core.GrantedAuthority)50 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)47 SecurityContextImpl (org.springframework.security.core.context.SecurityContextImpl)42 MifosUser (org.mifos.security.MifosUser)38 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)34 HttpServletRequest (javax.servlet.http.HttpServletRequest)32 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)32 AuthenticationException (org.springframework.security.core.AuthenticationException)31 UserDetails (org.springframework.security.core.userdetails.UserDetails)31 MifosUserBuilder (org.mifos.builders.MifosUserBuilder)29 HashMap (java.util.HashMap)27 HttpServletResponse (javax.servlet.http.HttpServletResponse)27 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)25