Example usage for javax.servlet.http HttpServletResponse encodeRedirectUrl

List of usage examples for javax.servlet.http HttpServletResponse encodeRedirectUrl

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse encodeRedirectUrl.

Prototype

@Deprecated
public String encodeRedirectUrl(String url);

Source Link

Usage

From source file:org.springframework.security.oauth.consumer.OAuthConsumerProcessingFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    Set<String> accessTokenDeps = getAccessTokenDependencies(request, response, chain);
    if (!accessTokenDeps.isEmpty()) {
        try {//from  w  ww  .j av a  2 s.c  om
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (requireAuthenticated && !authentication.isAuthenticated()) {
                throw new InsufficientAuthenticationException("An authenticated principal must be present.");
            }

            OAuthConsumerTokenServices tokenServices = getTokenServicesFactory()
                    .getTokenServices(authentication, request);
            List<OAuthConsumerToken> tokens = new ArrayList<OAuthConsumerToken>();
            for (String dependency : accessTokenDeps) {
                OAuthConsumerToken token = tokenServices.getToken(dependency);
                if (token == null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Obtaining request token for dependency: " + dependency);
                    }

                    //obtain authorization.
                    String callbackURL = response.encodeRedirectURL(getCallbackURL(request));
                    OAuthConsumerToken requestToken = getConsumerSupport()
                            .getUnauthorizedRequestToken(dependency, callbackURL);

                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Request token obtained for dependency " + dependency + ": " + requestToken);
                    }
                    tokenServices.storeToken(dependency, requestToken);
                    String redirect = getUserAuthorizationRedirectURL(requestToken, callbackURL);

                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Redirecting request to " + redirect
                                + " for user authorization of the request token for dependency " + dependency
                                + ".");
                    }
                    response.sendRedirect(redirect);
                    return;
                } else {
                    if (!token.isAccessToken()) {

                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Obtaining access token for dependency: " + dependency);
                        }

                        //authorize the request token and store it.
                        try {
                            token = getConsumerSupport().getAccessToken(token,
                                    request.getParameter(OAuthProviderParameter.oauth_verifier.toString()));
                        } finally {
                            //make sure any request tokens are removed.
                            tokenServices.removeToken(dependency);
                        }

                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Access token " + token + " obtained for dependency " + dependency
                                    + ". Now storing and using.");
                        }

                        tokenServices.storeToken(dependency, token);
                    } else if (LOG.isDebugEnabled()) {
                        LOG.debug("Authorized access token " + token + " loaded for dependency " + dependency
                                + ".");
                    }

                    //token already authorized.
                    tokens.add(token);
                }
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("Storing access tokens in request attribute '" + getAccessTokensRequestAttribute()
                        + "'.");
            }

            request.setAttribute(getAccessTokensRequestAttribute(), tokens);
            chain.doFilter(request, response);
        } catch (OAuthException ae) {
            fail(request, response, ae);
        } catch (ServletException e) {
            if (e.getRootCause() instanceof OAuthException) {
                fail(request, response, (OAuthException) e.getRootCause());
            } else {
                throw e;
            }
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No access token dependencies for request.");
        }
        chain.doFilter(servletRequest, servletResponse);
    }
}

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 .  j ava  2  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.wso2.carbon.identity.authenticator.clef.ClefAuthenticator.java

/**
 * This is override because of some values are hard coded and input
 * values validations are not required.//  w w  w  .ja v a 2  s. co m
 *
 * @param httpServletRequest    http request
 * @param httpServletResponse   http response
 * @param authenticationContext authentication context
 * @throws AuthenticationFailedException
 */
@Override
protected void initiateAuthenticationRequest(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, AuthenticationContext authenticationContext)
        throws AuthenticationFailedException {
    AuthenticatedUser authenticatedUser = getUsername(authenticationContext);
    String username = authenticatedUser.getAuthenticatedSubjectIdentifier();
    String clefUserId;
    String requestType;
    try {
        UserStoreManager userStoreManager = getUserStoreManager(authenticationContext);
        clefUserId = userStoreManager.getUserClaimValue(username, ClefAuthenticatorConstants.CLEF_ID, null);
        if (StringUtils.isEmpty(clefUserId)) {
            requestType = ClefAuthenticatorConstants.LOGIN;
        } else {
            requestType = ClefAuthenticatorConstants.CONNECT;
        }
        String clefLoginPage = ClefAuthenticatorConstants.CLEF_OAUTH_ENDPOINT;
        Map<String, String> authenticatorProperties = authenticationContext.getAuthenticatorProperties();
        String callbackurl = getCallbackUrl(authenticatorProperties);
        String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(
                authenticationContext.getQueryParams(), authenticationContext.getCallerSessionKey(),
                authenticationContext.getContextIdentifier());
        httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(clefLoginPage
                + ("?" + queryParams + "&" + OIDCAuthenticatorConstants.CLIENT_ID + "="
                        + authenticationContext.getAuthenticatorProperties()
                                .get(OIDCAuthenticatorConstants.CLIENT_ID))
                + "&" + ClefAuthenticatorConstants.REQUEST_TYPE + "=" + requestType + "&"
                + IdentityApplicationConstants.OAuth2.CALLBACK_URL + "=" + callbackurl));
        if (log.isDebugEnabled()) {
            log.debug("Request send to " + clefLoginPage);
        }
        authenticationContext.setCurrentAuthenticator(getName());
    } catch (UserStoreException e) {
        throw new AuthenticationFailedException(
                "Error occurred while loading user claim - " + ClefAuthenticatorConstants.CLEF_ID, e);
    } catch (IOException e) {
        throw new AuthenticationFailedException(e.getMessage(), e);
    }
}

From source file:org.mycore.frontend.editor.MCREditorServlet.java

private void processTargetSubmission(MCRServletJob job, MCRRequestParameters parms, Element editor)
        throws ServletException, IOException, TransformerException, SAXException {
    LOGGER.debug("Editor: processTargetSubmission ");

    HttpServletRequest req = job.getRequest();
    HttpServletResponse res = job.getResponse();

    editor.removeChild("failed");

    MCREditorSubmission sub = new MCREditorSubmission(parms, editor, true);

    if (sub.errors()) // validation failed, go back to editor form in
                      // webpage
    {//from w ww  . ja v a  2 s  .  c o  m
        editor.removeChild("input");
        editor.removeChild("repeats");
        editor.addContent(sub.buildInputElements());
        editor.addContent(sub.buildRepeatElements());
        editor.addContent(sub.buildFailedConditions());

        String sessionID = parms.getParameter("_session");

        // Redirect to webpage to reload editor form
        StringBuilder sb = new StringBuilder(MCRFrontendUtil.getBaseURL());
        String wp = parms.getParameter("_webpage");
        sb.append(wp);
        if (!wp.contains("XSL.editor.session.id=")) {
            sb.append("XSL.editor.session.id=");
            sb.append(sessionID);
        }
        LOGGER.debug("Editor redirect to " + sb.toString());
        res.sendRedirect(res.encodeRedirectURL(sb.toString()));

        return;
    }

    Document xml = sub.getXML();

    postProcess(editor, sub);

    String targetType = parms.getParameter("_target-type");
    LOGGER.debug("Editor: targettype=" + targetType);

    if (targetType.equals("servlet")) {
        sendToServlet(req, res, sub);
    } else if (targetType.equals("url")) {
        sendToURL(req, res);
    } else if (targetType.equals("webapp")) {
        sendToWebAppFile(req, res, sub, editor);
    } else if (targetType.equals("debug")) {
        sendToDebug(res, xml, sub);
    } else if (targetType.equals("display")) {
        getLayoutService().doLayout(req, res, new MCRJDOMContent(sub.getXML()));
    } else if (targetType.equals("subselect")) {
        List variables = sub.getVariables();
        String root = sub.getXML().getRootElement().getName();
        sendToSubSelect(res, parms, variables, root);
    } else {
        LOGGER.debug("Unknown targettype");
    }

    LOGGER.debug("Editor: processTargetSubmission DONE");
}

From source file:fll.web.report.StoreNonNumericNominees.java

@Override
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {

    final StringBuilder message = new StringBuilder();

    Connection connection = null;
    try {/*from w  ww  . j  a  v  a2 s  . co m*/
        final DataSource datasource = ApplicationAttributes.getDataSource(application);
        connection = datasource.getConnection();

        final int tournament = Queries.getCurrentTournament(connection);

        // get parameters
        final String nomineesStr = request.getParameter("non-numeric-nominees_data");
        if (null == nomineesStr || "".equals(nomineesStr)) {
            throw new FLLRuntimeException("Parameter 'non-numeric-nominees_data' cannot be null");
        }

        // decode JSON
        final ObjectMapper jsonMapper = new ObjectMapper();

        final Collection<NonNumericNominees> nominees = jsonMapper.readValue(nomineesStr,
                NonNumericNomineesTypeInformation.INSTANCE);
        for (final NonNumericNominees nominee : nominees) {
            nominee.store(connection, tournament);
        }

        message.append("<p id='success'>Non-numeric nominees saved to the database</p>");

    } catch (final SQLException e) {
        message.append("<p class='error'>Error saving non-numeric nominees into the database: " + e.getMessage()
                + "</p>");
        LOGGER.error(e, e);
        throw new RuntimeException("Error saving subjective data into the database", e);
    }

    session.setAttribute("message", message.toString());
    response.sendRedirect(response.encodeRedirectURL("non-numeric-nominees.jsp"));

}

From source file:org.kuali.mobility.sakai.controllers.SakaiController.java

@RequestMapping(value = "/{siteId}/resources", method = RequestMethod.GET)
public String getResources(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("siteId") String siteId, @RequestParam(value = "resId", required = false) String resId,
        @RequestParam(value = "type", required = false) String type, Model uiModel) {
    try {/*from w w w .ja va2  s  .  c o  m*/
        //resId = URLEncoder.encode(resId, "UTF-8");
        User user = (User) request.getSession().getAttribute(Constants.KME_USER_KEY);
        if (resId == null || resId.isEmpty()) {
            List<Resource> resources = sakaiSiteService.findSiteResources(siteId, user.getUserId(), null);
            uiModel.addAttribute("resources", resources);
        } else {
            char lastChar = resId.charAt(resId.length() - 1);
            if (lastChar == '/') {
                //Go into a sub-folder
                List<Resource> resources = sakaiSiteService.findSiteResources(siteId, user.getUserId(), resId);
                uiModel.addAttribute("resources", resources);
            } else {
                //download the file
                byte[] fileData = sakaiSiteService.getResource(resId, user.getUserId());
                if (fileData != null) {
                    String mimeType = type;

                    if (mimeType.equals(Constants.URL_MIME_TYPE)) {
                        String url = new String(fileData);
                        response.sendRedirect(response.encodeRedirectURL(url));
                    } else {
                        response.setContentType(mimeType);
                        response.setContentLength(fileData.length);
                        response.setHeader("Content-Disposition",
                                "attachment; filename=\"" + getFileName(resId) + "\"");
                        response.getOutputStream().write(fileData, 0, fileData.length);
                        return null;
                    }
                } else {
                    //couldn't find the resource
                    String referrer = request.getHeader("referer");
                    response.sendRedirect(referrer);
                    return null;
                }
            }
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    uiModel.addAttribute("siteId", siteId);
    return "sakai/resources";
}

From source file:org.wso2.carbon.identity.authenticator.wikid.WiKIDAuthenticator.java

/**
 * Initiate the authentication request/*ww w  . jav  a2s .  com*/
 */
@Override
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationContext context) throws AuthenticationFailedException {
    try {
        Map<String, String> authenticatorProperties = context.getAuthenticatorProperties();
        String username = authenticatorProperties.get(WiKIDAuthenticatorConstants.WIKID_USERNAME);
        String password = authenticatorProperties.get(WiKIDAuthenticatorConstants.WIKID_PASSWORD);
        if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
            if (StringUtils.isEmpty(login(username, password))) {
                log.error("Invalid username or password");
                throw new AuthenticationFailedException("Invalid username or password");
            } else {
                String retryParam = "";
                if (context.isRetrying()) {
                    retryParam = WiKIDAuthenticatorConstants.RETRY_PARAMS;
                }
                String wikidPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL().replace(
                        WiKIDAuthenticatorConstants.LOGIN_PAGE, WiKIDAuthenticatorConstants.WIKID_PAGE);
                String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(
                        context.getQueryParams(), context.getCallerSessionKey(),
                        context.getContextIdentifier());
                response.sendRedirect(response.encodeRedirectURL(wikidPage + ("?" + queryParams))
                        + WiKIDAuthenticatorConstants.AUTHENTICATORS + getName() + ":"
                        + WiKIDAuthenticatorConstants.LOCAL + "&" + retryParam);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Error while retrieving properties. WiKID username and password cannot be null");
            }
            throw new AuthenticationFailedException(
                    "Error while retrieving properties. WiKID username and password cannot be null");
        }
    } catch (IOException e) {
        throw new AuthenticationFailedException("Exception while redirecting the page: " + e.getMessage(), e);
    }
}

From source file:es.pode.soporte.seguridad.openId.ui.openid.OpenIDAuthenticationProcessingFilter.java

protected void successfulAuthenticationOpenID(HttpServletRequest request, HttpServletResponse response,
        Authentication authResult) throws IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Authentication success: " + authResult.toString());
    }/*from   ww  w  . j av  a  2 s .  c  o m*/

    SecurityContextHolder.getContext().setAuthentication(authResult);

    if (logger.isDebugEnabled()) {
        logger.debug(
                "Updated SecurityContextHolder to contain the following Authentication: '" + authResult + "'");
    }

    String targetUrl = obtainFullRequestUrl(request);
    if (logger.isDebugEnabled()) {
        logger.debug("[targetUrl vale] " + targetUrl);
    }

    if (targetUrl == null) {
        //  targetUrl = request.getContextPath() + "/PortadaAdministracion/PortadaAdministracion.do";
        targetUrl = "http://" + this.getAgregaPropertyValue("host")
                + this.getAgregaPropertyValue("admin.ws.subdominio")
                + "/portaladministracion/PortadaAdministracion/PortadaAdministracion.do";
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "targetUrl es null redirecting to target URL from HTTP Session (or default): " + targetUrl);
        }
        response.sendRedirect(response.encodeRedirectURL(targetUrl));
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Redirecting to target URL from HTTP Session (or default): " + targetUrl);
        }
        successfulAuthentication(request, response, authResult);
    }

}

From source file:org.etudes.mneme.tool.QuestionEditView.java

/**
 * {@inheritDoc}/*from  w  w w  .j  av  a 2s.  c o  m*/
 */
public void get(HttpServletRequest req, HttpServletResponse res, Context context, String[] params)
        throws IOException {
    // we need a qid, assessment and part id, then any number of parameters to form the return destination
    if (params.length < 5) {
        throw new IllegalArgumentException();
    }

    String destination = null;
    if (params.length > 5) {
        destination = "/" + StringUtil.unsplit(params, 5, params.length - 5, "/");
    }

    // if not specified, go to the main pools page
    else {
        destination = "/pools";
    }
    context.put("return", destination);

    String questionId = params[2];
    String assessmentId = params[3];
    String partId = params[4];

    boolean fixMode = params[1].equals("question_fix");
    if (fixMode)
        context.put("fix", Boolean.TRUE);

    // get the question to work on
    Question question = this.questionService.getQuestion(questionId);
    if (question == null)
        throw new IllegalArgumentException();

    // check security
    if (!this.questionService.allowEditQuestion(question)) {
        // redirect to error
        res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
        return;
    }

    // put the question in the context
    context.put("question", question);
    context.put("question_id", questionId);

    // next/prev for pools (not assessment) editing
    if (destination.startsWith("/pool_edit") || destination.startsWith("/pool_fix")) {
        context.put("nextPrev", Boolean.TRUE);

        // figure out the question id
        String returnDestParts[] = StringUtil.split(destination, "/");
        String sortCode = "0A";
        if (returnDestParts.length > 3 && (!"-".equals(returnDestParts[3])))
            sortCode = returnDestParts[3];

        QuestionService.FindQuestionsSort sort = PoolEditView.findSort(sortCode);

        // get questions
        List<Question> questions = questionService.findQuestions(question.getPool(), sort, null, null, null,
                null, null, null);

        // find this one ( 0 based)
        int pos = 0;
        for (Question q : questions) {
            if (q.equals(question)) {
                break;
            }
            pos++;
        }

        context.put("position", Integer.valueOf(pos + 1));
        context.put("size", Integer.valueOf(questions.size()));
    }

    // the question types
    List<QuestionPlugin> questionTypes = this.mnemeService.getQuestionPlugins();
    context.put("questionTypes", questionTypes);

    // select the question's current type
    Value value = this.uiService.newValue();
    value.setValue(question.getType());
    context.put("selectedQuestionType", value);

    // if we are adding directly to an assessment part
    if ((!"0".equals(assessmentId)) && (!"0".equals(partId))) {
        Assessment assessment = this.assessmentService.getAssessment(assessmentId);
        if (assessment == null) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
            return;
        }
        context.put("assessment", assessment);

        Part part = assessment.getParts().getPart(partId);
        if (part == null) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.invalid)));
            return;
        }
        context.put("part", part);

        // security check for the assessment edit
        if (!this.assessmentService.allowEditAssessment(assessment)) {
            // redirect to error
            res.sendRedirect(res.encodeRedirectURL(Web.returnUrl(req, "/error/" + Errors.unauthorized)));
            return;
        }

        // for the selected "for" part
        value = this.uiService.newValue();
        value.setValue(part.getId());
        context.put("partId", value);
    }

    new CKSetup().setCKCollectionAttrib(getDocsPath(), toolManager.getCurrentPlacement().getContext());

    uiService.render(ui, context);
}