Example usage for javax.servlet.http HttpServletResponse SC_FOUND

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

Introduction

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

Prototype

int SC_FOUND

To view the source code for javax.servlet.http HttpServletResponse SC_FOUND.

Click Source Link

Document

Status code (302) indicating that the resource reside temporarily under a different URI.

Usage

From source file:com.stormpath.sample.web.controllers.AuthenticationController.java

@RequestMapping(value = "/sso/redirect", method = RequestMethod.GET)
public void createSsoUrl(HttpServletResponse httpResponse,
        @RequestParam(value = "state", required = false) String state) {

    IdSiteUrlBuilder urlBuilder = cloudApplication.newIdSiteUrlBuilder()
            .setCallbackUri("http://localhost:8088/sso/response");

    if (Strings.hasText(state)) {
        urlBuilder.setState(state);/*from   w  ww  .j ava 2  s .c o m*/
    }

    httpResponse.setStatus(HttpServletResponse.SC_FOUND);

    httpResponse.setHeader("Location", urlBuilder.build());
}

From source file:org.apache.shindig.social.core.oauth2.OAuth2NormalizedRequest.java

public ResponseType getEnumeratedResponseType() throws OAuth2Exception {
    String respType = getResponseType();
    if (respType == null) {
        return null;
    }//from   ww  w . j  a v  a  2  s  .c om
    if (respType.equals("code")) {
        return ResponseType.CODE;
    } else if (respType.equals("token")) {
        return ResponseType.TOKEN;
    } else {
        OAuth2NormalizedResponse resp = new OAuth2NormalizedResponse();
        resp.setError(ErrorType.UNSUPPORTED_RESPONSE_TYPE.toString());
        resp.setErrorDescription("Unsupported response type");
        resp.setStatus(HttpServletResponse.SC_FOUND);
        resp.setBodyReturned(false);
        resp.setHeader("Location", OAuth2Utils.buildUrl(getRedirectURI(), resp.getResponseParameters(), null));
        throw new OAuth2Exception(resp);
    }
}

From source file:edu.harvard.i2b2.fhir.oauth2.ws.OAuth2AuthzEndpoint.java

@GET
@Path("authorize")
public Response authorize(@Context HttpServletRequest request, @Context HttpRequest httprequest)
        throws URISyntaxException, OAuthSystemException {
    String authorizationCode = null;
    try {//from  ww w  . j a v  a  2s  . c  o m
        logger.trace("got request to authorize for OAuth2");
        OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);
        OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());

        // build response according to response_type
        String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);

        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse
                .authorizationResponse(request, HttpServletResponse.SC_FOUND);

        String redirectURI = oauthRequest.getRedirectURI();
        String state = oauthRequest.getState();
        final OAuthResponse Oresponse = builder.location(redirectURI).buildQueryMessage();
        URI url = new URI(Oresponse.getLocationUri());
        Response response = Response.status(Oresponse.getResponseStatus()).location(url).build();
        if (url == null)
            throw new OAuthSystemException("redirectURI is missing");

        HttpSession session = request.getSession();

        String finalUri = successfulResponse(request);
        // finalUri+="&state="+state;
        //logger.info("generated finalUri:" + finalUri);
        session.setAttribute("redirectUri", oauthRequest.getRedirectURI());
        session.setAttribute("clientId", oauthRequest.getClientId());
        session.setAttribute("state", oauthRequest.getState());
        session.setAttribute("scope", oauthRequest.getScopes());

        session.setAttribute("finalUri", finalUri);
        //session.setAttribute("request", request);
        String clientId = (String) oauthRequest.getClientId();
        if (isClientIdValid(clientId, oauthRequest.getRedirectURI()) == true) {

            String uri = HttpHelper.getServletUri(request).toString() + "/i2b2/login.xhtml";
            logger.trace("redirecting to:" + uri);
            return Response.status(Status.MOVED_PERMANENTLY).location(new URI(uri))
                    .header("session_id", request.getSession().getId()).build();

        } else
            return Response.status(Status.UNAUTHORIZED).entity("client_id or redirect_uri is not valid")
                    .build();

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).header("xreason", e.getMessage())
                .build();
    }
}

From source file:org.jboss.as.test.clustering.cluster.web.authentication.FormAuthenticationWebFailoverTestCase.java

@Test
public void test(@ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IOException, URISyntaxException {

    URI uri1 = SecureServlet.createURI(baseURL1);
    URI uri2 = SecureServlet.createURI(baseURL2);

    try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) {
        HttpResponse response = client.execute(new HttpGet(uri1));
        try {//from w ww  .  j ava2 s  .c o  m
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertNull(response.getFirstHeader(SecureServlet.SESSION_ID_HEADER));
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        HttpPost login = new HttpPost(baseURL1.toURI().resolve("j_security_check"));

        List<NameValuePair> pairs = new ArrayList<>(2);
        pairs.add(new BasicNameValuePair("j_username", "allowed"));
        pairs.add(new BasicNameValuePair("j_password", "password"));

        login.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
        response = client.execute(login);
        try {
            Assert.assertEquals(HttpServletResponse.SC_FOUND, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        String sessionId = null;
        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertNotNull(response.getFirstHeader(SecureServlet.SESSION_ID_HEADER));
            sessionId = response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue();
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        undeploy(DEPLOYMENT_1);

        response = client.execute(new HttpGet(uri2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        deploy(DEPLOYMENT_1);

        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }
}

From source file:com.vmware.identity.samlservice.impl.AuthnRequestStateCookieWrapper.java

@Override
public void authenticate(AuthnRequestState t) throws SamlServiceException {
    log.debug("AuthnRequestStateCookieWrapper.authenticate is called");

    // check for session existence first
    Validate.notNull(t, "AuthnRequestState");
    HttpServletRequest request = t.getRequest();
    Validate.notNull(request, "request");
    SessionManager sessionManager = t.getSessionManager();
    Validate.notNull(sessionManager, "sessionManager");
    Session currentSession = Shared.getSession(sessionManager, request, t.getIdmAccessor().getTenant());
    if (currentSession != null) {
        log.debug("Found existing session {}", currentSession);
        // use session data here to determine identity
        PrincipalId principalId = currentSession.getPrincipalId();
        Validate.notNull(principalId, "principalId");
        t.setPrincipalId(principalId);/*ww  w  . j a va 2  s.co  m*/
        t.setAuthnMethod(currentSession.getAuthnMethod());
        t.setSessionId(currentSession.getId());

        //turning off the proxying flag since we will are using existing session for the user.
        if (t.isProxying())
            t.setProxying(false);
    } else if (this.getAuthenticator() != null || t.isProxying()) {
        // fall back to stored authenticator: currently it could be kerbros,pw, external.
        if (t.isProxying() && getExternalAuthenticator() != null)
            getExternalAuthenticator().authenticate(t);
        else if (!t.isProxying() && getAuthenticator() != null) {
            getAuthenticator().authenticate(t);
            t.createSession(null, null);
        } else {
            log.error("externel authenticator is not intialized! ");
            throw new SamlServiceException();
        }
    } else {
        // fall back to sending browser the login page.
        ValidationResult vr = new ValidationResult(HttpServletResponse.SC_FOUND, null, null);
        t.setValidationResult(vr);
    }
}

From source file:foo.domaintest.http.HttpApiModule.java

@Provides
@Param("status")/* w  w w . ja v  a  2 s .c om*/
Integer provideStatus(Multimap<String, String> params, @EasterEggs String easterEggUrl) {
    if (easterEggUrl == null) {
        String statusString = getFirst(params.get("status"), null);
        return statusString == null ? null : parseInt(statusString);
    }
    return HttpServletResponse.SC_FOUND;
}

From source file:net.ymate.module.oauth.impl.ImplicitGrantProcessor.java

private OAuthResponse __doParseResponseType(HttpServletRequest request, String clientId, String _redirectURI,
        String scope, String uid, String state) throws Exception {
    OAuthResponse _response;/*from  w w w  .  j a v  a2s  .  c om*/
    switch (__responseType) {
    case CODE:
        OAuthCodeBean _codeBean = new OAuthCodeBean(
                getOwner().getModuleCfg().getTokenGenerator().authorizationCode(), _redirectURI, clientId, uid,
                scope);
        _codeBean = saveOrUpdateCode(_codeBean);
        //
        OAuthASResponse.OAuthAuthorizationResponseBuilder _authBuilder = OAuthASResponse
                .authorizationResponse(request, HttpServletResponse.SC_FOUND).location(_redirectURI)
                .setCode(_codeBean.getCode());
        if (StringUtils.isNotBlank(state)) {
            _authBuilder.setParam(org.apache.oltu.oauth2.common.OAuth.OAUTH_STATE, state);
        }
        _response = _authBuilder.buildQueryMessage();
        break;
    case TOKEN:
        OAuthClientUserBean _clientUser = getClientUser(clientId, uid, IdType.UID);
        if (_clientUser == null) {
            _clientUser = new OAuthClientUserBean(clientId, uid, true, scope,
                    getOwner().getModuleCfg().getTokenGenerator().accessToken(), null,
                    getOwner().getModuleCfg().getTokenGenerator().refreshToken(), 0,
                    getOwner().getModuleCfg().getAccessTokenExpireIn());
        } else {
            _clientUser.setAuthorized(true);
            _clientUser.setLastAccessToken(_clientUser.getAccessToken());
            _clientUser.setAccessToken(getOwner().getModuleCfg().getTokenGenerator().accessToken());
            _clientUser.setRefreshToken(getOwner().getModuleCfg().getTokenGenerator().refreshToken());
            _clientUser.setScope(scope);
            _clientUser.setRefreshCount(0);
            _clientUser.setExpiresIn(getOwner().getModuleCfg().getAccessTokenExpireIn());
        }
        _clientUser = saveOrUpdateToken(_clientUser, false);
        //
        getOwner().getOwner().getEvents()
                .fireEvent(new OAuthEvent(getOwner(), OAuthEvent.EVENT.IMPLICIT).setEventSource(_clientUser));
        //
        OAuthResponse.OAuthResponseBuilder _builder = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)
                .setAccessToken(_clientUser.getAccessToken())
                .setExpiresIn(String.valueOf(_clientUser.getExpiresIn()))
                .setRefreshToken(_clientUser.getRefreshToken()).setScope(_clientUser.getScope())
                .setParam(IOAuth.Const.OPEN_ID, _clientUser.getOpenId());
        if (StringUtils.isNotBlank(state)) {
            _builder.setParam(org.apache.oltu.oauth2.common.OAuth.OAUTH_STATE, state);
        }
        _response = OAuthResponseUtils.appendParams(_clientUser.getAttributes(),
                OAuthResponseUtils.appendParams(getParams(), _builder)).buildJSONMessage();
        break;
    default:
        _response = buildError(IOAuth.ErrorType.UNSUPPORTED_RESPONSE_TYPE);
    }
    return _response;
}

From source file:org.wso2.carbon.identity.oauth.ui.endpoints.authz.OAuth2AuthzEndpoint.java

private String handleOAuthAuthorizationRequest(HttpServletRequest req)
        throws IOException, OAuthSystemException {
    OAuth2ClientValidationResponseDTO clientValidationResponseDTO = null;
    try {//w w  w.j a  va  2s  . c  o m
        // Extract the client_id and callback url from the request, because constructing an Amber
        // Authz request can cause an OAuthProblemException exception. In that case, that error
        // needs to be passed back to client. Before that we need to validate the client_id and callback URL
        String clientId = CharacterEncoder.getSafeText(req.getParameter("client_id"));
        String callbackURL = CharacterEncoder.getSafeText(req.getParameter("redirect_uri"));

        if (clientId != null) {
            clientValidationResponseDTO = validateClient(req, clientId, callbackURL);
        } else { // Client Id is not present in the request.
            log.warn("Client Id is not present in the authorization request.");
            HttpSession session = req.getSession();
            session.setAttribute(OAuthConstants.OAUTH_ERROR_CODE, OAuth2ErrorCodes.INVALID_REQUEST);
            session.setAttribute(OAuthConstants.OAUTH_ERROR_MESSAGE,
                    "Invalid Request. Client Id is not present in the request");
            String errorPageURL = CarbonUIUtil.getAdminConsoleURL(req) + "oauth/oauth-error.jsp";
            errorPageURL = errorPageURL.replace("/oauth2/authorize", "");
            return errorPageURL;
        }
        // Client is not valid. Do not send this error back to client, send to an error page instead.
        if (!clientValidationResponseDTO.getValidClient()) {
            HttpSession session = req.getSession();
            session.setAttribute(OAuthConstants.OAUTH_ERROR_CODE, clientValidationResponseDTO.getErrorCode());
            session.setAttribute(OAuthConstants.OAUTH_ERROR_MESSAGE, clientValidationResponseDTO.getErrorMsg());
            String errorPageURL = CarbonUIUtil.getAdminConsoleURL(req) + "oauth/oauth-error.jsp";
            errorPageURL = errorPageURL.replace("/oauth2/authorize", "");
            return errorPageURL;
        }

        // Now the client is valid, redirect him for authorization page.
        OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(req);
        OAuth2Parameters params = new OAuth2Parameters();
        params.setApplicationName(clientValidationResponseDTO.getApplicationName());
        params.setRedirectURI(clientValidationResponseDTO.getCallbackURL());
        params.setResponseType(oauthRequest.getResponseType());
        params.setScopes(oauthRequest.getScopes());
        params.setState(oauthRequest.getState());
        params.setClientId(clientId);

        HttpSession session = req.getSession();
        session.setAttribute(OAuthConstants.OAUTH2_PARAMS, params);
        String loginPage = CarbonUIUtil.getAdminConsoleURL(req) + "oauth/oauth2_authn_ajaxprocessor.jsp";
        loginPage = loginPage.replace("/oauth2/authorize", "");
        return loginPage;

    } catch (OAuthProblemException e) {
        log.error(e.getError(), e.getCause());
        return OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e)
                .location(clientValidationResponseDTO.getCallbackURL()).buildQueryMessage().getLocationUri();
    }
}

From source file:com.github.mfpdev.sample.googleOTP.GoogleOTPResource.java

@GET
@OAuthSecurity(enabled = false)/*from w  ww.  ja v  a 2 s . c o  m*/
@Path("/qrCode/{appId}/{appVersion}")
@ApiOperation(value = "Get the Google Authenticator QR Code URL", notes = "Redirect to the QR code URL, if exist in the user registration.  The QR code should be scanned by the Google Authenticator App", httpMethod = "GET", response = String.class)

@ApiResponses(value = { @ApiResponse(code = 302, message = "Redirect to the QR code URL"),
        @ApiResponse(code = 404, message = "QR code not found"),
        @ApiResponse(code = 401, message = "Unauthorized user") })

public void qrCode(
        @ApiParam(value = "App bundleId or package name", required = true) @PathParam("appId") String appId,
        @ApiParam(value = "App version", required = true) @PathParam("appVersion") String appVersion)
        throws Exception {

    //Get the username and password from the the authorization header
    Map<String, Object> usernamePassword = getEncodedUsernamePassword();

    //If username & password not sent or invalid, return a basic challenge to the client
    if (usernamePassword == null || !securityContext.validateCredentials(USER_LOGIN_SECURITY_CHECK_NAME,
            usernamePassword, request)) {
        response.addHeader("WWW-Authenticate", "Basic realm=\"Please provide your credentials\"");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    // Get the username after passing the basic authentication
    String user = (String) usernamePassword.get(UserLoginSecurityCheck.USER_KEY);

    // Build search criteria to locate the relevant client data by application, version and user
    ClientSearchCriteria criteria = new ClientSearchCriteria().byUser(USER_LOGIN_SECURITY_CHECK_NAME, user)
            .byApplication(appId, appVersion);

    List<ClientData> dataList = securityContext.findClientRegistrationData(criteria);
    GoogleOTPState googleOTPState = null;

    // Get the most recent generated GoogleOTPState object from registration service
    long lastActivityTime = -1;
    for (ClientData clientData : dataList) {
        GoogleOTPState currentGoogleOTPState = clientData.getProtectedAttributes().get(GOOGLE_OTP_STATE_KEY,
                GoogleOTPState.class);
        //Get the last generated key for that user and application
        if (currentGoogleOTPState.getTimeStamp() > lastActivityTime) {
            //Get the latest client in case user logged in to more then one device
            lastActivityTime = currentGoogleOTPState.getTimeStamp();
            googleOTPState = currentGoogleOTPState;
        }
    }

    if (googleOTPState != null) {
        //Redirect to the QR code URL
        throw new RedirectionException(HttpServletResponse.SC_FOUND, new URI(googleOTPState.getQrCodeURL()));
    } else {
        throw new NotFoundException(String.format("Cannot found QR code for user [%s]", user));
    }
}

From source file:com.sonicle.webtop.vfs.PublicService.java

@Override
public void processDefaultAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
    PublicPath path = new PublicPath(request.getPathInfo());
    WebTopSession wts = getWts();/*from   w  w  w  .j av  a  2s .  c om*/

    try {
        try {
            if (path.getContext().equals(PUBPATH_CONTEXT_LINK)) {
                FileUrlPath fileUrlPath = new FileUrlPath(path.getRemainingPath());

                SharingLink link = null;
                if (!StringUtils.isBlank(fileUrlPath.getLinkId())) {
                    link = manager.getSharingLink(fileUrlPath.getLinkId());
                }

                if (link == null) { // Link not found
                    logger.trace("Link not found [{}]", fileUrlPath.getLinkId());
                    writeErrorPage(request, response, wts, "linknotfound");

                } else if (link.isExpired(DateTimeUtils.now())) { // Link expired
                    logger.trace("Link expired [{}]", fileUrlPath.getLinkId());
                    writeErrorPage(request, response, wts, "linkexpired");

                } else if (!isLinkAuthorized(link)) { // Link not authorized
                    writeLinkPage(request, response, wts, "Authorize", link);

                } else if (link.getType().equals(SharingLink.TYPE_DOWNLOAD)) {
                    if (PathUtils.isFolder(link.getFilePath())) {
                        Integer dl = ServletUtils.getIntParameter(request, "dl", 0);

                        if (dl == 1) { // Download file request
                            String fileId = ServletUtils.getStringParameter(request, "fileId", true);

                            String outName;
                            if (PathUtils.isFolder(fileId)) {
                                if (PathUtils.isRootFolder(fileId)) {
                                    outName = StringUtils.defaultString(
                                            PathUtils.getFileName(link.getFilePath()), link.getLinkId());
                                } else {
                                    outName = PathUtils.getFileName(fileId);
                                }
                                outName += ".zip";
                            } else {
                                outName = PathUtils.getFileName(fileId);
                            }

                            String servicePublicUrl = WT.getServicePublicUrl(wts.getProfileDomainId(),
                                    SERVICE_ID);
                            String url = buildPublicLinkPathGetUrl(servicePublicUrl, link, outName, fileId);
                            ServletUtils.setLocationHeader(response, url);
                            response.setStatus(HttpServletResponse.SC_FOUND);

                        } else if (fileUrlPath.isGet()) { // Real binary stream
                            String p = ServletUtils.getStringParameter(request, "p", true);

                            String filePath = PathUtils.concatPaths(link.getFilePath(), p);
                            writeStoreFile(response, link.getStoreId(), filePath, fileUrlPath.getOutFileName());
                            manager.notifySharingLinkUsage(link.getLinkId(), filePath, wts.getRemoteIP(),
                                    wts.getPlainUserAgent());

                        } else {
                            writeLinkPage(request, response, wts, "DownloadLink", link);
                        }

                    } else {
                        Integer raw = ServletUtils.getIntParameter(request, "raw", 0);
                        if (raw == 1) { // Link points directly to raw data (no preview)
                            String servicePublicUrl = WT.getServicePublicUrl(wts.getProfileDomainId(),
                                    SERVICE_ID);
                            String url = VfsManager.buildLinkPublicGetUrl(servicePublicUrl, link);
                            ServletUtils.setLocationHeader(response, url);
                            response.setStatus(HttpServletResponse.SC_FOUND);

                        } else if (fileUrlPath.isGet()) { // Real binary stream
                            writeStoreFile(response, link.getStoreId(), link.getFilePath(),
                                    fileUrlPath.getOutFileName());
                            manager.notifySharingLinkUsage(link.getLinkId(), link.getFilePath(),
                                    wts.getRemoteIP(), wts.getPlainUserAgent());

                        } else {
                            logger.trace("Invalid request");
                            writeErrorPage(request, response, wts, "badrequest");
                        }
                    }

                } else if (link.getType().equals(SharingLink.TYPE_UPLOAD)) {
                    Integer maxUpload = WT.getCoreServiceSettings(SERVICE_ID).getUploadMaxFileSize();
                    VfsUserSettings us = new VfsUserSettings(SERVICE_ID, link.getProfileId());

                    JsWTSPublic.Vars vars = new JsWTSPublic.Vars();
                    vars.put("uploadMaxFileSize",
                            LangUtils.coalesce(us.getPublicUploadMaxFileSize(), maxUpload));
                    writeLinkPage(request, response, wts, "UploadLink", link, vars);
                }

            } else {
                logger.trace("Invalid context [{}]", path.getContext());
                writeErrorPage(request, response, wts, "badrequest");
            }

        } catch (Exception ex) {
            writeErrorPage(request, response, wts, "badrequest");
            //logger.trace("Error", t);
        }
    } catch (Throwable t) {
        logger.error("Unexpected error", t);
    }
}