undertow refresh token support

This commit is contained in:
Bill Burke 2014-02-22 17:24:04 -05:00
parent baa0e453b6
commit 273e706a42
11 changed files with 271 additions and 143 deletions

View file

@ -1,11 +1,11 @@
package org.keycloak.adapters.undertow; package org.keycloak.adapters.undertow;
import io.undertow.server.HandlerWrapper;
import io.undertow.server.HttpHandler; import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange; import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers; import io.undertow.util.Headers;
import io.undertow.util.StatusCodes; import io.undertow.util.StatusCodes;
import org.jboss.logging.Logger; import org.jboss.logging.Logger;
import org.keycloak.KeycloakAuthenticatedSession;
import org.keycloak.adapters.AdapterConstants; import org.keycloak.adapters.AdapterConstants;
import org.keycloak.representations.AccessToken; import org.keycloak.representations.AccessToken;
import org.keycloak.representations.adapters.config.AdapterConfig; import org.keycloak.representations.adapters.config.AdapterConfig;
@ -30,6 +30,20 @@ public class AuthenticatedActionsHandler implements HttpHandler {
protected AdapterConfig adapterConfig; protected AdapterConfig adapterConfig;
protected HttpHandler next; protected HttpHandler next;
public static class Wrapper implements HandlerWrapper {
protected AdapterConfig config;
public Wrapper(AdapterConfig config) {
this.config = config;
}
@Override
public HttpHandler wrap(HttpHandler handler) {
return new AuthenticatedActionsHandler(config, handler);
}
}
protected AuthenticatedActionsHandler(AdapterConfig config, HttpHandler next) { protected AuthenticatedActionsHandler(AdapterConfig config, HttpHandler next) {
this.adapterConfig = config; this.adapterConfig = config;
this.next = next; this.next = next;
@ -38,34 +52,32 @@ public class AuthenticatedActionsHandler implements HttpHandler {
@Override @Override
public void handleRequest(HttpServerExchange exchange) throws Exception { public void handleRequest(HttpServerExchange exchange) throws Exception {
log.debugv("AuthenticatedActionsValve.invoke {0}", exchange.getRequestURI()); log.debugv("AuthenticatedActionsValve.invoke {0}", exchange.getRequestURI());
KeycloakAuthenticatedSession session = getSkeletonKeySession(exchange); KeycloakUndertowAccount account = getAccount(exchange);
if (corsRequest(exchange, session)) return; if (corsRequest(exchange, account)) return;
String requestUri = exchange.getRequestURI(); String requestUri = exchange.getRequestURI();
if (requestUri.endsWith(AdapterConstants.K_QUERY_BEARER_TOKEN)) { if (requestUri.endsWith(AdapterConstants.K_QUERY_BEARER_TOKEN)) {
queryBearerToken(exchange, session); queryBearerToken(exchange, account);
return; return;
} }
next.handleRequest(exchange); next.handleRequest(exchange);
} }
public KeycloakAuthenticatedSession getSkeletonKeySession(HttpServerExchange exchange) { public KeycloakUndertowAccount getAccount(HttpServerExchange exchange) {
KeycloakAuthenticatedSession skSession = exchange.getAttachment(KeycloakAuthenticationMechanism.SKELETON_KEY_SESSION_ATTACHMENT_KEY); return (KeycloakUndertowAccount)exchange.getSecurityContext().getAuthenticatedAccount();
if (skSession != null) return skSession;
return null;
} }
protected void queryBearerToken(HttpServerExchange exchange, KeycloakAuthenticatedSession session) throws IOException, ServletException { protected void queryBearerToken(HttpServerExchange exchange, KeycloakUndertowAccount account) throws IOException, ServletException {
log.debugv("queryBearerToken {0}",exchange.getRequestURI()); log.debugv("queryBearerToken {0}",exchange.getRequestURI());
if (abortTokenResponse(exchange, session)) return; if (abortTokenResponse(exchange, account)) return;
exchange.setResponseCode(StatusCodes.OK); exchange.setResponseCode(StatusCodes.OK);
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send(session.getTokenString()); exchange.getResponseSender().send(account.getEncodedAccessToken());
exchange.endExchange(); exchange.endExchange();
} }
protected boolean abortTokenResponse(HttpServerExchange exchange, KeycloakAuthenticatedSession session) throws IOException { protected boolean abortTokenResponse(HttpServerExchange exchange, KeycloakUndertowAccount account) throws IOException {
if (session == null) { if (account == null) {
log.debugv("session was null, sending back 401: {0}",exchange.getRequestURI()); log.debugv("Not logged in, sending back 401: {0}",exchange.getRequestURI());
exchange.setResponseCode(StatusCodes.UNAUTHORIZED); exchange.setResponseCode(StatusCodes.UNAUTHORIZED);
exchange.endExchange(); exchange.endExchange();
return true; return true;
@ -75,6 +87,7 @@ public class AuthenticatedActionsHandler implements HttpHandler {
exchange.endExchange(); exchange.endExchange();
return true; return true;
} }
// Don't allow a CORS request if we're not validating CORS requests.
if (!adapterConfig.isCors() && exchange.getRequestHeaders().getFirst(Headers.ORIGIN) != null) { if (!adapterConfig.isCors() && exchange.getRequestHeaders().getFirst(Headers.ORIGIN) != null) {
exchange.setResponseCode(StatusCodes.OK); exchange.setResponseCode(StatusCodes.OK);
exchange.endExchange(); exchange.endExchange();
@ -83,13 +96,13 @@ public class AuthenticatedActionsHandler implements HttpHandler {
return false; return false;
} }
protected boolean corsRequest(HttpServerExchange exchange, KeycloakAuthenticatedSession session) throws IOException { protected boolean corsRequest(HttpServerExchange exchange, KeycloakUndertowAccount account) throws IOException {
if (!adapterConfig.isCors()) return false; if (!adapterConfig.isCors()) return false;
log.debugv("CORS enabled + request.getRequestURI()"); log.debugv("CORS enabled + request.getRequestURI()");
String origin = exchange.getRequestHeaders().getFirst("Origin"); String origin = exchange.getRequestHeaders().getFirst("Origin");
log.debugv("Origin: {0} uri: {1}", origin, exchange.getRequestURI()); log.debugv("Origin: {0} uri: {1}", origin, exchange.getRequestURI());
if (session != null && origin != null) { if (account != null && origin != null) {
AccessToken token = session.getToken(); AccessToken token = account.getAccessToken();
Set<String> allowedOrigins = token.getAllowedOrigins(); Set<String> allowedOrigins = token.getAllowedOrigins();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
for (String a : allowedOrigins) log.debug(" " + a); for (String a : allowedOrigins) log.debug(" " + a);
@ -111,7 +124,7 @@ public class AuthenticatedActionsHandler implements HttpHandler {
exchange.getResponseHeaders().put(PreflightCorsHandler.ACCESS_CONTROL_ALLOW_ORIGIN, origin); exchange.getResponseHeaders().put(PreflightCorsHandler.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
exchange.getResponseHeaders().put(PreflightCorsHandler.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); exchange.getResponseHeaders().put(PreflightCorsHandler.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
} else { } else {
log.debugv("session or origin was null: {0}", exchange.getRequestURI()); log.debugv("not secured or origin was null: {0}", exchange.getRequestURI());
} }
return false; return false;
} }

View file

@ -59,11 +59,7 @@ public class KeycloakAuthenticationMechanism implements AuthenticationMechanism
return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
} }
else if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) { else if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) {
final AccessToken token = bearer.getToken(); completeAuthentication(securityContext, bearer);
String surrogate = bearer.getSurrogate();
KeycloakAuthenticatedSession session = new KeycloakAuthenticatedSession(bearer.getTokenString(), token, resourceMetadata);
KeycloakPrincipal principal = completeAuthentication(securityContext, token, surrogate);
propagateBearer(exchange, session, principal);
return AuthenticationMechanismOutcome.AUTHENTICATED; return AuthenticationMechanismOutcome.AUTHENTICATED;
} }
else if (adapterConfig.isBearerOnly()) { else if (adapterConfig.isBearerOnly()) {
@ -82,9 +78,7 @@ public class KeycloakAuthenticationMechanism implements AuthenticationMechanism
return AuthenticationMechanismOutcome.NOT_ATTEMPTED; return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
} }
KeycloakAuthenticatedSession session = new KeycloakAuthenticatedSession(oauth.getTokenString(), oauth.getToken(), resourceMetadata); completeAuthentication(securityContext, oauth);
KeycloakPrincipal principal = completeAuthentication(securityContext, oauth.getToken(), null);
propagateOauth(exchange, session, principal);
log.info("AUTHENTICATED"); log.info("AUTHENTICATED");
return AuthenticationMechanismOutcome.AUTHENTICATED; return AuthenticationMechanismOutcome.AUTHENTICATED;
} }
@ -97,43 +91,19 @@ public class KeycloakAuthenticationMechanism implements AuthenticationMechanism
return new BearerTokenAuthenticator(resourceMetadata, adapterConfig.isUseResourceRoleMappings()); return new BearerTokenAuthenticator(resourceMetadata, adapterConfig.isUseResourceRoleMappings());
} }
protected KeycloakPrincipal completeAuthentication(SecurityContext securityContext, AccessToken token, String surrogate) { protected void completeAuthentication(SecurityContext securityContext, OAuthAuthenticator oauth) {
final KeycloakPrincipal skeletonKeyPrincipal = new KeycloakPrincipal(token.getSubject(), surrogate); final KeycloakPrincipal principal = new KeycloakPrincipal(oauth.getToken().getSubject(), null);
Set<String> roles = null; KeycloakUndertowAccount account = new KeycloakUndertowAccount(principal, oauth.getToken(), oauth.getTokenString(), oauth.getRefreshToken(), realmConfig, resourceMetadata, adapterConfig);
if (adapterConfig.isUseResourceRoleMappings()) {
AccessToken.Access access = token.getResourceAccess(resourceMetadata.getResourceName());
if (access != null) roles = access.getRoles();
} else {
AccessToken.Access access = token.getRealmAccess();
if (access != null) roles = access.getRoles();
}
if (roles == null) roles = Collections.emptySet();
final Set<String> accountRoles = roles;
Account account = new Account() {
@Override
public Principal getPrincipal() {
return skeletonKeyPrincipal;
}
@Override
public Set<String> getRoles() {
return accountRoles;
}
};
securityContext.authenticationComplete(account, "KEYCLOAK", true); securityContext.authenticationComplete(account, "KEYCLOAK", true);
return skeletonKeyPrincipal;
} }
protected void propagateBearer(HttpServerExchange exchange, KeycloakAuthenticatedSession session, KeycloakPrincipal principal) {
exchange.putAttachment(SKELETON_KEY_SESSION_ATTACHMENT_KEY, session);
protected void completeAuthentication(SecurityContext securityContext, BearerTokenAuthenticator bearer) {
final KeycloakPrincipal principal = new KeycloakPrincipal(bearer.getToken().getSubject(), bearer.getSurrogate());
KeycloakUndertowAccount account = new KeycloakUndertowAccount(principal, bearer.getToken(), bearer.getTokenString(), null, realmConfig, resourceMetadata, adapterConfig);
securityContext.authenticationComplete(account, "KEYCLOAK", false);
} }
protected void propagateOauth(HttpServerExchange exchange, KeycloakAuthenticatedSession session, KeycloakPrincipal principal) {
exchange.putAttachment(SKELETON_KEY_SESSION_ATTACHMENT_KEY, session);
}
@Override @Override
public ChallengeResult sendChallenge(HttpServerExchange exchange, SecurityContext securityContext) { public ChallengeResult sendChallenge(HttpServerExchange exchange, SecurityContext securityContext) {
KeycloakChallenge challenge = exchange.getAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY); KeycloakChallenge challenge = exchange.getAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY);

View file

@ -0,0 +1,48 @@
package org.keycloak.adapters.undertow;
import io.undertow.security.idm.Account;
import io.undertow.security.idm.Credential;
import io.undertow.security.idm.IdentityManager;
import io.undertow.util.StatusCodes;
import org.jboss.logging.Logger;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.RSATokenVerifier;
import org.keycloak.VerificationException;
import org.keycloak.adapters.ResourceMetadata;
import org.keycloak.adapters.TokenGrantRequest;
import org.keycloak.adapters.config.RealmConfiguration;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.adapters.config.AdapterConfig;
import java.io.IOException;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
class KeycloakIdentityManager implements IdentityManager {
protected static Logger log = Logger.getLogger(KeycloakIdentityManager.class);
@Override
public Account verify(Account account) {
log.info("Verifying account in IdentityManager");
KeycloakUndertowAccount keycloakAccount = (KeycloakUndertowAccount)account;
if (keycloakAccount.getAccessToken().isActive()) return account;
keycloakAccount.refreshExpiredToken();
if (!keycloakAccount.getAccessToken().isActive()) return null;
return account;
}
@Override
public Account verify(String id, Credential credential) {
KeycloakServletExtension.log.warn("Shouldn't call verify!!!");
throw new IllegalStateException("Not allowed");
}
@Override
public Account verify(Credential credential) {
KeycloakServletExtension.log.warn("Shouldn't call verify!!!");
throw new IllegalStateException("Not allowed");
}
}

View file

@ -28,7 +28,7 @@ import java.util.Map;
*/ */
public class KeycloakServletExtension implements ServletExtension { public class KeycloakServletExtension implements ServletExtension {
protected Logger log = Logger.getLogger(KeycloakServletExtension.class); protected static Logger log = Logger.getLogger(KeycloakServletExtension.class);
// todo when this DeploymentInfo method of the same name is fixed. // todo when this DeploymentInfo method of the same name is fixed.
public boolean isAuthenticationMechanismPresent(DeploymentInfo deploymentInfo, final String mechanismName) { public boolean isAuthenticationMechanismPresent(DeploymentInfo deploymentInfo, final String mechanismName) {
@ -79,7 +79,7 @@ public class KeycloakServletExtension implements ServletExtension {
realmConfiguration, realmConfiguration,
deploymentInfo.getConfidentialPortManager()); deploymentInfo.getConfidentialPortManager());
} }
ServletAuthenticatedActionsHandler.Wrapper actions = new ServletAuthenticatedActionsHandler.Wrapper(keycloakConfig); AuthenticatedActionsHandler.Wrapper actions = new AuthenticatedActionsHandler.Wrapper(keycloakConfig);
// setup handlers // setup handlers
@ -95,25 +95,7 @@ public class KeycloakServletExtension implements ServletExtension {
deploymentInfo.addInnerHandlerChainWrapper(ServletPropagateSessionHandler.WRAPPER); // propagates SkeletonKeySession deploymentInfo.addInnerHandlerChainWrapper(ServletPropagateSessionHandler.WRAPPER); // propagates SkeletonKeySession
deploymentInfo.addInnerHandlerChainWrapper(actions); // handles authenticated actions and cors. deploymentInfo.addInnerHandlerChainWrapper(actions); // handles authenticated actions and cors.
deploymentInfo.setIdentityManager(new IdentityManager() { deploymentInfo.setIdentityManager(new KeycloakIdentityManager());
@Override
public Account verify(Account account) {
log.info("Verifying account in IdentityManager");
return account;
}
@Override
public Account verify(String id, Credential credential) {
log.warn("Shouldn't call verify!!!");
throw new IllegalStateException("Not allowed");
}
@Override
public Account verify(Credential credential) {
log.warn("Shouldn't call verify!!!");
throw new IllegalStateException("Not allowed");
}
});
log.info("Setting jsession cookie path to: " + deploymentInfo.getContextPath()); log.info("Setting jsession cookie path to: " + deploymentInfo.getContextPath());
ServletSessionConfig cookieConfig = new ServletSessionConfig(); ServletSessionConfig cookieConfig = new ServletSessionConfig();

View file

@ -0,0 +1,114 @@
package org.keycloak.adapters.undertow;
import io.undertow.security.idm.Account;
import org.jboss.logging.Logger;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.RSATokenVerifier;
import org.keycloak.VerificationException;
import org.keycloak.adapters.ResourceMetadata;
import org.keycloak.adapters.TokenGrantRequest;
import org.keycloak.adapters.config.RealmConfiguration;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.adapters.config.AdapterConfig;
import java.io.IOException;
import java.security.Principal;
import java.util.Collections;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class KeycloakUndertowAccount implements Account {
protected static Logger log = Logger.getLogger(KeycloakUndertowAccount.class);
protected AccessToken accessToken;
protected String encodedAccessToken;
protected String refreshToken;
protected KeycloakPrincipal principal;
protected Set<String> accountRoles;
protected RealmConfiguration realmConfiguration;
protected ResourceMetadata resourceMetadata;
protected AdapterConfig adapterConfig;
public KeycloakUndertowAccount(KeycloakPrincipal principal, AccessToken accessToken, String encodedAccessToken, String refreshToken,
RealmConfiguration realmConfiguration, ResourceMetadata resourceMetadata, AdapterConfig adapterConfig) {
this.principal = principal;
this.accessToken = accessToken;
this.encodedAccessToken = encodedAccessToken;
this.refreshToken = refreshToken;
this.realmConfiguration = realmConfiguration;
this.resourceMetadata = resourceMetadata;
this.adapterConfig = adapterConfig;
setRoles(accessToken);
}
protected void setRoles(AccessToken accessToken) {
Set<String> roles = null;
if (adapterConfig.isUseResourceRoleMappings()) {
AccessToken.Access access = accessToken.getResourceAccess(resourceMetadata.getResourceName());
if (access != null) roles = access.getRoles();
} else {
AccessToken.Access access = accessToken.getRealmAccess();
if (access != null) roles = access.getRoles();
}
if (roles == null) roles = Collections.emptySet();
this.accountRoles = roles;
}
@Override
public Principal getPrincipal() {
return principal;
}
@Override
public Set<String> getRoles() {
return accountRoles;
}
public AccessToken getAccessToken() {
return accessToken;
}
public String getEncodedAccessToken() {
return encodedAccessToken;
}
public String getRefreshToken() {
return refreshToken;
}
public ResourceMetadata getResourceMetadata() {
return resourceMetadata;
}
public void refreshExpiredToken() {
if (accessToken.isActive()) return;
log.debug("Doing refresh");
AccessTokenResponse response = null;
try {
response = TokenGrantRequest.invokeRefresh(realmConfiguration, getRefreshToken());
} catch (IOException e) {
log.error("Refresh token failure", e);
return;
} catch (TokenGrantRequest.HttpFailure httpFailure) {
log.error("Refresh token failure status: " + httpFailure.getStatus() + " " + httpFailure.getError());
return;
}
String tokenString = response.getToken();
AccessToken token = null;
try {
token = RSATokenVerifier.verifyToken(tokenString, realmConfiguration.getMetadata().getRealmKey(), realmConfiguration.getMetadata().getRealm());
log.debug("Token Verification succeeded!");
} catch (VerificationException e) {
log.error("failed verification of token");
}
this.accessToken = token;
this.refreshToken = response.getRefreshToken();
this.encodedAccessToken = tokenString;
setRoles(this.accessToken);
}
}

View file

@ -34,6 +34,7 @@ public class OAuthAuthenticator {
protected AccessToken token; protected AccessToken token;
protected HttpServerExchange exchange; protected HttpServerExchange exchange;
protected KeycloakChallenge challenge; protected KeycloakChallenge challenge;
protected String refreshToken;
public OAuthAuthenticator(HttpServerExchange exchange, RealmConfiguration realmInfo, int sslRedirectPort) { public OAuthAuthenticator(HttpServerExchange exchange, RealmConfiguration realmInfo, int sslRedirectPort) {
this.exchange = exchange; this.exchange = exchange;
@ -53,6 +54,10 @@ public class OAuthAuthenticator {
return token; return token;
} }
public String getRefreshToken() {
return refreshToken;
}
protected String getRequestUrl() { protected String getRequestUrl() {
KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(exchange.getRequestURI()) KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(exchange.getRequestURI())
.replaceQuery(exchange.getQueryString()); .replaceQuery(exchange.getQueryString());
@ -249,6 +254,7 @@ public class OAuthAuthenticator {
} }
tokenString = tokenResponse.getToken(); tokenString = tokenResponse.getToken();
refreshToken = tokenResponse.getRefreshToken();
try { try {
token = RSATokenVerifier.verifyToken(tokenString, realmInfo.getMetadata().getRealmKey(), realmInfo.getMetadata().getRealm()); token = RSATokenVerifier.verifyToken(tokenString, realmInfo.getMetadata().getRealmKey(), realmInfo.getMetadata().getRealm());
log.debug("Token Verification succeeded!"); log.debug("Token Verification succeeded!");

View file

@ -1,48 +0,0 @@
package org.keycloak.adapters.undertow;
import io.undertow.server.HandlerWrapper;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.servlet.handlers.ServletRequestContext;
import org.keycloak.KeycloakAuthenticatedSession;
import org.keycloak.representations.adapters.config.AdapterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ServletAuthenticatedActionsHandler extends AuthenticatedActionsHandler {
protected ServletAuthenticatedActionsHandler(AdapterConfig config, HttpHandler next) {
super(config, next);
}
public static class Wrapper implements HandlerWrapper {
protected AdapterConfig config;
public Wrapper(AdapterConfig config) {
this.config = config;
}
@Override
public HttpHandler wrap(HttpHandler handler) {
return new ServletAuthenticatedActionsHandler(config, handler);
}
}
@Override
public KeycloakAuthenticatedSession getSkeletonKeySession(HttpServerExchange exchange) {
KeycloakAuthenticatedSession skSession = super.getSkeletonKeySession(exchange);
if (skSession != null) return skSession;
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
HttpSession session = req.getSession(false);
if (session == null) return null;
return (KeycloakAuthenticatedSession)session.getAttribute(KeycloakAuthenticatedSession.class.getName());
}
}

View file

@ -29,7 +29,6 @@ public class ServletKeycloakAuthenticationMechanism extends KeycloakAuthenticati
public ServletKeycloakAuthenticationMechanism(AdapterConfig config, ResourceMetadata metadata, ConfidentialPortManager portManager) { public ServletKeycloakAuthenticationMechanism(AdapterConfig config, ResourceMetadata metadata, ConfidentialPortManager portManager) {
super(config, metadata); super(config, metadata);
this.portManager = portManager; this.portManager = portManager;
this.userSessionManagement = userSessionManagement;
} }
@ -38,6 +37,7 @@ public class ServletKeycloakAuthenticationMechanism extends KeycloakAuthenticati
return new ServletOAuthAuthenticator(exchange, realmConfig, portManager); return new ServletOAuthAuthenticator(exchange, realmConfig, portManager);
} }
/*
@Override @Override
protected void propagateBearer(HttpServerExchange exchange, KeycloakAuthenticatedSession skSession, KeycloakPrincipal principal) { protected void propagateBearer(HttpServerExchange exchange, KeycloakAuthenticatedSession skSession, KeycloakPrincipal principal) {
super.propagateBearer(exchange, skSession, principal); super.propagateBearer(exchange, skSession, principal);
@ -56,4 +56,5 @@ public class ServletKeycloakAuthenticationMechanism extends KeycloakAuthenticati
session.setAttribute(KeycloakAuthenticatedSession.class.getName(), skSession); session.setAttribute(KeycloakAuthenticatedSession.class.getName(), skSession);
userSessionManagement.login(servletRequestContext.getDeployment().getSessionManager(), session, principal.getName()); userSessionManagement.login(servletRequestContext.getDeployment().getSessionManager(), session, principal.getName());
} }
*/
} }

View file

@ -33,31 +33,27 @@ public class ServletPropagateSessionHandler implements HttpHandler {
@Override @Override
public void handleRequest(HttpServerExchange exchange) throws Exception { public void handleRequest(HttpServerExchange exchange) throws Exception {
log.info("handleRequest"); log.debug("handleRequest");
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); KeycloakUndertowAccount account = (KeycloakUndertowAccount)exchange.getSecurityContext().getAuthenticatedAccount();
HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest(); if (account == null) {
KeycloakAuthenticatedSession skSession = (KeycloakAuthenticatedSession)req.getAttribute(KeycloakAuthenticatedSession.class.getName()); log.debug("Not logged in, nothing to propagate");
if (skSession != null) {
log.info("skSession is in request");
next.handleRequest(exchange); next.handleRequest(exchange);
return; return;
} }
UndertowKeycloakSession skSession = new UndertowKeycloakSession(account);
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
req.setAttribute(KeycloakAuthenticatedSession.class.getName(), skSession);
HttpSession session = req.getSession(false); HttpSession session = req.getSession(false);
if (session == null) { if (session == null) {
log.info("http session was null, nothing to propagate");
next.handleRequest(exchange); next.handleRequest(exchange);
return; return;
} }
skSession = (KeycloakAuthenticatedSession)session.getAttribute(KeycloakAuthenticatedSession.class.getName()); log.debug("propagating to HTTP Session");
if (skSession == null) { session.setAttribute(KeycloakAuthenticatedSession.class.getName(), skSession);
log.info("skSession not in http session, nothing to propagate");
next.handleRequest(exchange);
return;
}
log.info("propagating");
req.setAttribute(KeycloakAuthenticatedSession.class.getName(), skSession);
exchange.putAttachment(KeycloakAuthenticationMechanism.SKELETON_KEY_SESSION_ATTACHMENT_KEY, skSession);
next.handleRequest(exchange); next.handleRequest(exchange);
} }
} }

View file

@ -0,0 +1,43 @@
package org.keycloak.adapters.undertow;
import org.keycloak.KeycloakAuthenticatedSession;
import org.keycloak.adapters.ResourceMetadata;
import org.keycloak.representations.AccessToken;
import java.io.Serializable;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class UndertowKeycloakSession extends KeycloakAuthenticatedSession {
private transient KeycloakUndertowAccount account;
public UndertowKeycloakSession(KeycloakUndertowAccount account) {
super(account.getEncodedAccessToken(), account.getAccessToken(), account.getResourceMetadata());
this.account = account;
}
@Override
public AccessToken getToken() {
checkExpiration();
return super.getToken();
}
private void checkExpiration() {
if (token.isExpired() && account != null) {
account.refreshExpiredToken();
this.token = account.getAccessToken();
this.tokenString = account.getEncodedAccessToken();
}
}
@Override
public String getTokenString() {
checkExpiration();
return super.getTokenString();
}
}

View file

@ -161,6 +161,9 @@ public class RealmManager {
if (rep.getAccessTokenLifespan() != null) newRealm.setAccessTokenLifespan(rep.getAccessTokenLifespan()); if (rep.getAccessTokenLifespan() != null) newRealm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
else newRealm.setAccessTokenLifespan(300); else newRealm.setAccessTokenLifespan(300);
if (rep.getRefreshTokenLifespan() != null) newRealm.setRefreshTokenLifespan(rep.getRefreshTokenLifespan());
else newRealm.setRefreshTokenLifespan(3600);
if (rep.getAccessCodeLifespan() != null) newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan()); if (rep.getAccessCodeLifespan() != null) newRealm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
else newRealm.setAccessCodeLifespan(60); else newRealm.setAccessCodeLifespan(60);