Java Code Examples for io.undertow.server.HttpServerExchange#setResponseCookie()

The following examples show how to use io.undertow.server.HttpServerExchange#setResponseCookie() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TwitterStartAuthFlowPath.java    From PYX-Reloaded with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.startBlocking();
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    try {
        OAuth1RequestToken token = helper.requestToken();
        CookieImpl cookie = new CookieImpl("PYX-Twitter-Token", token.getRawResponse());
        cookie.setMaxAge(COOKIE_MAX_AGE);
        exchange.setResponseCookie(cookie);
        exchange.getResponseHeaders().add(Headers.LOCATION, helper.authorizationUrl(token) + "&force_login=false");
        exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
    } catch (Throwable ex) {
        logger.error("Failed processing the request." + exchange, ex);
        throw ex;
    }
}
 
Example 2
Source File: SessionCookieConfig.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void setSessionId(final HttpServerExchange exchange, final String sessionId) {
    Cookie cookie = new CookieImpl(cookieName, sessionId)
            .setPath(path)
            .setDomain(domain)
            .setDiscard(discard)
            .setSecure(secure)
            .setHttpOnly(httpOnly)
            .setComment(comment);
    if (maxAge > 0) {
        cookie.setMaxAge(maxAge);
    }
    exchange.setResponseCookie(cookie);
    UndertowLogger.SESSION_LOGGER.tracef("Setting session cookie session id %s on %s", sessionId, exchange);
}
 
Example 3
Source File: SessionCookieConfig.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void clearSession(final HttpServerExchange exchange, final String sessionId) {
    Cookie cookie = new CookieImpl(cookieName, sessionId)
            .setPath(path)
            .setDomain(domain)
            .setDiscard(discard)
            .setSecure(secure)
            .setHttpOnly(httpOnly)
            .setMaxAge(0);
    exchange.setResponseCookie(cookie);
    UndertowLogger.SESSION_LOGGER.tracef("Clearing session cookie session id %s on %s", sessionId, exchange);
}
 
Example 4
Source File: SessionCookieConfig.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setSessionId(final HttpServerExchange exchange, final String sessionId) {
    Cookie cookie = new CookieImpl(cookieName, sessionId)
            .setPath(path)
            .setDomain(domain)
            .setDiscard(discard)
            .setSecure(secure)
            .setHttpOnly(httpOnly)
            .setComment(comment);
    if (maxAge > 0) {
        cookie.setMaxAge(maxAge);
    }
    exchange.setResponseCookie(cookie);
    UndertowLogger.SESSION_LOGGER.tracef("Setting session cookie session id %s on %s", sessionId, exchange);
}
 
Example 5
Source File: SessionCookieConfig.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void clearSession(final HttpServerExchange exchange, final String sessionId) {
    Cookie cookie = new CookieImpl(cookieName, sessionId)
            .setPath(path)
            .setDomain(domain)
            .setDiscard(discard)
            .setSecure(secure)
            .setHttpOnly(httpOnly)
            .setMaxAge(0);
    exchange.setResponseCookie(cookie);
    UndertowLogger.SESSION_LOGGER.tracef("Clearing session cookie session id %s on %s", sessionId, exchange);
}
 
Example 6
Source File: GithubCallbackPath.java    From PYX-Reloaded with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.startBlocking();
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    String code = Utils.extractParam(exchange, "code");
    if (code == null) {
        exchange.setStatusCode(StatusCodes.BAD_REQUEST);
        return;
    }

    try {
        String accessToken = githubHelper.exchangeCode(code);

        CookieImpl cookie = new CookieImpl("PYX-Github-Token", accessToken);
        cookie.setMaxAge(COOKIE_MAX_AGE);
        exchange.setResponseCookie(cookie);
        exchange.getResponseHeaders().add(Headers.LOCATION, REDIRECT_LOCATION);
        exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
    } catch (Throwable ex) {
        logger.error("Failed processing the request: " + exchange, ex);
        throw ex;
    }
}
 
Example 7
Source File: TwitterCallbackPath.java    From PYX-Reloaded with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.startBlocking();
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    try {
        String token = Utils.extractParam(exchange, "oauth_token");
        String verifier = Utils.extractParam(exchange, "oauth_verifier");

        if (token == null || verifier == null)
            throw new IllegalArgumentException("Missing token or verifier!");

        Cookie tokensCookie = exchange.getRequestCookies().get("PYX-Twitter-Token");
        if (tokensCookie == null)
            throw new IllegalArgumentException("Missing 'PYX-Twitter-Token' cookie!");

        List<NameValuePair> tokens = URLEncodedUtils.parse(tokensCookie.getValue(), Charset.forName("UTF-8"));
        if (!Objects.equals(token, Utils.get(tokens, "oauth_token")))
            throw new IllegalStateException("Missing token in cookie or tokens don't match!");

        String secret = Utils.get(tokens, "oauth_token_secret");
        if (secret == null)
            throw new IllegalArgumentException("Missing token secret in cookie!");

        OAuth1AccessToken accessToken = helper.accessToken(new OAuth1RequestToken(token, secret), verifier);
        CookieImpl cookie = new CookieImpl("PYX-Twitter-Token", accessToken.getRawResponse());
        cookie.setMaxAge(COOKIE_MAX_AGE);
        exchange.setResponseCookie(cookie);
        exchange.getResponseHeaders().add(Headers.LOCATION, REDIRECT_LOCATION);
        exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
    } catch (Throwable ex) {
        logger.error("Failed processing the request: " + exchange, ex);
        throw ex;
    }
}
 
Example 8
Source File: CookieAttribute.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public void writeAttribute(final HttpServerExchange exchange, final String newValue) throws ReadOnlyAttributeException {
    exchange.setResponseCookie(new CookieImpl(cookieName, newValue));
}
 
Example 9
Source File: CookieAttribute.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void writeAttribute(final HttpServerExchange exchange, final String newValue) throws ReadOnlyAttributeException {
    exchange.setResponseCookie(new CookieImpl(cookieName, newValue));
}
 
Example 10
Source File: RegisterHandler.java    From PYX-Reloaded with Apache License 2.0 4 votes vote down vote up
@NotNull
@Override
public JsonWrapper handle(@Nullable User user, Parameters params, HttpServerExchange exchange) throws BaseJsonHandler.StatusException {
    if (banList.contains(exchange.getHostName()))
        throw new BaseCahHandler.CahException(Consts.ErrorCode.BANNED);

    PreparingShutdown.get().check();

    Consts.AuthType type;
    try {
        type = Consts.AuthType.parse(params.getStringNotNull(Consts.GeneralKeys.AUTH_TYPE));
    } catch (ParseException ex) {
        throw new BaseCahHandler.CahException(Consts.ErrorCode.BAD_REQUEST, ex);
    }

    UserAccount account;
    String nickname;
    switch (type) {
        case PASSWORD:
            nickname = params.getStringNotNull(Consts.UserData.NICKNAME);
            if (!Pattern.matches(Consts.VALID_NAME_PATTERN, nickname))
                throw new BaseCahHandler.CahException(Consts.ErrorCode.INVALID_NICK);

            account = accounts.getPasswordAccountForNickname(nickname);
            if (account == null) { // Without account
                user = new User(nickname, exchange.getHostName(), Sessions.generateNewId());
            } else {
                String password = params.getStringNotNull(Consts.AuthType.PASSWORD);
                if (password.isEmpty() || !BCrypt.checkpw(password, ((PasswordAccount) account).hashedPassword))
                    throw new BaseCahHandler.CahException(Consts.ErrorCode.WRONG_PASSWORD);

                user = User.withAccount(account, exchange.getHostName());
            }
            break;
        case GOOGLE:
            if (!socialLogin.googleEnabled())
                throw new BaseCahHandler.CahException(Consts.ErrorCode.UNSUPPORTED_AUTH_TYPE);

            GoogleIdToken.Payload googleToken = socialLogin.verifyGoogle(params.getStringNotNull(Consts.AuthType.GOOGLE));
            if (googleToken == null) throw new BaseCahHandler.CahException(Consts.ErrorCode.GOOGLE_INVALID_TOKEN);

            account = accounts.getGoogleAccount(googleToken);
            if (account == null) throw new BaseCahHandler.CahException(Consts.ErrorCode.GOOGLE_NOT_REGISTERED);

            nickname = account.username;
            user = User.withAccount(account, exchange.getHostName());
            break;
        case FACEBOOK:
            if (!socialLogin.facebookEnabled())
                throw new BaseCahHandler.CahException(Consts.ErrorCode.UNSUPPORTED_AUTH_TYPE);

            FacebookToken facebookToken = socialLogin.verifyFacebook(params.getStringNotNull(Consts.AuthType.FACEBOOK));
            if (facebookToken == null)
                throw new BaseCahHandler.CahException(Consts.ErrorCode.FACEBOOK_INVALID_TOKEN);

            account = accounts.getFacebookAccount(facebookToken);
            if (account == null) throw new BaseCahHandler.CahException(Consts.ErrorCode.FACEBOOK_NOT_REGISTERED);

            nickname = account.username;
            user = User.withAccount(account, exchange.getHostName());
            break;
        case GITHUB:
            if (!socialLogin.githubEnabled())
                throw new BaseCahHandler.CahException(Consts.ErrorCode.UNSUPPORTED_AUTH_TYPE);

            String githubToken = params.getStringNotNull(Consts.AuthType.GITHUB);

            GithubProfileInfo githubInfo = socialLogin.infoGithub(githubToken);
            account = accounts.getGithubAccount(githubInfo);
            if (account == null) throw new BaseCahHandler.CahException(Consts.ErrorCode.GITHUB_NOT_REGISTERED);

            nickname = account.username;
            user = User.withAccount(account, exchange.getHostName());
            break;
        case TWITTER:
            if (!socialLogin.twitterEnabled())
                throw new BaseCahHandler.CahException(Consts.ErrorCode.UNSUPPORTED_AUTH_TYPE);

            String twitterTokens = params.getStringNotNull(Consts.AuthType.TWITTER);

            TwitterProfileInfo twitterInfo = socialLogin.infoTwitter(twitterTokens);
            account = accounts.getTwitterAccount(twitterInfo);
            if (account == null) throw new BaseCahHandler.CahException(Consts.ErrorCode.TWITTER_NOT_REGISTERED);

            nickname = account.username;
            user = User.withAccount(account, exchange.getHostName());
            break;
        default:
            throw new BaseCahHandler.CahException(Consts.ErrorCode.BAD_REQUEST);
    }

    User registeredUser = users.checkAndAdd(user);
    if (registeredUser != null) user = registeredUser;
    exchange.setResponseCookie(new CookieImpl("PYX-Session", Sessions.get().add(user)));

    return new JsonWrapper()
            .add(Consts.UserData.NICKNAME, nickname)
            .add(Consts.UserData.IS_ADMIN, user.isAdmin());
}