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:com.evolveum.midpoint.model.test.AbstractModelIntegrationTest.java

protected void loginSuperUser(MidPointPrincipal principal) throws SchemaException {
    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);/*w w  w.  j  av a 2 s .c  om*/
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, null);
    securityContext.setAuthentication(authentication);
}

From source file:org.apache.ambari.server.security.authorization.AmbariAuthorizationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String requestURI = httpRequest.getRequestURI();

    SecurityContext context = getSecurityContext();

    Authentication authentication = context.getAuthentication();

    //  If no explicit authenticated user is set, set it to the default user (if one is specified)
    if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
        Authentication defaultAuthentication = getDefaultAuthentication();
        if (defaultAuthentication != null) {
            context.setAuthentication(defaultAuthentication);
            authentication = defaultAuthentication;
        }//from w w  w  . ja  v a2  s  .  co m
    }

    if (authentication == null || !authentication.isAuthenticated()) {
        String token = httpRequest.getHeader(INTERNAL_TOKEN_HEADER);
        if (token != null) {
            context.setAuthentication(new InternalAuthenticationToken(token));
        } else {
            // for view access, we should redirect to the Ambari login
            if (requestURI.matches(VIEWS_CONTEXT_ALL_PATTERN)) {
                String queryString = httpRequest.getQueryString();
                String requestedURL = queryString == null ? requestURI : (requestURI + '?' + queryString);
                String redirectURL = httpResponse.encodeRedirectURL(LOGIN_REDIRECT_BASE + requestedURL);

                httpResponse.sendRedirect(redirectURL);
                return;
            } else {
                httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Authentication required");
            }
        }
    } else if (!authorizationPerformedInternally(requestURI)) {
        boolean authorized = false;

        for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
            if (grantedAuthority instanceof AmbariGrantedAuthority) {

                AmbariGrantedAuthority ambariGrantedAuthority = (AmbariGrantedAuthority) grantedAuthority;

                PrivilegeEntity privilegeEntity = ambariGrantedAuthority.getPrivilegeEntity();
                Integer permissionId = privilegeEntity.getPermission().getId();

                // admin has full access
                if (permissionId.equals(PermissionEntity.AMBARI_ADMINISTRATOR_PERMISSION)) {
                    authorized = true;
                    break;
                }

                // clusters require permission
                if (!"GET".equalsIgnoreCase(httpRequest.getMethod())
                        && requestURI.matches(API_CREDENTIALS_AMBARI_PATTERN)) {
                    // Only the administrator can operate on credentials where the alias starts with "ambari."
                    if (permissionId.equals(PermissionEntity.AMBARI_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (requestURI.matches(API_CLUSTERS_ALL_PATTERN)) {
                    if (permissionId.equals(PermissionEntity.CLUSTER_USER_PERMISSION)
                            || permissionId.equals(PermissionEntity.CLUSTER_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (STACK_ADVISOR_REGEX.matcher(requestURI).matches()) {
                    //TODO permissions model doesn't manage stacks api, but we need access to stack advisor to save configs
                    if (permissionId.equals(PermissionEntity.CLUSTER_USER_PERMISSION)
                            || permissionId.equals(PermissionEntity.CLUSTER_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (requestURI.matches(API_VIEWS_ALL_PATTERN)) {
                    // views require permission
                    if (permissionId.equals(PermissionEntity.VIEW_USER_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                } else if (requestURI.matches(API_PERSIST_ALL_PATTERN)) {
                    if (permissionId.equals(PermissionEntity.CLUSTER_ADMINISTRATOR_PERMISSION)) {
                        authorized = true;
                        break;
                    }
                }
            }
        }

        // allow GET for everything except /views, /api/v1/users, /api/v1/groups, /api/v1/ldap_sync_events
        if (!authorized && (!httpRequest.getMethod().equals("GET")
                || requestURI.matches(API_LDAP_SYNC_EVENTS_ALL_PATTERN))) {

            httpResponse.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
            httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "You do not have permissions to access this resource.");
            httpResponse.flushBuffer();
            return;
        }
    }

    if (AuthorizationHelper.getAuthenticatedName() != null) {
        httpResponse.setHeader("User", AuthorizationHelper.getAuthenticatedName());
    }
    chain.doFilter(request, response);
}

From source file:org.apache.rave.portal.service.impl.DefaultUserService.java

private SecurityContext createContext(final User user) {
    SecurityContext securityContext = new SecurityContextImpl();
    securityContext.setAuthentication(new AbstractAuthenticationToken(user.getAuthorities()) {
        private static final long serialVersionUID = 1L;

        @Override//  ww  w  .jav a2  s .c o  m
        public Object getCredentials() {
            return "N/A";
        }

        @Override
        public Object getPrincipal() {
            return user;
        }

        @Override
        public boolean isAuthenticated() {
            return true;
        }
    });
    return securityContext;
}

From source file:org.artifactory.webapp.servlet.AccessFilter.java

private void authenticateAndExecute(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
        SecurityContext securityContext) throws IOException, ServletException {
    // Try to see if authentication in cache based on the hashed header and client ip
    Authentication authentication = getNonUiCachedAuthentication(request);
    if (authentication != null && authentication.isAuthenticated()
            && !reAuthenticationRequired(request, authentication)) {
        log.debug("Header authentication {} found in cache.", authentication);
        useAuthentication(request, response, chain, authentication, securityContext);
        // Add to user change cache the login state
        addToUserChange(authentication);
        return;/*from   w  w  w.  java  2s.  co m*/
    }
    try {
        authFilter.doFilter(request, response, chain);
    } finally {
        Authentication newAuthentication = securityContext.getAuthentication();
        if (newAuthentication != null && newAuthentication.isAuthenticated()) {
            // Add to user change cache the login state
            addToUserChange(newAuthentication);
            // Save authentication (if session exists)
            if (RequestUtils.setAuthentication(request, newAuthentication, false)) {
                log.debug("Added authentication {} in Http session.", newAuthentication);
            } else {
                // If it did not work use the header cache
                // An authorization cache key with no header can only be used for Anonymous authentication
                AuthCacheKey authCacheKey = new AuthCacheKey(authFilter.getCacheKey(request),
                        request.getRemoteAddr());
                String username = newAuthentication.getName();
                if ((UserInfo.ANONYMOUS.equals(username) && authCacheKey.hasEmptyHeader())
                        || (!UserInfo.ANONYMOUS.equals(username) && !authCacheKey.hasEmptyHeader())) {
                    nonUiAuthCache.put(authCacheKey, newAuthentication);
                    userChangedCache.get(username).addAuthCacheKey(authCacheKey);
                    log.debug("Added authentication {} in cache.", newAuthentication);
                }
            }
        }
        securityContext.setAuthentication(null);
    }
}

From source file:org.artifactory.webapp.servlet.AccessFilter.java

private void useAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
        Authentication authentication, SecurityContext securityContext) throws IOException, ServletException {
    try {/*  w ww  .  j a v  a 2 s .  co m*/
        securityContext.setAuthentication(authentication);
        chain.doFilter(request, response);
        addToUserChange(authentication);
    } finally {
        securityContext.setAuthentication(null);
    }
}

From source file:org.artifactory.webapp.wicket.application.ArtifactoryWebSession.java

void bindAuthentication() {
    //Add the authentication to the request thread
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(authentication);
}

From source file:org.cloudfoundry.identity.uaa.mock.util.MockMvcUtils.java

public static SecurityContext getUaaSecurityContext(String username, ApplicationContext context) {
    ScimUserProvisioning userProvisioning = context.getBean(JdbcScimUserProvisioning.class);
    ScimUser user = userProvisioning.query("username eq \"" + username + "\" and origin eq \"uaa\"").get(0);
    UaaPrincipal uaaPrincipal = new UaaPrincipal(user.getId(), user.getUserName(), user.getPrimaryEmail(),
            user.getOrigin(), user.getExternalId(), IdentityZoneHolder.get().getId());
    UaaAuthentication principal = new UaaAuthentication(uaaPrincipal, null,
            Arrays.asList(UaaAuthority.fromAuthorities("uaa.user")),
            new UaaAuthenticationDetails(new MockHttpServletRequest()), true, System.currentTimeMillis());
    SecurityContext securityContext = new SecurityContextImpl();
    securityContext.setAuthentication(principal);
    return securityContext;
}

From source file:org.mifos.security.AuthenticationAuthorizationServiceFacadeImpl.java

@Override
public void reloadUserDetailsForSecurityContext(String username) {
    UserDetails userSecurityDetails = loadUserByUsername(username);
    MifosUser reloadedUserDetails = (MifosUser) userSecurityDetails;

    SecurityContext securityContext = SecurityContextHolder.getContext();
    if (securityContext == null) {
        securityContext = new SecurityContextImpl();
        SecurityContextHolder.setContext(securityContext);
    }//from ww  w  .  j  a va2 s .c o  m
    Authentication authentication = new UsernamePasswordAuthenticationToken(reloadedUserDetails,
            reloadedUserDetails, reloadedUserDetails.getAuthorities());
    securityContext.setAuthentication(authentication);
}

From source file:org.patientview.patientview.controller.lookinglocal.LookingLocalHomeController.java

/**
 * Deal with the URIs "/lookinglocal/auth", check POSTed credentials
 * @param request HTTP request//from w  w  w . j a va 2s .  co m
 * @param response HTTP response
 * @param username User entered username
 * @param password User entered password
 */
@RequestMapping(value = Routes.LOOKING_LOCAL_AUTH)
@ResponseBody
public void getAuth(HttpServletRequest request,
        @RequestParam(value = "username", required = false) String username,
        @RequestParam(value = "password", required = false) String password, HttpServletResponse response) {
    LOGGER.debug("auth start");

    PatientViewPasswordEncoder encoder = new PatientViewPasswordEncoder();
    User user = securityUserManager.get(username);

    if (user != null) {
        if (user.getPassword().equals(encoder.encode(password))) {

            // Authenticate user manually
            SecurityUser userLogin = (SecurityUser) userDetailsService.loadUserByUsername(username);
            SecurityContext securityContext = SecurityContextHolder.getContext();
            securityContext.setAuthentication(new UsernamePasswordAuthenticationToken(userLogin,
                    userLogin.getPassword(), userLogin.getAuthorities()));

            // manage extra authentication success handlers manually (usually
            // managed by PatientViewAuthenticationSuccessHandler.onAuthenticationSuccess)
            SecurityUser securityUser = (SecurityUser) securityContext.getAuthentication().getPrincipal();
            List<SpecialtyUserRole> specialtyUserRoles = userManager.getSpecialtyUserRoles(user);

            if (CollectionUtils.isNotEmpty(specialtyUserRoles)) {
                Specialty specialty = specialtyUserRoles.get(0).getSpecialty();
                securityUser.setSpecialty(specialty);
                // manually add to session
                HttpSession session = request.getSession(true);
                session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
                LOGGER.debug("auth passed");
                try {
                    LookingLocalUtils.getAuthXml(response);
                } catch (Exception e) {
                    LOGGER.error("Could not create home screen response output stream{}" + e);
                }

            } else {
                LOGGER.debug("auth failed, no specialties");
                try {
                    LookingLocalUtils.getErrorXml(response);
                } catch (Exception e) {
                    LOGGER.error("Could not create home screen response output stream{}" + e);
                }
            }
        } else {
            LOGGER.debug("auth failed, password");
            try {
                LookingLocalUtils.getErrorXml(response);
            } catch (Exception e) {
                LOGGER.error("Could not create home screen response output stream{}" + e);
            }
        }
    } else {
        LOGGER.debug("auth failed, user null");
        try {
            LookingLocalUtils.getErrorXml(response);
        } catch (Exception e) {
            LOGGER.error("Could not create home screen response output stream{}" + e);
        }
    }
}

From source file:org.springframework.security.extensions.portlet.PortletProcessingInterceptor.java

/**
 * Common preHandle method for both the action and render phases of the interceptor.
 *//* w w  w.j a va2  s . c o  m*/
private boolean preHandle(PortletRequest request, PortletResponse response, Object handler) throws Exception {

    // get the SecurityContext
    SecurityContext ctx = SecurityContextHolder.getContext();

    if (logger.isDebugEnabled())
        logger.debug("Checking secure context token: " + ctx.getAuthentication());

    // if there is no existing Authentication object, then lets create one
    if (ctx.getAuthentication() == null) {

        try {

            // build the authentication request from the PortletRequest
            PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(
                    getPrincipalFromRequest(request), getCredentialsFromRequest(request));

            // put the PortletRequest into the authentication request as the "details"
            authRequest.setDetails(authenticationDetailsSource.buildDetails(request));

            if (logger.isDebugEnabled())
                logger.debug("Beginning authentication request for user '" + authRequest.getName() + "'");

            onPreAuthentication(request, response);

            // ask the authentication manager to authenticate the request
            // it will throw an AuthenticationException if it fails, otherwise it succeeded
            Authentication authResult = authenticationManager.authenticate(authRequest);

            // process a successful authentication
            if (logger.isDebugEnabled()) {
                logger.debug("Authentication success: " + authResult);
            }

            ctx.setAuthentication(authResult);
            onSuccessfulAuthentication(request, response, authResult);

        } catch (AuthenticationException failed) {
            // process an unsuccessful authentication
            if (logger.isDebugEnabled()) {
                logger.debug("Authentication failed - updating ContextHolder to contain null Authentication",
                        failed);
            }
            ctx.setAuthentication(null);
            request.getPortletSession().setAttribute(
                    AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY, failed,
                    PortletSession.APPLICATION_SCOPE);
            onUnsuccessfulAuthentication(request, response, failed);
        }
    }

    return true;
}