Skip to content

Commit

Permalink
Change short-term session naming to session-token naming
Browse files Browse the repository at this point in the history
  • Loading branch information
alexbalakirev committed Oct 27, 2024
1 parent 01707b0 commit 06a0157
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 46 deletions.
20 changes: 10 additions & 10 deletions src/main/java/com/corbado/sdk/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,17 @@ public class Config {
/** The backend api with custom setter. */
@Getter private String backendApi;

/** The short session cookie name. Default value: "cbo_session_token" */
@Getter @Setter @Builder.Default private String shortSessionCookieName = "cbo_session_token";
/** The session token cookie name. Default value: "cbo_session_token." */
@Getter @Setter @Builder.Default private String sessionTokenCookieName = "cbo_session_token";

/** The issuer. Used for session verification. */
@Getter @Setter private String issuer;

/** The frontend api with custom setter. */
@Getter private String frontendApi;

/** The short session length for session service. Default = 300. */
@Getter @Setter @Builder.Default private Integer shortSessionLength = 300;
/** The life duration for session service token. Default = 300. */
@Getter @Setter @Builder.Default private Integer sessionTokenLength = 300;

/** Flag to cache keys in session service. Default = true. */
@Getter @Setter @Builder.Default private boolean cacheKeys = true;
Expand Down Expand Up @@ -134,31 +134,31 @@ public void setProjectId(@NonNull String projectId) {
* @param projectId the project id
* @param apiSecret the api secret
* @param backendApi the backend api
* @param shortSessionCookieName the short session cookie name
* @param sessionTokenCookieName the short session cookie name
* @param issuer the issuer
* @param frontendApi the frontend api
* @param shortSessionLength the short session length
* @param sessionTokenLength the short session length
* @param cacheKeys the cache keys
* @param cname the cname
*/
public Config(
@NonNull final String projectId,
@NonNull final String apiSecret,
@NonNull final String backendApi,
final String shortSessionCookieName,
final String sessionTokenCookieName,
final String issuer,
@NonNull final String frontendApi,
final Integer shortSessionLength,
final Integer sessionTokenLength,
final boolean cacheKeys,
String cname) {

setProjectId(projectId);
setApiSecret(apiSecret);
setBackendApi(backendApi);
setShortSessionCookieName(shortSessionCookieName);
setSessionTokenCookieName(sessionTokenCookieName);
setFrontendApi(frontendApi);

setShortSessionLength(shortSessionLength);
setSessionTokenLength(sessionTokenLength);
setCacheKeys(cacheKeys);
setCname(cname);

Expand Down
61 changes: 29 additions & 32 deletions src/main/java/com/corbado/services/SessionService.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
package com.corbado.services;

import java.net.MalformedURLException;
import java.net.URL;
import java.security.interfaces.RSAPublicKey;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;

import com.auth0.jwk.Jwk;
import com.auth0.jwk.JwkException;
import com.auth0.jwk.JwkProvider;
Expand All @@ -21,7 +14,11 @@
import com.corbado.entities.SessionValidationResult;
import com.corbado.sdk.Config;
import com.corbado.utils.ValidationUtils;

import java.net.MalformedURLException;
import java.net.URL;
import java.security.interfaces.RSAPublicKey;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
Expand All @@ -40,8 +37,8 @@ public class SessionService {
/** The Constant DEFAULT_SESSION_LENGTH. */
private static final int DEFAULT_SESSION_LENGTH = 300;

/** The short session cookie name. */
private String shortSessionCookieName;
/** The session token cookie name. */
private String sessionTokenCookieName;

/** The issuer. */
private String issuer;
Expand All @@ -50,39 +47,39 @@ public class SessionService {
private String jwksUri;

/** The last short session validation result. */
private String lastShortSessionValidationResult;
private String lastSessionTokenValidationResult;

/** The jwk provider. */
private JwkProvider jwkProvider;

/**
* Instantiates a new session service.
*
* @param shortSessionCookieName the short session cookie name
* @param sessionTokenCookieName the short session cookie name
* @param issuer the issuer
* @param jwksUri the jwks uri
* @param shortSessionLength the short session length
* @param sessionTokenLength the short session length
* @param cacheKeys the cache keys
*/
public SessionService(
final String shortSessionCookieName,
final String sessionTokenCookieName,
final String issuer,
final String jwksUri,
Integer shortSessionLength,
Integer sessionTokenLength,
final boolean cacheKeys) {

ValidationUtils.validateNotEmpty(shortSessionCookieName, issuer, jwksUri);
shortSessionLength = (shortSessionLength != null) ? shortSessionLength : DEFAULT_SESSION_LENGTH;
ValidationUtils.validateNotEmpty(sessionTokenCookieName, issuer, jwksUri);
sessionTokenLength = (sessionTokenLength != null) ? sessionTokenLength : DEFAULT_SESSION_LENGTH;

this.shortSessionCookieName = shortSessionCookieName;
this.sessionTokenCookieName = sessionTokenCookieName;
this.issuer = issuer;
this.jwksUri = jwksUri;

JwkProviderBuilder jwkProviderBuilder;
try {
jwkProviderBuilder = new JwkProviderBuilder(new URL(jwksUri));
if (cacheKeys) {
jwkProviderBuilder.cached(JWK_CACHE_SIZE, shortSessionLength, TimeUnit.SECONDS);
jwkProviderBuilder.cached(JWK_CACHE_SIZE, sessionTokenLength, TimeUnit.SECONDS);
}
this.jwkProvider = jwkProviderBuilder.build();
} catch (final MalformedURLException e) {
Expand All @@ -98,10 +95,10 @@ public SessionService(
*/
public SessionService(@NonNull final Config config) {
this(
config.getShortSessionCookieName(),
config.getSessionTokenCookieName(),
config.getIssuer(),
config.getFrontendApi() + "/.well-known/jwks",
config.getShortSessionLength(),
config.getSessionTokenLength(),
config.isCacheKeys());
}

Expand All @@ -111,38 +108,38 @@ public SessionService(@NonNull final Config config) {
* @param issuer the new issuer mismatch error
*/
public void setIssuerMismatchError(final String issuer) {
this.lastShortSessionValidationResult =
this.lastSessionTokenValidationResult =
String.format("Mismatch in issuer (configured: %s, JWT: %s)", this.issuer, issuer);
}

/**
* Gets the and validate user from short session value.
*
* @param shortSession the short session
* @param sessionToken the short session
* @return the and validate user from short session value
* @throws JWTVerificationException the JWT verification exception
* @throws JwkException the jwk exception
* @throws IncorrectClaimException the incorrect claim exception
*/
private SessionValidationResult getAndValidateUserFromShortSessionValue(final String shortSession)
private SessionValidationResult getAndValidateUserFromShortSessionValue(final String sessionToken)
throws JWTVerificationException, JwkException, IncorrectClaimException {

if (shortSession == null || shortSession.isEmpty()) {
if (sessionToken == null || sessionToken.isEmpty()) {
throw new IllegalArgumentException("Session value cannot be null or empty");
}
try {
// Get the signing key
DecodedJWT decodedJwt = JWT.decode(shortSession);
DecodedJWT decodedJwt = JWT.decode(sessionToken);
final Jwk jwk = this.jwkProvider.get(decodedJwt.getKeyId());
if (jwk == null) {
throw new SigningKeyNotFoundException(shortSession, null);
throw new SigningKeyNotFoundException(sessionToken, null);
}
final RSAPublicKey publicKey = (RSAPublicKey) jwk.getPublicKey();

// Verify and decode the JWT using the signing key
final Algorithm algorithm = Algorithm.RSA256(publicKey);
final JWTVerifier verifier = JWT.require(algorithm).withIssuer(this.issuer).build();
decodedJwt = verifier.verify(shortSession);
decodedJwt = verifier.verify(sessionToken);

return SessionValidationResult.builder()
.fullName(decodedJwt.getClaim("name").asString())
Expand All @@ -168,17 +165,17 @@ private SessionValidationResult getAndValidateUserFromShortSessionValue(final St
}

/**
* Retrieves userID and full name if 'shortSession' is valid.
* Retrieves userID and full name if 'sessionToken' is valid.
*
* @param shortSession the short session
* @param sessionToken the short session
* @return the and validate current user
* @throws IncorrectClaimException the incorrect claim exception
* @throws JWTVerificationException the JWT verification exception
* @throws JwkException the jwk exception
*/
public SessionValidationResult getAndValidateCurrentUser(final String shortSession)
public SessionValidationResult getAndValidateCurrentUser(final String sessionToken)
throws IncorrectClaimException, JWTVerificationException, JwkException {

return getAndValidateUserFromShortSessionValue(shortSession);
return getAndValidateUserFromShortSessionValue(sessionToken);
}
}
8 changes: 4 additions & 4 deletions src/test/java/com/corbado/unit/SessionServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -148,25 +148,25 @@ void test_testGenerateJwt() throws InvalidKeySpecException, NoSuchAlgorithmExcep
*
* @param issuer the issuer
* @param jwksUri the jwks uri
* @param shortSessionCookieName the short session cookie name
* @param sessionTokenCookieName the short session cookie name
* @param expectValid the expect valid
*/
@ParameterizedTest
@MethodSource("initParametersTestData")
void testInitParametersValidation(
final String issuer,
final String jwksUri,
final String shortSessionCookieName,
final String sessionTokenCookieName,
final boolean expectValid) {
if (expectValid) {
// No exception should be raised
assertDoesNotThrow(
() -> new SessionService(shortSessionCookieName, issuer, jwksUri, 0, false));
() -> new SessionService(sessionTokenCookieName, issuer, jwksUri, 0, false));
} else {
// ValidationError should be raised
assertThrows(
IllegalArgumentException.class,
() -> new SessionService(shortSessionCookieName, issuer, jwksUri, 0, false));
() -> new SessionService(sessionTokenCookieName, issuer, jwksUri, 0, false));
}
}

Expand Down

0 comments on commit 06a0157

Please sign in to comment.