Example usage for org.springframework.security.core.context SecurityContext setAuthentication

List of usage examples for org.springframework.security.core.context SecurityContext setAuthentication

Introduction

In this page you can find the example usage for org.springframework.security.core.context SecurityContext setAuthentication.

Prototype

void setAuthentication(Authentication authentication);

Source Link

Document

Changes the currently authenticated principal, or removes the authentication information.

Usage

From source file:org.vaadin.spring.security.internal.VaadinSharedSecurity.java

@Override
public Authentication login(Authentication authentication, boolean rememberMe) throws Exception {
    SecurityContext context = SecurityContextHolder.getContext();

    final HttpServletRequest request = httpRequestResponseHolder.getCurrentRequest();
    if (request == null) {
        throw new IllegalStateException("No HttpServletRequest bound to current thread");
    }/*  www  . j  a v a 2s  .  co  m*/

    final HttpServletResponse response = httpRequestResponseHolder.getCurrentResponse();
    if (response == null) {
        throw new IllegalStateException("No HttpServletResponse bound to current thread");
    }

    try {
        logger.debug("Attempting authentication of {}, rememberMe = {}", authentication, rememberMe);
        final Authentication fullyAuthenticated = getAuthenticationManager().authenticate(authentication);
        context.setAuthentication(fullyAuthenticated);
        if (rememberMe) {
            if (hasRememberMeServices()) {
                logger.debug("Invoking RememberMeServices");
                getRememberMeServices().loginSuccess(request, response, authentication);
            } else {
                throw new IllegalStateException(
                        "Requested RememberMe authentication but no RememberBeServices are available");
            }
        }
        logger.debug("Invoking session authentication strategy");
        sessionAuthenticationStrategy.onAuthentication(fullyAuthenticated, request, response);
        logger.debug("Invoking authentication success handler");
        vaadinAuthenticationSuccessHandler.onAuthenticationSuccess(fullyAuthenticated);
        return authentication;
    } catch (AuthenticationException e) {
        logger.debug("Authentication failed");
        context = SecurityContextHolder.createEmptyContext();
        if (hasRememberMeServices()) {
            logger.debug("Invoking RememberMeServices");
            getRememberMeServices().loginFail(request, response);
        }
        throw e;
    } finally {
        if (saveContextInSessionAfterLogin) {
            logger.debug("Saving security context in the session");
            WrappedSession session = getSession();
            if (session != null) {
                session.setAttribute(springSecurityContextKey, context);
            } else {
                logger.warn(
                        "Tried to save security context in the session, but no session was bound to the current thread");
            }
        }
    }
}

From source file:com.cfitzarl.cfjwed.core.security.SecurityContextLoader.java

/**
 * This method does all the heavy work in retrieving the context out of Redis. It inspects the servlet request
 * and tries to scrape the authentication token out of a header. If the header is missing or the token is not
 * found, an empty {@link SecurityContext} is returned, effectively telling Spring that the current request is
 * coming from an anonymous, unauthenticated actor.
 *
 * @param requestResponseHolder the request container
 * @return a security context//w  w  w  . j a v  a2s  .  c  o m
 */
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
    HttpServletRequest request = requestResponseHolder.getRequest();
    String tokenParam = coalesce(request.getHeader(SessionConstant.AUTH_TOKEN_HEADER),
            request.getParameter(SessionConstant.AUTH_TOKEN_PARAM));

    SecurityContext securityContext = new SecurityContextImpl();

    if (tokenParam == null || !redisService.exists(tokenParam)) {
        return securityContext;
    }

    String serializedAuthData = redisService.get(tokenParam);
    AuthenticationDTO dto;

    try {
        dto = new ObjectMapper().readValue(serializedAuthData, AuthenticationDTO.class);
    } catch (IOException e) {
        LOGGER.error("Error deserializing auth DTO", e);
        return securityContext;
    }

    Account account = accountDao.findByEmail(dto.getEmail());

    Collection<GrantedAuthority> gal = Collections.singletonList(new SimpleGrantedAuthority(dto.getRole()));
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(account.getId(), null,
            gal);
    token.setDetails(dto.getCsrf());

    securityContext.setAuthentication(token);

    return securityContext;
}

From source file:org.vaadin.spring.security.GenericVaadinSecurity.java

/**
 * {@inheritDoc}//from w ww .  ja  v  a  2s  .  com
 */
@Override
public void login(Authentication authentication, boolean rememberMe) throws AuthenticationException, Exception {

    // Ensure SecurityContext is never null
    SecurityContext context = SecurityContextHolder.getContext();

    // Retrieve HttpServletRequest / HttpServletResponse from RequestScope
    HttpServletRequest request = httpRequestResponseHolder.getCurrentRequest();
    HttpServletResponse response = httpRequestResponseHolder.getCurrentResponse();

    try {

        /*
         * Try to authenticate user
         */
        final Authentication fullyAuthenticated = getAuthenticationManager().authenticate(authentication);

        /*
         * Store Authentication within SecurityContext
         */
        context.setAuthentication(fullyAuthenticated);

        /*
         * Handle RememberMe
         */
        if (rememberMe) {

            /*
             * Locate RememberMeService
             */
            if (rememberMeService != null) {

                /*
                 * Store RememberMe within HttpServletRequest
                 */
                logger.debug("Registering RememberMe in request");
                request.setAttribute(AbstractRememberMeServices.DEFAULT_PARAMETER, rememberMe);

                /*
                 * Signal the RememberMeService of the login
                 */
                rememberMeService.loginSuccess(request, response, authentication);

            } else {
                logger.error(
                        "RememberMe Request while no <RememberMeServices> found within <ApplicationContext>");
            }

        }

        /*
         * Signal the SessionAuthenticationStrategy of the login
         */
        getSessionAuthenticationStrategy().onAuthentication(fullyAuthenticated, request, response);

        /*
         * Process AuthenticationSuccessHandler if configured
         */
        if (hasAuthenticationSuccessHandlerConfigured()) {
            getAuthenticationSuccessHandler().onAuthenticationSuccess(authentication);
        }

    } catch (AuthenticationException e) {

        /**
         * {@link DisabledException}            -> Optional
         * {@link LockedException}              -> Optional
         * {@link BadCredentialsException}      -> Required
         * 
         * Clear SecurityContext and handler Authentication Failure
         * If AuthenticationFailureHandler is configured, use it else
         * throw {@link AuthenticationFailureHandler}
         */
        context = generateNewContext();

        /*
         * Handle RememberMe authentication Failure
         * No need to check if it is being used; 
         * on failure invalidate all remember-me-tokens.
         */
        if (rememberMeService != null) {
            rememberMeService.loginFail(request, response);
        }

        /*
         * Process AuthenticationFailureHandler if configured
         */
        if (hasAuthenticationFailureHandlerConfigured()) {
            getAuthenticationFailureHandler().onAuthenticationFailure(e);
        } else {
            throw e;
        }

    } finally {

        /**
         * Store SecurityContext within the Session for the SecurityFilterChain
         * On error this will store an emtpy context, which will cause
         * the security filter chain to invalidate the authentication.
         * 
         * Context needs to be stored within the HttpSession so the {@link SecurityContextPersistenceFilter}
         * can make a call to the default configured {@link HttpSessionSecurityContextRepository}
         */
        HttpSession session = httpRequestResponseHolder.getCurrentRequest().getSession();
        session.setAttribute(springSecurityContextKey, context);

    }

}

From source file:com.evolveum.midpoint.security.impl.SecurityEnforcerImpl.java

@Override
public void setupPreAuthenticatedSecurityContext(Authentication authentication) {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(authentication);
}

From source file:com.evolveum.midpoint.init.InitialDataImport.java

public void init() throws SchemaException {
    LOGGER.info("Starting initial object import (if necessary).");

    OperationResult mainResult = new OperationResult(OPERATION_INITIAL_OBJECTS_IMPORT);
    Task task = taskManager.createTaskInstance(OPERATION_INITIAL_OBJECTS_IMPORT);
    task.setChannel(SchemaConstants.CHANNEL_GUI_INIT_URI);

    int count = 0;
    int errors = 0;

    File[] files = getInitialImportObjects();
    LOGGER.debug("Files to be imported: {}.", Arrays.toString(files));

    // We need to provide a fake Spring security context here.
    // We have to fake it because we do not have anything in the repository yet. And to get
    // something to the repository we need a context. Chicken and egg. So we fake the egg.
    SecurityContext securityContext = SecurityContextHolder.getContext();
    UserType userAdministrator = new UserType();
    prismContext.adopt(userAdministrator);
    userAdministrator.setName(new PolyStringType(new PolyString("initAdmin", "initAdmin")));
    MidPointPrincipal principal = new MidPointPrincipal(userAdministrator);
    AuthorizationType superAutzType = new AuthorizationType();
    prismContext.adopt(superAutzType, RoleType.class, new ItemPath(RoleType.F_AUTHORIZATION));
    superAutzType.getAction().add(AuthorizationConstants.AUTZ_ALL_URL);
    Authorization superAutz = new Authorization(superAutzType);
    Collection<Authorization> authorities = principal.getAuthorities();
    authorities.add(superAutz);//from  www .  j a  v a  2s. c om
    Authentication authentication = new PreAuthenticatedAuthenticationToken(principal, null);
    securityContext.setAuthentication(authentication);

    for (File file : files) {
        try {
            LOGGER.debug("Considering initial import of file {}.", file.getName());
            PrismObject object = prismContext.parseObject(file);
            if (ReportType.class.equals(object.getCompileTimeClass())) {
                ReportTypeUtil.applyDefinition(object, prismContext);
            }

            Boolean importObject = importObject(object, file, task, mainResult);
            if (importObject == null) {
                continue;
            }
            if (importObject) {
                count++;
            } else {
                errors++;
            }
        } catch (Exception ex) {
            LoggingUtils.logException(LOGGER, "Couldn't import file {}", ex, file.getName());
            mainResult.recordFatalError("Couldn't import file '" + file.getName() + "'", ex);
        }
    }

    securityContext.setAuthentication(null);

    mainResult.recomputeStatus("Couldn't import objects.");

    LOGGER.info("Initial object import finished ({} objects imported, {} errors)", count, errors);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Initialization status:\n" + mainResult.debugDump());
    }
}

From source file:org.geonode.security.GeoNodeCookieProcessingFilter.java

/**
 * //w  w  w  .j a  v a2s.  c  om
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest httpRequest = (HttpServletRequest) request;

    final SecurityContext securityContext = SecurityContextHolder.getContext();
    final Authentication existingAuth = securityContext.getAuthentication();

    final String gnCookie = getGeoNodeCookieValue(httpRequest);

    final boolean alreadyAuthenticated = existingAuth != null && existingAuth.isAuthenticated();
    final boolean anonymous = existingAuth == null || existingAuth instanceof AnonymousAuthenticationToken;
    // if logging in via geoserver web form, we want to short circuit the cookie
    // check below which might get triggered with an anon geonode cookie
    // the result looks like the login worked but because we replace the
    // auth below, it functionaly fails
    final boolean loggedInWithPassword = existingAuth instanceof UsernamePasswordAuthenticationToken
            && alreadyAuthenticated;
    final boolean hasPreviouslyValidatedGeoNodeCookie = (existingAuth instanceof GeoNodeSessionAuthToken)
            && existingAuth.getCredentials().equals(gnCookie);

    if (hasPreviouslyValidatedGeoNodeCookie)
        existingAuth.setAuthenticated(true);

    // if we still need to authenticate and we find the cookie, consult GeoNode for
    // an authentication
    final boolean authenticationRequired = (!alreadyAuthenticated || anonymous
            || !hasPreviouslyValidatedGeoNodeCookie);

    if (!loggedInWithPassword && authenticationRequired && gnCookie != null) {
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine(
                    "Found GeoNode cookie - checking if we have the authorizations in cache or if we have to reload from GeoNode");
        }
        try {
            Object principal = existingAuth == null ? null : existingAuth.getPrincipal();
            Collection<? extends GrantedAuthority> authorities = existingAuth == null ? null
                    : existingAuth.getAuthorities();
            Authentication authRequest = new GeoNodeSessionAuthToken(principal, gnCookie, authorities);
            final Authentication authResult = getSecurityManager().authenticate(authRequest);
            LOGGER.log(Level.FINE, "authResult : {0}", authResult);
            securityContext.setAuthentication(authResult);
        } catch (AuthenticationException e) {
            // we just go ahead and fall back on basic authentication
            LOGGER.log(Level.WARNING, "Error connecting to the GeoNode server for authentication purposes", e);
        }
    }

    // move forward along the chain
    chain.doFilter(request, response);
}

From source file:com.evolveum.midpoint.model.test.AbstractModelIntegrationTest.java

protected void resetAuthentication() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(null);
}

From source file:com.evolveum.midpoint.model.test.AbstractModelIntegrationTest.java

@AfterClass
protected void cleanUpSecurity() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(null);
}

From source file:com.evolveum.midpoint.model.test.AbstractModelIntegrationTest.java

protected void createSecurityContext(MidPointPrincipal principal) {
    SecurityContext context = new SecurityContextImpl();
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, null);
    context.setAuthentication(authentication);
    SecurityContextHolder.setContext(context);
}

From source file:com.evolveum.midpoint.model.test.AbstractModelIntegrationTest.java

protected void login(MidPointPrincipal principal) {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, null);
    securityContext.setAuthentication(authentication);
}