protected void setAuthenticationCookie ( HttpServerExchange exchange ) { Authentication authentication = this . attachment . getAuthentication ( ) ; if ( authentication . isInvalid ( ) || authentication . isLogout ( ) ) { Cookie cookie = new CookieImpl ( this . config . getAuthenticationCookieName ( ) ) . setSecure ( this . config . isAuthenticationCookieSecure ( ) ) . setHttpOnly ( true ) . setPath ( "/" ) . setMaxAge ( 0 ) . setSameSite ( true ) . setSameSiteMode ( SAME_SITE_MODE ) . setDiscard ( true ) ; exchange . setResponseCookie ( cookie ) ; } else if ( authentication . isValid ( ) ) { if ( authentication . isRememberMe ( ) ) { authentication . withExpires ( LocalDateTime . now ( ) . plusHours ( this . config . getAuthenticationCookieRememberExpires ( ) ) ) ; } JwtClaims jwtClaims = new JwtClaims ( ) ; jwtClaims . setSubject ( authentication . getSubject ( ) ) ; jwtClaims . setClaim ( ClaimKey . TWO_FACTOR . toString ( ) , authentication . isTwoFactor ( ) ) ; if ( authentication . getExpires ( ) == null ) { jwtClaims . setClaim ( ClaimKey . EXPIRES . toString ( ) , "-1" ) ; } else { jwtClaims . setClaim ( ClaimKey . EXPIRES . toString ( ) , authentication . getExpires ( ) . format ( DateUtils . formatter ) ) ; } JsonWebSignature jsonWebSignature = new JsonWebSignature ( ) ; jsonWebSignature . setKey ( new HmacKey ( this . config . getAuthenticationCookieSignKey ( ) . getBytes ( StandardCharsets . UTF_8 ) ) ) ; jsonWebSignature . setPayload ( jwtClaims . toJson ( ) ) ; jsonWebSignature . setAlgorithmHeaderValue ( AlgorithmIdentifiers . HMAC_SHA512 ) ; try { String encryptedValue = Application . getInstance ( Crypto . class ) . encrypt ( jsonWebSignature . getCompactSerialization ( ) , this . config . getAuthenticationCookieEncryptionKey ( ) ) ; final Cookie cookie = new CookieImpl ( this . config . getAuthenticationCookieName ( ) ) . setValue ( encryptedValue ) . setSecure ( this . config . isAuthenticationCookieSecure ( ) ) . setHttpOnly ( true ) . setSameSite ( true ) . setPath ( "/" ) . setSameSiteMode ( SAME_SITE_MODE ) ; if ( authentication . getExpires ( ) != null ) { cookie . setExpires ( DateUtils . localDateTimeToDate ( authentication . getExpires ( ) ) ) ; } exchange . setResponseCookie ( cookie ) ; } catch ( JoseException e ) { LOG . error ( "Failed to generate authentication cookie" , e ) ; } } else { //Ignore and send no cookie to the client } }
Sets the authentication cookie to the current HttpServerExchange