Example usage for org.springframework.security.web.authentication.preauth PreAuthenticatedAuthenticationToken setDetails

List of usage examples for org.springframework.security.web.authentication.preauth PreAuthenticatedAuthenticationToken setDetails

Introduction

In this page you can find the example usage for org.springframework.security.web.authentication.preauth PreAuthenticatedAuthenticationToken setDetails.

Prototype

public void setDetails(Object details) 

Source Link

Usage

From source file:com.lll.util.SpringSecurityUtils.java

/**
 * UserDetails?Security Context.//from  www . ja  v a 2s .  c  o m
 * 
 * @param userDetails ??.
 * @param request ?IP??.
 */
public static void saveUserDetailsToContext(UserDetails userDetails, HttpServletRequest request) {
    PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(userDetails,
            userDetails.getPassword(), userDetails.getAuthorities());

    authentication.setDetails(new WebAuthenticationDetails(request));

    SecurityContextHolder.getContext().setAuthentication(authentication);
}

From source file:com.rosy.bill.security.SpringSecurityUtils.java

/**
 * UserDetails?Security Context./*from   w  ww .  java2 s.com*/
 * 
 * @param userDetails ??.
 * @param request ?IP??,?Null.
 */
public static void saveUserDetailsToContext(UserDetails userDetails, HttpServletRequest request) {
    PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(userDetails,
            userDetails.getPassword(), userDetails.getAuthorities());

    if (request != null) {
        authentication.setDetails(new WebAuthenticationDetails(request));
    }

    SecurityContextHolder.getContext().setAuthentication(authentication);
}

From source file:com.katsu.springframework.security.authentication.dni.DniAuthenticationProvider.java

private PreAuthenticatedAuthenticationToken createSuccessAuthentication(AbstractAuthenticationToken auth,
        UserDetails upat, Collection<? extends GrantedAuthority> roles) {
    PreAuthenticatedAuthenticationToken result = new PreAuthenticatedAuthenticationToken(upat,
            upat.getAuthorities(), roles);
    result.setDetails(auth.getDetails());
    return result;
}

From source file:com.example.AuthenticationController.java

@PostMapping("/factor")
public void accept(@RequestParam String factor, Principal principal, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (!"red".equals(factor)) {
        response.sendRedirect("/factor?error=true");
        return;//w ww . ja va2s.  c  o  m
    }
    Authentication authentication = (Authentication) principal;
    Collection<GrantedAuthority> authorities = new ArrayList<>(authentication.getAuthorities());
    authorities.add(new SimpleGrantedAuthority("ROLE_FACTOR"));
    PreAuthenticatedAuthenticationToken successful = new PreAuthenticatedAuthenticationToken(
            authentication.getPrincipal(), authentication.getCredentials(), authorities);
    successful.setDetails(authentication.getDetails());
    SecurityContextHolder.getContext().setAuthentication(successful);
    handler.onAuthenticationSuccess(request, response, successful);
}

From source file:com.bisone.saiku.security.replace.SessionService.java

public void authenticate(HttpServletRequest req, String username, String password) {
    try {//from  w  w w .j  av  a2  s. c  o  m
        PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(username, password);
        token.setDetails(new WebAuthenticationDetails(req));
        Authentication authentication = this.authenticationManager.authenticate(token);
        log.debug("Logging in with [{}]", authentication.getPrincipal());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } catch (BadCredentialsException bd) {
        throw new RuntimeException("Authentication failed for: " + username, bd);
    }

}

From source file:org.jasig.springframework.security.portlet.authentication.PortletAuthenticationProcessingFilter.java

/**
* Do the actual authentication for a pre-authenticated user.
*///from w w w  .ja  v a  2 s  .c  o m
private void doAuthenticate(PortletRequest request, PortletResponse response) {
    Authentication authResult;

    Object principal = getPreAuthenticatedPrincipal(request);
    Object credentials = getPreAuthenticatedCredentials(request);

    if (principal == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("No pre-authenticated principal found in request");
        }

        return;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("preAuthenticatedPrincipal = " + principal + ", trying to authenticate");
    }

    try {
        PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(principal,
                credentials);
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
        authResult = authenticationManager.authenticate(authRequest);
        successfulAuthentication(request, response, authResult);
    } catch (AuthenticationException failed) {
        unsuccessfulAuthentication(request, response, failed);

        if (!continueFilterChainOnUnsuccessfulAuthentication) {
            throw failed;
        }
    }
}

From source file:com.googlecode.fascinator.portal.security.filter.FascinatorAuthenticationInterceptorFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    JsonSessionState jsonSessionState = (JsonSessionState) request.getSession()
            .getAttribute("sso:com.googlecode.fascinator.portal.JsonSessionState");
    if (jsonSessionState != null) {
        PreAuthenticatedAuthenticationToken token = null;
        if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
            if (jsonSessionState.get("username") != null) {
                token = new PreAuthenticatedAuthenticationToken(jsonSessionState.get("username"), "password");
                SpringUser user = new SpringUser();
                user.setUsername((String) jsonSessionState.get("username"));
                user.setSource((String) jsonSessionState.get("source"));
                token.setDetails(user);
            } else {
                if (request.getParameter("apiKey") != null
                        && apiClients.get(request.getParameter("apiKey")) != null) {
                    String username = apiClients.get(request.getParameter("apiKey"));
                    token = new PreAuthenticatedAuthenticationToken(username, "password");
                    jsonSessionState.set("username", username);
                    jsonSessionState.set("source", "internal");
                    SpringUser user = new SpringUser();
                    user.setUsername(username);
                    user.setSource("internal");
                    token.setDetails(user);
                }//from  ww  w .  j  a v a  2s  . com
            }

        } else if (jsonSessionState.get("username") != null
                && !authentication.getName().equals(jsonSessionState.get("username"))) {
            token = new PreAuthenticatedAuthenticationToken(jsonSessionState.get("username"), "password");
            SpringUser user = new SpringUser();
            user.setUsername((String) jsonSessionState.get("username"));
            user.setSource((String) jsonSessionState.get("source"));
            token.setDetails(user);
        } else if (jsonSessionState.get("username") == null) {
            // must have logged out
            SecurityContextHolder.getContext().setAuthentication(null);
        }

        if (token != null) {
            // User has been logged in so let's create their credentials and
            // authenticate them
            authentication = authManager.authenticate(token);

            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }

    if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
        // SSO doesn't use a normal Roles plugin so we need to get the
        // roles again here and create a new token
        SpringUser user = (SpringUser) authentication.getCredentials();
        if (!user.isSsoRolesSet()) {
            List<GrantedAuthority> userRoles = buildRoleList(user, jsonSessionState);
            user.setSsoRolesSet(true);
            authentication = new PreAuthenticatedAuthenticationToken(user.getUsername(), user, userRoles);
            SecurityContextHolder.getContext().setAuthentication(authentication);

        }

    }
    filterChain.doFilter(request, response);

}

From source file:org.openinfinity.sso.security.spring.IdentityBasedAuthenticationUserDetailsService.java

public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) throws UsernameNotFoundException {
    LOGGER.debug("IdentityBasedAuthenticationUserDetailsService.loadUserDetails initialized.");
    String sessionIdentifier = httpServletRequest.getAttribute(ATTRIBUTE_SESSION_IDENTIFIER) != null
            ? (String) httpServletRequest.getAttribute(ATTRIBUTE_SESSION_IDENTIFIER)
            : (String) httpServletRequest.getAttribute(HEADER_SESSION_IDENTIFIER);
    String sessionId = (String) httpServletRequest.getAttribute(sessionIdentifier);
    Assert.isNull(sessionId, "Session id not found from the request.");
    LOGGER.debug(// w w w.j av a  2  s  . c o  m
            "IdentityBasedAuthenticationUserDetailsService.loadUserDetails fetched identity with session id ["
                    + sessionId + "]");
    final Identity identity = IdentityContext.loadIdentity(sessionId);
    LOGGER.debug("IdentityBasedAuthenticationUserDetailsService.loadUserDetails session found for identity id ["
            + identity.getUserPrincipal().getName() + "]");
    token.setDetails(identity);
    return new UserDetails() {

        private static final long serialVersionUID = 1404244132102359899L;

        public Collection<? extends GrantedAuthority> getAuthorities() {
            Collection<GrantedAuthority> grantedAuthorities = new TreeSet<GrantedAuthority>();
            for (Principal principal : identity.getAllPrincipalsForIdentity()) {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(principal.getName());
                grantedAuthorities.add(grantedAuthority);
            }
            return grantedAuthorities;
        }

        public String getPassword() {
            return identity.getPassword();
        }

        public String getUsername() {
            return identity.getUserPrincipal().getName();
        }

        public boolean isAccountNonExpired() {
            return true;
        }

        public boolean isAccountNonLocked() {
            return true;
        }

        public boolean isCredentialsNonExpired() {
            return true;
        }

        public boolean isEnabled() {
            return true;
        }

    };
}

From source file:org.apache.cxf.fediz.service.idp.STSPreAuthAuthenticationProvider.java

private Authentication handlePreAuthenticated(PreAuthenticatedAuthenticationToken preauthenticatedToken,
        IdpSTSClient sts) {/*from  ww w  .jav a 2 s .  c  om*/
    X509Certificate cert = (X509Certificate) preauthenticatedToken.getCredentials();
    if (cert == null) {
        return null;
    }

    // Convert the received certificate to a DOM Element to write it out "OnBehalfOf"
    Document doc = DOMUtils.newDocument();
    X509Data certElem = new X509Data(doc);
    try {
        certElem.addCertificate(cert);
        sts.setOnBehalfOf(certElem.getElement());
    } catch (XMLSecurityException e) {
        LOG.debug("Error parsing a client certificate", e);
        return null;
    }

    try {
        // Line below may be uncommented for debugging    
        // setTimeout(sts.getClient(), 3600000L);

        SecurityToken token = sts.requestSecurityToken(this.appliesTo);

        List<GrantedAuthority> authorities = createAuthorities(token);

        STSUserDetails details = new STSUserDetails(preauthenticatedToken.getName(), "", authorities, token);

        preauthenticatedToken.setDetails(details);

        LOG.debug("[IDP_TOKEN={}] provided for user '{}'", token.getId(), preauthenticatedToken.getName());
        return preauthenticatedToken;

    } catch (Exception ex) {
        LOG.info("Failed to authenticate user '" + preauthenticatedToken.getName() + "'", ex);
        return null;
    }
}

From source file:org.apache.nifi.web.security.authorization.NodeAuthorizedUserFilter.java

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

    // get the proxied user's authorities
    final String hexEncodedUserDetails = httpServletRequest.getHeader(PROXY_USER_DETAILS);

    // check if the request has the necessary header information and this instance is configured as a node
    if (StringUtils.isNotBlank(hexEncodedUserDetails) && properties.isNode()) {

        // get the flow controller from the Spring context
        final ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        final FlowController flowController = ctx.getBean("flowController", FlowController.class);

        // check that we are connected to the cluster
        if (flowController.getNodeId() != null) {
            try {
                // get the DN from the cert in the request
                final X509Certificate certificate = certificateExtractor
                        .extractClientCertificate((HttpServletRequest) request);
                if (certificate != null) {
                    // extract the principal from the certificate
                    final Object certificatePrincipal = principalExtractor.extractPrincipal(certificate);
                    final String dn = certificatePrincipal.toString();

                    // only consider the pre-authorized user when the request came from the NCM according to the DN in the certificate
                    final String clusterManagerDN = flowController.getClusterManagerDN();
                    if (clusterManagerDN != null && clusterManagerDN.equals(dn)) {
                        // deserialize hex encoded object
                        final Serializable userDetailsObj = WebUtils
                                .deserializeHexToObject(hexEncodedUserDetails);

                        // if we have a valid object, set the authentication token and bypass the remaining authentication processing chain
                        if (userDetailsObj instanceof NiFiUserDetails) {
                            final NiFiUserDetails userDetails = (NiFiUserDetails) userDetailsObj;
                            final NiFiUser user = userDetails.getNiFiUser();

                            // log the request attempt - response details will be logged later
                            logger.info(String.format("Attempting request for (%s) %s %s (source ip: %s)",
                                    user.getDn(), httpServletRequest.getMethod(),
                                    httpServletRequest.getRequestURL().toString(), request.getRemoteAddr()));

                            // we do not create the authentication token with the X509 certificate because the certificate is from the sending system, not the proxied user
                            final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
                                    userDetails, null, userDetails.getAuthorities());
                            token.setDetails(authenticationDetailsSource.buildDetails(request));
                            SecurityContextHolder.getContext().setAuthentication(token);
                        }//from ww  w.jav a  2s  .c o m
                    }
                }
            } catch (final ClassNotFoundException cnfe) {
                LOGGER.warn(
                        "Classpath issue detected because failed to deserialize authorized user in request header due to: "
                                + cnfe,
                        cnfe);
            }
        }
    }

    chain.doFilter(request, response);
}