io.undertow.server.handlers.CookieImpl Java Examples

The following examples show how to use io.undertow.server.handlers.CookieImpl. 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: AdminController.java    From mangooio with Apache License 2.0 6 votes vote down vote up
private Cookie getAdminCookie(boolean includeTwoFactor) {
    PasetoV1LocalBuilder token = Pasetos.V1.LOCAL.builder()
            .setSharedSecret(new SecretKeySpec(this.config.getApplicationSecret().getBytes(StandardCharsets.UTF_8), "AES"))
            .setExpiration(LocalDateTime.now().plusMinutes(30).toInstant(ZoneOffset.UTC))
            .claim("uuid", MangooUtils.randomString(32));
    
    if (includeTwoFactor && StringUtils.isNotBlank(this.config.getApplicationAdminSecret())) {
        token.claim("twofactor", Boolean.TRUE);
    }

    return new CookieImpl(Default.ADMIN_COOKIE_NAME.toString())
            .setValue(token.compact())
            .setHttpOnly(true)
            .setSecure(Application.inProdMode())
            .setPath("/")
            .setSameSite(true)
            .setSameSiteMode("Strict");
}
 
Example #2
Source File: Cookies.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
private static void handleValue(CookieImpl cookie, String key, String value) {
    if (key.equalsIgnoreCase("path")) {
        cookie.setPath(value);
    } else if (key.equalsIgnoreCase("domain")) {
        cookie.setDomain(value);
    } else if (key.equalsIgnoreCase("max-age")) {
        cookie.setMaxAge(Integer.parseInt(value));
    } else if (key.equalsIgnoreCase("expires")) {
        cookie.setExpires(DateUtils.parseDate(value));
    } else if (key.equalsIgnoreCase("discard")) {
        cookie.setDiscard(true);
    } else if (key.equalsIgnoreCase("secure")) {
        cookie.setSecure(true);
    } else if (key.equalsIgnoreCase("httpOnly")) {
        cookie.setHttpOnly(true);
    } else if (key.equalsIgnoreCase("version")) {
        cookie.setVersion(Integer.parseInt(value));
    } else if (key.equalsIgnoreCase("comment")) {
        cookie.setComment(value);
    } else if (key.equalsIgnoreCase("samesite")) {
        cookie.setSameSite(true);
        cookie.setSameSiteMode(value);
    }
    //otherwise ignore this key-value pair
}
 
Example #3
Source File: UndertowServerHttpResponse.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected void applyCookies() {
	for (String name : getCookies().keySet()) {
		for (ResponseCookie httpCookie : getCookies().get(name)) {
			Cookie cookie = new CookieImpl(name, httpCookie.getValue());
			if (!httpCookie.getMaxAge().isNegative()) {
				cookie.setMaxAge((int) httpCookie.getMaxAge().getSeconds());
			}
			if (httpCookie.getDomain() != null) {
				cookie.setDomain(httpCookie.getDomain());
			}
			if (httpCookie.getPath() != null) {
				cookie.setPath(httpCookie.getPath());
			}
			cookie.setSecure(httpCookie.isSecure());
			cookie.setHttpOnly(httpCookie.isHttpOnly());
			this.exchange.getResponseCookies().putIfAbsent(name, cookie);
		}
	}
}
 
Example #4
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 #5
Source File: Cookies.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void handleValue(CookieImpl cookie, String key, String value) {
    if (key.equalsIgnoreCase("path")) {
        cookie.setPath(value);
    } else if (key.equalsIgnoreCase("domain")) {
        cookie.setDomain(value);
    } else if (key.equalsIgnoreCase("max-age")) {
        cookie.setMaxAge(Integer.parseInt(value));
    } else if (key.equalsIgnoreCase("expires")) {
        cookie.setExpires(DateUtils.parseDate(value));
    } else if (key.equalsIgnoreCase("discard")) {
        cookie.setDiscard(true);
    } else if (key.equalsIgnoreCase("secure")) {
        cookie.setSecure(true);
    } else if (key.equalsIgnoreCase("httpOnly")) {
        cookie.setHttpOnly(true);
    } else if (key.equalsIgnoreCase("version")) {
        cookie.setVersion(Integer.parseInt(value));
    } else if (key.equalsIgnoreCase("comment")) {
        cookie.setComment(value);
    } else if (key.equalsIgnoreCase("samesite")) {
        cookie.setSameSite(true);
        cookie.setSameSiteMode(value);
    }
    //otherwise ignore this key-value pair
}
 
Example #6
Source File: UndertowServerHttpResponse.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void applyCookies() {
	for (String name : getCookies().keySet()) {
		for (ResponseCookie httpCookie : getCookies().get(name)) {
			Cookie cookie = new CookieImpl(name, httpCookie.getValue());
			if (!httpCookie.getMaxAge().isNegative()) {
				cookie.setMaxAge((int) httpCookie.getMaxAge().getSeconds());
			}
			if (httpCookie.getDomain() != null) {
				cookie.setDomain(httpCookie.getDomain());
			}
			if (httpCookie.getPath() != null) {
				cookie.setPath(httpCookie.getPath());
			}
			cookie.setSecure(httpCookie.isSecure());
			cookie.setHttpOnly(httpCookie.isHttpOnly());
			this.exchange.getResponseCookies().putIfAbsent(name, cookie);
		}
	}
}
 
Example #7
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 #8
Source File: UndertowHttpFacade.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly) {
    CookieImpl cookie = new CookieImpl(name, value);
    cookie.setPath(path);
    cookie.setDomain(domain);
    cookie.setMaxAge(maxAge);
    cookie.setSecure(secure);
    cookie.setHttpOnly(httpOnly);
    exchange.setResponseCookie(cookie);
}
 
Example #9
Source File: UndertowHttpFacade.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void resetCookie(String name, String path) {
    CookieImpl cookie = new CookieImpl(name, "");
    cookie.setMaxAge(0);
    cookie.setPath(path);
    exchange.setResponseCookie(cookie);
}
 
Example #10
Source File: AdminController.java    From mangooio with Apache License 2.0 5 votes vote down vote up
public Response logout() {
    Cookie cookie = new CookieImpl(Default.ADMIN_COOKIE_NAME.toString())
            .setValue("")
            .setHttpOnly(true)
            .setSecure(Application.inProdMode())
            .setPath("/")
            .setDiscard(true)
            .setExpires(new Date())
            .setSameSite(true)
            .setSameSiteMode("Strict");
    
    return Response.withRedirect(ADMIN_INDEX).andCookie(cookie);
}
 
Example #11
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 #12
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 #13
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 #14
Source File: SingleSignOnAuthenticationMechanism.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public StreamSinkConduit wrap(ConduitFactory<StreamSinkConduit> factory, HttpServerExchange exchange) {
    SecurityContext sc = exchange.getSecurityContext();
    Account account = sc.getAuthenticatedAccount();
    if (account != null) {
        try (SingleSignOn sso = singleSignOnManager.createSingleSignOn(account, sc.getMechanismName())) {
            Session session = getSession(exchange);
            registerSessionIfRequired(sso, session);
            exchange.getResponseCookies().put(cookieName, new CookieImpl(cookieName, sso.getId()).setHttpOnly(httpOnly).setSecure(secure).setDomain(domain).setPath(path));
        }
    }
    return factory.create();
}
 
Example #15
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 #16
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 #17
Source File: SingleSignOnAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeCommit(HttpServerExchange exchange) {

    SecurityContext sc = exchange.getSecurityContext();
    Account account = sc.getAuthenticatedAccount();
    if (account != null) {
        try (SingleSignOn sso = singleSignOnManager.createSingleSignOn(account, sc.getMechanismName())) {
            Session session = getSession(exchange);
            registerSessionIfRequired(sso, session);
            exchange.getResponseCookies().put(cookieName, new CookieImpl(cookieName, sso.getId()).setHttpOnly(httpOnly).setSecure(secure).setDomain(domain).setPath(path));
        }
    }
}
 
Example #18
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 #19
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());
}
 
Example #20
Source File: SingleSignOnAuthenticationMechanism.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void clearSsoCookie(HttpServerExchange exchange) {
    exchange.getResponseCookies().put(cookieName, new CookieImpl(cookieName).setMaxAge(0).setHttpOnly(httpOnly).setSecure(secure).setDomain(domain).setPath(path));
}
 
Example #21
Source File: RequestParserTest.java    From core-ng-project with Apache License 2.0 4 votes vote down vote up
@Test
void parseCookies() {
    Map<String, String> cookies = parser.decodeCookies(Map.of("name", new CookieImpl("name", "value")));
    assertThat(cookies).containsEntry("name", "value");
}
 
Example #22
Source File: RequestParserTest.java    From core-ng-project with Apache License 2.0 4 votes vote down vote up
@Test
void decodeInvalidCookieValue() {
    Map<String, String> cookies = parser.decodeCookies(Map.of("name", new CookieImpl("name", "%%")));
    assertThat(cookies).isEmpty();
}
 
Example #23
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 #24
Source File: I18nController.java    From mangooio with Apache License 2.0 4 votes vote down vote up
public Response localize() {
    Cookie cookie = new CookieImpl(Default.I18N_COOKIE_NAME.toString(), "en");
    return Response.withOk().andCookie(cookie);
}
 
Example #25
Source File: SingleSignOnAuthenticationMechanism.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
private void clearSsoCookie(HttpServerExchange exchange) {
    exchange.getResponseCookies().put(cookieName, new CookieImpl(cookieName).setMaxAge(0).setHttpOnly(httpOnly).setSecure(secure).setDomain(domain).setPath(path));
}