Example usage for org.springframework.web.context.request ServletRequestAttributes getRequest

List of usage examples for org.springframework.web.context.request ServletRequestAttributes getRequest

Introduction

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

Prototype

public final HttpServletRequest getRequest() 

Source Link

Document

Exposes the native HttpServletRequest that we're wrapping.

Usage

From source file:com.jaspersoft.jasperserver.war.model.impl.AwsDataSourceTreeDataProvider.java

private String retrieveEndpointFromRequest() {
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = attr.getRequest();

    return request.getParameter("region");
}

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

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

    try {/*from w w w . j a  v a2  s  .  c  o 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:com.jaspersoft.jasperserver.war.model.impl.AwsDataSourceTreeDataProvider.java

private AWSCredentials retrieveCredentialsFromRequest() {
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = attr.getRequest();

    String accessKey = request.getParameter("awsAccessKey");
    String secretKey = request.getParameter("awsSecretKey");

    if (secretKey != null && secretKey.equals(
            messageSource.getMessage("input.password.substitution", null, LocaleContextHolder.getLocale()))) {
        String uri = request.getParameter("datasourceUri");
        AwsReportDataSource existingDs = (AwsReportDataSource) getRepositoryService().getResource(null, uri);
        if (existingDs != null) {
            secretKey = existingDs.getAWSSecretKey();
        }/*from ww  w .j  a v a  2  s .co  m*/
    }

    String arn = request.getParameter("arn");

    arn = !isBlank(arn) ? arn : null;

    return AwsCredentialUtil.getAWSCredentials(accessKey, secretKey, arn);
}

From source file:edu.dfci.cccb.mev.dataset.rest.controllers.WorkspaceController.java

@RequestMapping(method = GET, value = "/session/close")
@ResponseStatus(OK)/*from   w  w w .  j a  va  2 s .co  m*/
public void closeSession() {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    HttpSession session = attributes.getRequest().getSession(true);
    session.invalidate();
}

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 . ja  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);
}

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

@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
    String authenticationKey = authenticationKeyGenerator.extractKey(authentication);
    String userLogin = authentication.getName();

    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    Locale locale = restAuthUtils.extractLocaleFromRequestHeader(request);
    String refreshTokenValue = token.getRefreshToken() != null ? token.getRefreshToken().getValue() : null;
    serverTokenStore.storeAccessToken(token.getValue(), serializeAccessToken(token), authenticationKey,
            serializeAuthentication(authentication), token.getExpiration(), userLogin, locale,
            refreshTokenValue);/*from w  ww.jav a2 s. c om*/
    processSession(authentication, token.getValue());
    log.info("REST API access token stored: [{}] {}", authentication.getPrincipal(), token.getValue());
}

From source file:org.mitre.openid.connect.token.TofuUserApprovalHandler.java

/**
 * Get the auth time out of the current session and add it to the
 * auth request in the extensions map./*  www . j  a  v  a  2  s. co m*/
 * 
 * @param authorizationRequest
 */
private void setAuthTime(AuthorizationRequest authorizationRequest) {
    // Get the session auth time, if we have it, and store it in the request
    ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    if (attr != null) {
        HttpSession session = attr.getRequest().getSession();
        if (session != null) {
            Date authTime = (Date) session.getAttribute(AuthenticationTimeStamper.AUTH_TIMESTAMP);
            if (authTime != null) {
                String authTimeString = Long.toString(authTime.getTime());
                authorizationRequest.getExtensions().put(AuthenticationTimeStamper.AUTH_TIMESTAMP,
                        authTimeString);
            }
        }
    }
}

From source file:eu.supersede.fe.security.SecurityConfiguration.java

@Bean
AuthenticationProvider customAuthenticationProvider() {
    return new AuthenticationProvider() {
        private final Logger log = LoggerFactory.getLogger(this.getClass());

        @Override/*  w ww .  ja  v  a  2  s. c o  m*/
        @Transactional
        public Authentication authenticate(Authentication auth) throws AuthenticationException {
            String username = (String) auth.getPrincipal();
            String password = (String) auth.getCredentials();

            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
                    .currentRequestAttributes();
            HttpServletRequest req = attr.getRequest();
            String tenantId = req.getHeader("TenantId");

            if (tenantId == null) {
                log.error("Tenant provided");
                throw new BadCredentialsException("Invalid login request: missing tenant");
            }

            AuthorizationToken token = getAuthToken(username, password, tenantId);
            User user = users.findByUsername(username);

            if (user == null) {
                log.error("Username not found in Database");
                throw new BadCredentialsException("Invalid login request: user " + username + " not found");
            }

            // get authorities from profiles
            List<Profile> profiles = user.getProfiles();
            String[] authorities = new String[profiles.size()];

            for (int i = 0; i < profiles.size(); i++) {
                authorities[i] = "ROLE_" + profiles.get(i).getName();
            }

            log.debug("User has " + authorities.length + " authorities");

            List<GrantedAuthority> permissions = AuthorityUtils.createAuthorityList(authorities);
            DatabaseUser dbUser = new DatabaseUser(user.getUserId(),
                    user.getFirstName() + " " + user.getLastName(), user.getEmail(), password, token, true,
                    true, true, true, permissions, user.getLocale());

            return new UsernamePasswordAuthenticationToken(dbUser, password, permissions);// AUTHORITIES
        }

        private AuthorizationToken getAuthToken(String username, String password, String tenantId) {
            AuthorizationToken token = null;

            if (AUTH_MANAGER_ENABLED) {
                try {
                    token = proxy.getIFAuthenticationManager(tenantId).getAuthorizationToken(username, password,
                            tenantId);
                } catch (HttpClientErrorException e) {
                    log.error("Invalid username and password.");
                } catch (NullPointerException e1) {
                    log.error("Authorization token is null, check your if.properties file in the conf/ folder");
                } catch (Exception e2) {
                    e2.printStackTrace();
                }

                if (token == null || token.getAccessToken() == null) {
                    log.error("Supersede integration token is null");
                    throw new BadCredentialsException(
                            "Invalid login request: authentication manager token is null");
                }
            } else {
                log.warn("IF Authentication Manager disable, user token is NULL");
            }

            return token;
        }

        @Override
        @SuppressWarnings("rawtypes")
        public boolean supports(Class authentication) {
            return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
        }
    };
}

From source file:com.vsc.dayspring.security.ShiroDbRealm.java

/**
 * ?,.//from ww  w  .j a v  a  2s.c om
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes();
    String serverName = attributes.getRequest().getHeader("Host");
    if (StringUtils.isEmpty(serverName)) {
        serverName = attributes.getRequest().getServerName();
    }

    if (this.getSubDomains(KEY_APP_DOMAIN).contains(serverName)) {
        throw new AuthenticationException();
    }

    MyUsernamePasswordToken token = (MyUsernamePasswordToken) authcToken;

    List<Account> accountList = null;
    List<CompanyAccount> companyAccountList = null;

    if (token.getUsername() == null) {
        return null;
    }

    byte[] salt = null;

    //DEMO&&?
    if (CodeConstant.CODE_WHETHER_1.equals(CodeConstant.SYS_TYPE_FLAG)
            && CodeConstant.CODE_LOGIN_TYPE_SERIAL_NUMBER_USER.equals(token.getType())) {
        companyAccountList = compAccountService.getCompAccountBySerialNumber(token.getUsername());
        if (CollectionUtils.isEmpty(companyAccountList)) {
            throw new AuthenticationException();
        }
        CompanyAccount loginInfo = companyAccountList.get(0);
        Company company = companyMapper.selectByPrimaryKey(loginInfo.getCompUuid());
        if (company == null || CodeConstant.CODE_DELETE_FLAG_YES.equals(company.getDeleteFlag())) {
            throw new AuthenticationException();
        }
        loginInfo.setCompInitFlg(company.getInitFlag());
        loginInfo.setCompName(company.getShortName());
        salt = DigestUtils.generateSalt(AuthServer.SALT_SIZE);
        SimpleHash hash = new SimpleHash(HASH_ALGORITHM, token.getPassword(), ByteSource.Util.bytes(salt),
                HASH_INTERATIONS);
        return new SimpleAuthenticationInfo(loginInfo, hash.toHex(), ByteSource.Util.bytes(salt), getName());
    } else {

        if (token.getUsername().toLowerCase().indexOf(ConditionConstant.CONDITION_AT_YOWITS_COM) > 0) {
            // TODO DEBUG
            try {
                accountList = authServer.getLoginInfo(token.getUsername());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // TODO DEBUG
            try {
                companyAccountList = compAccountService.getCompAccountCountNoOrgByLoginId(token.getUsername());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (!CollectionUtils.isEmpty(companyAccountList)) {

            CompanyAccount loginInfo = companyAccountList.get(0);

            if ("1".equals(loginInfo.getDeleteFlag())) {

                throw new AuthenticationException();
            }

            // ?wizard uuid????
            if (StringUtils.isEmpty(loginInfo.getWizardUuid())) {
                Company company = companyMapper.selectByPrimaryKey(loginInfo.getCompUuid());

                if (company == null || CodeConstant.CODE_DELETE_FLAG_YES.equals(company.getDeleteFlag())) {

                    throw new AuthenticationException();
                }

                loginInfo.setCompInitFlg(company.getInitFlag());
                loginInfo.setCompName(company.getShortName());
            }

            salt = EncodeUtils.decodeHex(loginInfo.getSalt());
            return new SimpleAuthenticationInfo(loginInfo, loginInfo.getPassword(), ByteSource.Util.bytes(salt),
                    getName());

        } else if (!CollectionUtils.isEmpty(accountList)) {

            if (!this.getSubDomains(KEY_OFFIC_DOMAIN).contains(serverName)) {
                throw new AuthenticationException();
            }

            Account loginInfo = accountList.get(0);

            if ("1".equals(loginInfo.getDeleteFlag())) {
                throw new AuthenticationException();
            }

            salt = EncodeUtils.decodeHex(loginInfo.getSalt());
            return new SimpleAuthenticationInfo(loginInfo, loginInfo.getPassword(), ByteSource.Util.bytes(salt),
                    getName());

        } else {
            throw new AuthenticationException();
        }
    }
}

From source file:org.jahia.modules.spamfiltering.rules.SpamFilteringRuleService.java

/**
 * Verifies the content of the node with anti-spam service and applies spam filtering (by assigning a special mixin).
 * /*  ww  w  .  j  a  v  a2 s  .co  m*/
 * @param nodeFact
 *            the node which content should be checked
 * @param maxSpamCount the number of maximum spams tolerated before the user is locked and his session is killed.
 * @param drools
 *            the rule engine helper class
 * @throws RepositoryException
 *             in case of an error
 */
public void checkForSpam(AddedNodeFact nodeFact, Integer maxSpamCount, KnowledgeHelper drools)
        throws RepositoryException {
    if (logger.isDebugEnabled()) {
        logger.debug("Checking content of the node {} for spam", nodeFact.getPath());
    }

    try {
        User user = (User) drools.getWorkingMemory().getGlobal("user");

        HttpServletRequest httpServletRequest = spamFilter.getHttpServletRequest();

        if (httpServletRequest == null) {
            // we didn't manage to get the request from our own filter, try to access it through Spring MVC's
            // framework
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) {
                ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
                httpServletRequest = servletRequestAttributes.getRequest();
            }
        }

        boolean isSpam = false;
        JCRNodeWrapper node = nodeFact.getNode();
        String text = getTextContent(node);
        if (StringUtils.isNotEmpty(text)) {
            isSpam = spamFilteringService.isSpam(text, node, httpServletRequest);
        }

        if (isSpam) {
            if (!node.isNodeType(SPAM_DETECTED_MIXIN)) {
                // is detected as spam -> add mixin
                node.getSession().checkout(node);
                node.addMixin(SPAM_DETECTED_MIXIN);
            }
            if (maxSpamCount != null && httpServletRequest != null) {
                HttpSession httpSession = httpServletRequest.getSession(false);
                JahiaUser jahiaUser = user.getJahiaUser();
                if (httpSession != null && !"guest".equals(jahiaUser.getName())) {
                    String spamSessionsValue = jahiaUser.getProperty(SPAM_SESSIONS_PROPERTY_NAME);
                    List<String> spamSessions = new ArrayList<String>();
                    if (spamSessionsValue != null) {
                        spamSessions.addAll(Arrays.asList(spamSessionsValue.split(",")));
                    }

                    spamSessions.add(httpSession.getId());

                    if (spamSessions.size() >= maxSpamCount) {
                        logger.info("Maximum number of spam count reached (" + maxSpamCount
                                + "), locking user account and killing session...");
                        logger.info("Marking session " + httpSession.getId()
                                + " as invalid and will be killed on next access.");
                        spamFilter.addSessionToKill(httpSession.getId());
                        // add code to lock account
                        logger.info("Locking account " + jahiaUser + "...");
                        jahiaUser.setProperty("j:accountLocked", "true");
                        if (sendSpamNotificationEmails) {
                            logger.info("Sending account lock notification to administrator...");
                            sendAccountLockNotification(node, jahiaUser, httpServletRequest);
                        }
                        // we clear the session list to avoid it growing to big
                        spamSessions.clear();
                    } else {
                        logger.info("User " + jahiaUser + " has sent " + spamSessions.size() + " spam so far.");
                    }

                    if (spamSessions.size() > 0) {
                        jahiaUser.setProperty(SPAM_SESSIONS_PROPERTY_NAME, StringUtils.join(spamSessions, ","));
                    } else {
                        jahiaUser.removeProperty(SPAM_SESSIONS_PROPERTY_NAME);
                    }

                }
            }
        } else if (node.isNodeType(SPAM_DETECTED_MIXIN)) {
            // no longer spam -> remove mixin
            node.getSession().checkout(node);
            node.removeMixin(SPAM_DETECTED_MIXIN);
        }
        logger.info("Content of the node {} is{} detected as spam", node.getPath(), !isSpam ? " not" : "");
    } catch (Exception e) {
        logger.warn("Unable to check the content of the node " + nodeFact.getPath() + " for spam. Cause: "
                + e.getMessage(), e);
    }
}