Example usage for org.springframework.web.context.request RequestContextHolder currentRequestAttributes

List of usage examples for org.springframework.web.context.request RequestContextHolder currentRequestAttributes

Introduction

In this page you can find the example usage for org.springframework.web.context.request RequestContextHolder currentRequestAttributes.

Prototype

public static RequestAttributes currentRequestAttributes() throws IllegalStateException 

Source Link

Document

Return the RequestAttributes currently bound to the thread.

Usage

From source file:nl.surfnet.mujina.saml.RealAssertionConsumer.java

@Override
public User consume(Response samlResponse) throws AuthenticationException {

    try {/*from w w w  . ja  va2s . co m*/
        validatorSuite.validate(samlResponse);
    } catch (ValidationException ve) {
        log.warn("Response Message failed Validation", ve);
        throw new ServiceProviderAuthenticationException("Invalid SAML REsponse Message", ve);
    }

    checkResponseStatus(samlResponse);

    Assertion assertion = samlResponse.getAssertions().get(0);

    log.debug("authenticationResponseIssuingEntityName {}", samlResponse.getIssuer().getValue());

    log.debug("assertion.getID() {}", assertion.getID());
    log.debug("assertion.getSubject().getNameID().getValue() {}",
            assertion.getSubject().getNameID().getValue());

    AuthnStatement authnStatement = assertion.getAuthnStatements().get(0);

    log.debug("authnStatement.getAuthnInstant() {}", authnStatement.getAuthnInstant());

    Set<GrantedAuthority> authorities = extractAuthorities(assertion.getAttributeStatements());
    log.debug("Granted Authorities will be {}", authorities);

    final ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    final HttpSession session = requestAttributes.getRequest().getSession();
    session.setAttribute("assertionAttributes", assertion.getAttributeStatements());

    log.debug("assertion.getID() {}", assertion.getAuthnStatements());

    return new User(assertion.getSubject().getNameID().getValue(), samlResponse.getIssuer().getValue(),
            assertion.getIssuer().getValue(), samlResponse.getID(), assertion.getID(),
            samlResponse.getIssueInstant(), assertion.getIssueInstant(), authnStatement.getAuthnInstant(),
            authorities);

}

From source file:org.springjutsu.validation.context.MVCFormValidationContextHandler.java

/**
 * Initialize SPEL access to MVC scopes including
 * request parameters, request attributes,
 * MVC Path Variables and session attributes.
 *//*  w w w . ja v a2s  .c  o  m*/
@Override
@SuppressWarnings("unchecked")
public void initializeSPELResolver(SPELResolver spelResolver) {

    // initialize property accessors
    spelResolver.getScopedContext().addPropertyAccessor(new NamedAttributeAccessorPropertyAccessor());

    // access scoped request
    RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();

    // get path variable map
    Map<String, String> uriTemplateVars = (Map<String, String>) request
            .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
    if (uriTemplateVars == null) {
        uriTemplateVars = new HashMap<String, String>();
    }

    // initialize named contexts
    spelResolver.getScopedContext().addContext("requestParameters",
            new HttpRequestParametersNamedAttributeAccessor(request));
    spelResolver.getScopedContext().addContext("pathVariables", uriTemplateVars);
    spelResolver.getScopedContext().addContext("requestAttributes",
            new HttpRequestAttributesNamedAttributeAccessor(request));
    spelResolver.getScopedContext().addContext("session",
            new HttpSessionAttributesNamedAttributeAccessor(request));
}

From source file:com.google.code.rees.scope.spring.SpringConversationAdapter.java

/**
 * {@inheritDoc}//www.  ja v a 2 s .  c om
 */
@Override
public Map<String, String> getRequestContext() {

    HttpServletRequest currentRequest = ((ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes()).getRequest();

    if (!currentRequest.equals(this.request)) {
        this.request = currentRequest;
        requestContext = RequestContextUtil.getRequestContext(currentRequest);
    }

    return this.requestContext;
}

From source file:com.bsb.cms.commons.web.MossActionUtils.java

/**
 * // w ww . j  a v  a 2  s. c o m
 * ?session
 * 
 * @return
 */
private static HttpSession getUserSession() {
    final ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    final HttpSession contextSession = attr == null ? session : attr.getRequest().getSession(true);

    return contextSession;
}

From source file:de.uni_koeln.spinfo.maalr.mongo.SpringBackend.java

private void addUserInfo(LemmaVersion lemma) {
    String ip = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
            .getRemoteAddr();//from   w  w  w .  j  a v  a2s  .  co m
    lemma.setIP(ip);
    lemma.setCreatorRole(userInfos.getOrCreateCurrentUser().getRole());
}

From source file:org.jasig.portlet.courses.mvc.portlet.CourseCataloguePortletController.java

private String getPersonId() {
    Map<String, String> userInfo = (Map<String, String>) RequestContextHolder.currentRequestAttributes()
            .getAttribute(PortletRequest.USER_INFO, RequestAttributes.SCOPE_REQUEST);
    return (userInfo != null ? userInfo.get("personId") : null);
}

From source file:com.github.dactiv.common.spring.mvc.SpringMvcHolder.java

/**
 * ?spring mvcServletRequestAttributes/*from w  ww  .  j a v  a 2  s  .com*/
 * 
 * @return {@link ServletRequestAttributes}
 */
public static ServletRequestAttributes getServletRequestAttributes() {
    return (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
}

From source file:com.redhat.developers.msa.ola.OlaController.java

@CrossOrigin
@RequestMapping(method = RequestMethod.GET, value = "/logout", produces = "text/plain")
@ApiOperation("Logout")
public String logout() throws ServletException {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
            .getRequest();/*from   w w w . ja v  a  2  s.com*/
    request.logout();
    return "Logged out";
}

From source file:py.una.pol.karaku.util.Util.java

/**
 * Retorna la direccin desde donde esta accediendo el usuario de la sesin
 * actual.//from w ww. j a  va  2s . c om
 * 
 * @return cadena en formato NNN.NNN.NNN.NNN que representa la direccin del
 *         cliente
 */
public String getIpAdress() {

    return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
            .getRemoteAddr();
}

From source file:com.haulmont.restapi.auth.ExternalOAuthTokenGranter.java

@Override
public OAuth2AccessTokenResult issueToken(OAuth2AccessTokenRequest tokenRequest) {
    RestApiConfig config = configuration.getConfig(RestApiConfig.class);

    String login = tokenRequest.getLogin();
    Locale locale = tokenRequest.getLocale();

    Map<String, String> parameters = new HashMap<>();
    parameters.put("username", login);
    parameters.put("client_id", config.getRestClientId());
    parameters.put("scope", "rest-api");
    parameters.put("grant", GRANT_TYPE);

    UserSession session;/*from ww  w. j  a v  a2  s  .co m*/
    try {
        TrustedClientCredentials credentials = new TrustedClientCredentials(login,
                config.getTrustedClientPassword(), locale);
        credentials.setClientType(ClientType.REST_API);

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .currentRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            credentials.setIpAddress(request.getRemoteAddr());
            credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));
        } else {
            credentials.setClientInfo(makeClientInfo(""));
        }
        credentials.setParams(tokenRequest.getLoginParams());

        session = authenticationService.login(credentials).getSession();
    } catch (RestApiAccessDeniedException ex) {
        log.info("User is not allowed to use the REST API {}", login);
        throw new BadCredentialsException("User is not allowed to use the REST API");
    } catch (LoginException e) {
        log.info("Unable to issue token for REST API: {}", login);
        throw new BadCredentialsException("Bad credentials");
    }

    parameters.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString());
    for (Map.Entry<String, String> tokenParam : tokenRequest.getTokenDetails().entrySet()) {
        parameters.put(EXTENDED_DETAILS_ATTRIBUTE_PREFIX + tokenParam.getKey(), tokenParam.getValue());
    }

    // issue token using obtained Session, it is required for DB operations inside of persistent token store
    OAuth2AccessToken accessToken = withSecurityContext(new SecurityContext(session), () -> {
        ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(config.getRestClientId());
        TokenRequest tr = getRequestFactory().createTokenRequest(parameters, authenticatedClient);

        return grant(GRANT_TYPE, tr);
    });

    return new OAuth2AccessTokenResult(session, accessToken);
}