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

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

Introduction

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

Prototype

Authentication getAuthentication();

Source Link

Document

Obtains the currently authenticated principal, or an authentication request token.

Usage

From source file:fr.gael.dhus.server.http.valve.processings.ProcessingValve.java

/**
 * Logs information into temporary cache. According to the Valve
 * configuration, log will also display into the logger.
 *
 * @param request  the input user request to log.
 * @param response the response to the user to be incremented.
 *                 return the log entry.
 * @throws IOException// w ww.j  a v a2  s  .com
 * @throws ServletException
 */
private ProcessingInformation createProcessing(Request request, Response response)
        throws IOException, ServletException {
    String request_string = null;
    if (request.getQueryString() != null) {
        request_string = request.getRequestURL().append('?').append(request.getQueryString()).toString();
    } else {
        request_string = request.getRequestURL().toString();
    }

    ProcessingInformation pi = new ProcessingInformation(request_string);

    // Retrieve cookie to obtains existing context if any.
    Cookie integrityCookie = CookieKey.getIntegrityCookie(request.getCookies());

    SecurityContext ctx = null;
    if (integrityCookie != null) {
        String integrity = integrityCookie.getValue();
        if (integrity != null && !integrity.isEmpty()) {
            ctx = SEC_CTX_PROVIDER.getSecurityContext(integrity);
        }
    }
    if ((ctx != null) && (ctx.getAuthentication() != null)) {
        pi.setUsername(ctx.getAuthentication().getName());
    } else {
        String[] basicAuth = extractAndDecodeHeader(request.getHeader("Authorization"));
        if (basicAuth != null) {
            pi.setUsername(basicAuth[0]);
        }
    }
    pi.setRemoteAddress(ProxyWebAuthenticationDetails.getRemoteIp(request));
    pi.setRemoteHost(ProxyWebAuthenticationDetails.getRemoteHost(request));
    return pi;
}

From source file:com.ssbusy.controller.checkout.CheckoutController.java

@RequestMapping(value = "/checkout/singleship", method = RequestMethod.POST)
public String saveSingleShip(HttpServletRequest request, HttpServletResponse response, Model model,
        @ModelAttribute("orderInfoForm") OrderInfoForm orderInfoForm,
        @ModelAttribute("billingInfoForm") MyBillingInfoForm billingForm,
        @ModelAttribute("shippingInfoForm") MyShippingInfoForm shippingForm, BindingResult result)
        throws Exception {

    /*/*from   w ww  .  jav  a2s .  co  m*/
     * ??remember?
     */
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication auth = context.getAuthentication();
    Boolean b = (auth instanceof RememberMeAuthenticationToken)
            && ("integral_pay".equals(shippingForm.getPaymentMethod())
                    || "balance_pay".equals(shippingForm.getPaymentMethod()));
    if (b) {
        return REDIRECT_DENY;
    }
    return saveSingleShip0(request, response, model, orderInfoForm, billingForm, shippingForm, result, false);

}

From source file:de.theit.jenkins.crowd.CrowdServletFilter.java

/**
 * {@inheritDoc}//from  www .  jav  a 2s . c om
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // check if we have a token
        // if it is not present, we are not / no longer authenticated
        boolean isValidated = false;
        try {
            isValidated = this.configuration.crowdHttpAuthenticator.isAuthenticated(req, res);
        } catch (OperationFailedException ex) {
            LOG.log(Level.SEVERE, operationFailed(), ex);
        }

        if (!isValidated) {
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("User is not logged in (anymore) via Crowd => logout user");
            }
            SecurityContext sc = SecurityContextHolder.getContext();
            sc.setAuthentication(null);
            // close the SSO session
            if (null != this.rememberMe) {
                this.rememberMe.logout(req, res);
            }

            // invalidate the current session
            // (see SecurityRealm#doLogout())
            HttpSession session = req.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            SecurityContextHolder.clearContext();

            // reset remember-me cookie
            Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "");
            cookie.setPath(req.getContextPath().length() > 0 ? req.getContextPath() : "/");
            res.addCookie(cookie);
        } else {
            SecurityContext sc = SecurityContextHolder.getContext();

            if (!(sc.getAuthentication() instanceof CrowdAuthenticationToken)) {
                // user logged in via Crowd, but no Crowd-specific
                // authentication token available
                // => try to auto-login the user
                if (null != this.rememberMe) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine(
                                "User is logged in via Crowd, but no authentication token available; trying auto-login...");
                    }
                    Authentication auth = this.rememberMe.autoLogin(req, res);
                    if (null != auth) {
                        if (LOG.isLoggable(Level.FINE)) {
                            LOG.fine("User sucessfully logged in");
                        }
                        sc.setAuthentication(auth);
                    }
                }
            }
        }
    }

    this.defaultFilter.doFilter(request, response, chain);
}

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

protected void assertNoAuthentication() {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    assertNull("Unexpected authentication", securityContext.getAuthentication());
}

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

protected void assertLoggedInUser(String username) {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    Authentication authentication = securityContext.getAuthentication();
    if (authentication == null) {
        if (username == null) {
            return;
        } else {/*from  w ww  .  ja v  a 2s. c om*/
            AssertJUnit.fail("Expected logged in user '" + username
                    + "' but there was no authentication in the spring security context");
        }
    }
    Object principal = authentication.getPrincipal();
    if (principal == null) {
        if (username == null) {
            return;
        } else {
            AssertJUnit.fail("Expected logged in user '" + username
                    + "' but there was no principal in the spring security context");
        }
    }
    if (principal instanceof MidPointPrincipal) {
        MidPointPrincipal midPointPrincipal = (MidPointPrincipal) principal;
        UserType user = midPointPrincipal.getUser();
        if (user == null) {
            if (username == null) {
                return;
            } else {
                AssertJUnit.fail("Expected logged in user '" + username
                        + "' but there was no user in the spring security context");
            }
        }
        assertEquals("Wrong logged-in user", username, user.getName().getOrig());
    } else {
        AssertJUnit.fail("Expected logged in user '" + username
                + "' but there was unknown principal in the spring security context: " + principal);
    }
}

From source file:org.apache.ambari.server.controller.internal.WidgetResourceProvider.java

private boolean isScopeAllowedForUser(String scope) {
    if (scope.equals(WidgetEntity.USER_SCOPE)) {
        return true;
    }/*  w ww .  ja v a  2  s. co m*/

    // Only cluster operators are allowed to create widgets with cluster scope
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.getAuthentication().getAuthorities();
    boolean hasPermissionForClusterScope = false;
    for (GrantedAuthority grantedAuthority : securityContext.getAuthentication().getAuthorities()) {
        if (((AmbariGrantedAuthority) grantedAuthority).getPrivilegeEntity().getPermission()
                .getId() == PermissionEntity.AMBARI_ADMIN_PERMISSION
                || ((AmbariGrantedAuthority) grantedAuthority).getPrivilegeEntity().getPermission()
                        .getId() == PermissionEntity.CLUSTER_OPERATE_PERMISSION) {
            hasPermissionForClusterScope = true;
        }
    }
    if (hasPermissionForClusterScope) {
        return true;
    } else {
        return false;
    }
}

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   ww  w.j a va2 s . c  o  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.ambari.server.security.authorization.Users.java

/**
 * Modifies password of local user//from   w w  w.  j a  va2s  .co m
 * @throws AmbariException
 */
public synchronized void modifyPassword(String userName, String currentUserPassword, String newPassword)
        throws AmbariException {

    SecurityContext securityContext = SecurityContextHolder.getContext();
    String currentUserName = securityContext.getAuthentication().getName();
    if (currentUserName == null) {
        throw new AmbariException("Authentication required. Please sign in.");
    }

    UserEntity currentUserEntity = userDAO.findLocalUserByName(currentUserName);

    //Authenticate LDAP user
    boolean isLdapUser = false;
    if (currentUserEntity == null) {
        currentUserEntity = userDAO.findLdapUserByName(currentUserName);
        try {
            ldapAuthenticationProvider.authenticate(
                    new UsernamePasswordAuthenticationToken(currentUserName, currentUserPassword));
            isLdapUser = true;
        } catch (BadCredentialsException ex) {
            throw new AmbariException("Incorrect password provided for LDAP user " + currentUserName);
        }
    }

    boolean isCurrentUserAdmin = false;
    for (PrivilegeEntity privilegeEntity : currentUserEntity.getPrincipal().getPrivileges()) {
        if (privilegeEntity.getPermission().getPermissionName()
                .equals(PermissionEntity.AMBARI_ADMIN_PERMISSION_NAME)) {
            isCurrentUserAdmin = true;
            break;
        }
    }

    UserEntity userEntity = userDAO.findLocalUserByName(userName);

    if ((userEntity != null) && (currentUserEntity != null)) {
        if (!isCurrentUserAdmin && !userName.equals(currentUserName)) {
            throw new AmbariException("You can't change password of another user");
        }

        if ((isLdapUser && isCurrentUserAdmin) || (StringUtils.isNotEmpty(currentUserPassword)
                && passwordEncoder.matches(currentUserPassword, currentUserEntity.getUserPassword()))) {
            userEntity.setUserPassword(passwordEncoder.encode(newPassword));
            userDAO.merge(userEntity);
        } else {
            throw new AmbariException("Wrong current password provided");
        }

    } else {
        userEntity = userDAO.findLdapUserByName(userName);
        if (userEntity != null) {
            throw new AmbariException("Password of LDAP user cannot be modified");
        } else {
            throw new AmbariException("User " + userName + " not found");
        }
    }
}

From source file:org.apache.fineract.restwebservice.PlatformRestClient.java

/**
 * Creates a HTTP basic authentication credentials using the spring {@link SecurityContext} authentication credentials
 * /*  w w  w . ja  va 2  s  .  c  o m*/
 * @param securityContext {@link SecurityContext} object
 * @return basic authentication credentials
 */
public String createBasicAuthenticationCredentials(final SecurityContext securityContext) {
    String basicAuthenticationCredentials = null;

    if ((securityContext.getAuthentication() != null)
            && (securityContext.getAuthentication().getCredentials() != null)) {
        final String username = securityContext.getAuthentication().getName();
        final String password = securityContext.getAuthentication().getCredentials().toString();

        basicAuthenticationCredentials = this.createBasicAuthenticationCredentials(username, password);
    }

    return basicAuthenticationCredentials;
}

From source file:org.apache.nifi.authorization.user.NiFiUserUtils.java

/**
 * Returns the current NiFiUser or null if the current user is not a NiFiUser.
 *
 * @return user//from  w w  w  .  j av a  2 s.  c om
 */
public static NiFiUser getNiFiUser() {
    NiFiUser user = null;

    // obtain the principal in the current authentication
    final SecurityContext context = SecurityContextHolder.getContext();
    final Authentication authentication = context.getAuthentication();
    if (authentication != null) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof NiFiUserDetails) {
            user = ((NiFiUserDetails) principal).getNiFiUser();
        }
    }

    return user;
}