This commit is contained in:
Bill Burke 2014-02-22 20:40:06 -05:00
parent 273e706a42
commit 3e88cb3b76
18 changed files with 76 additions and 53 deletions

View file

@ -552,7 +552,7 @@ module.controller('RealmTokenDetailCtrl', function($scope, Realm, realm, $http,
$scope.realm.refreshTokenLifespanUnit = TimeUnit.autoUnit(realm.refreshTokenLifespan);
$scope.realm.refreshTokenLifespan = TimeUnit.toUnit(realm.refreshTokenLifespan, $scope.realm.refreshTokenLifespanUnit);
$scope.$watch('realm.refreshTokenLifespanUnit', function(to, from) {
$scope.realm.refreshTokenLifespan = TimeUnit.convert($scope.realm.tokenLifespan, from, to);
$scope.realm.refreshTokenLifespan = TimeUnit.convert($scope.realm.refreshTokenLifespan, from, to);
});
$scope.realm.accessCodeLifespanUnit = TimeUnit.autoUnit(realm.accessCodeLifespan);

View file

@ -20,8 +20,8 @@
id="accessTokenLifespan" name="accessTokenLifespan"/>
</div>
<div class="col-sm-2 select-kc">
<select name="tokenLifespanUnit" data-ng-model="realm.tokenLifespanUnit" >
<option data-ng-selected="!realm.tokenLifespanUnit">Seconds</option>
<select name="accessTokenLifespanUnit" data-ng-model="realm.accessTokenLifespanUnit" >
<option data-ng-selected="!realm.accessTokenLifespanUnit">Seconds</option>
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
@ -67,7 +67,7 @@
</div>
</div>
<div class="form-group input-select">
<label class="col-sm-2 control-label" for="refreshTokenLifespan">Refresh token lifespan</label>
<label class="col-sm-2 control-label" for="refreshTokenLifespan">Refresh token lifespan {{realm.refreshTokenLifespan}}</label>
<div class="col-sm-10">
<div class="row">
<div class="col-sm-2">
@ -76,7 +76,7 @@
id="refreshTokenLifespan" name="refreshTokenLifespan"/>
</div>
<div class="col-sm-2 select-kc">
<select name="tokenLifespanUnit" data-ng-model="realm.refreshTokenLifespanUnit" >
<select name="refreshTokenLifespanUnit" data-ng-model="realm.refreshTokenLifespanUnit" >
<option data-ng-selected="!realm.refreshTokenLifespanUnit">Seconds</option>
<option>Minutes</option>
<option>Hours</option>

View file

@ -12,8 +12,12 @@ import java.security.PublicKey;
* @version $Revision: 1 $
*/
public class RSATokenVerifier {
public static AccessToken verifyToken(String tokenString, PublicKey realmKey, String realm) throws VerificationException {
return verifyToken(tokenString, realmKey, realm, true);
}
public static AccessToken verifyToken(String tokenString, PublicKey realmKey, String realm, boolean checkActive) throws VerificationException {
JWSInput input = new JWSInput(tokenString);
boolean verified = false;
try {
@ -29,9 +33,6 @@ public class RSATokenVerifier {
} catch (IOException e) {
throw new VerificationException(e);
}
if (!token.isActive()) {
throw new VerificationException("Token is not active.");
}
String user = token.getSubject();
if (user == null) {
throw new VerificationException("Token user was null");
@ -40,6 +41,10 @@ public class RSATokenVerifier {
throw new VerificationException("Token audience doesn't match domain");
}
if (checkActive && !token.isActive()) {
throw new VerificationException("Token is not active.");
}
return token;
}
}

View file

@ -58,6 +58,7 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
super.start();
StandardContext standardContext = (StandardContext) context;
standardContext.addLifecycleListener(this);
cache = false;
}
@Override

View file

@ -78,7 +78,7 @@ public class KeycloakAuthenticationMechanism implements AuthenticationMechanism
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
completeAuthentication(securityContext, oauth);
completeAuthentication(exchange, securityContext, oauth);
log.info("AUTHENTICATED");
return AuthenticationMechanismOutcome.AUTHENTICATED;
}
@ -91,10 +91,15 @@ public class KeycloakAuthenticationMechanism implements AuthenticationMechanism
return new BearerTokenAuthenticator(resourceMetadata, adapterConfig.isUseResourceRoleMappings());
}
protected void completeAuthentication(SecurityContext securityContext, OAuthAuthenticator oauth) {
protected void completeAuthentication(HttpServerExchange exchange, SecurityContext securityContext, OAuthAuthenticator oauth) {
final KeycloakPrincipal principal = new KeycloakPrincipal(oauth.getToken().getSubject(), null);
KeycloakUndertowAccount account = new KeycloakUndertowAccount(principal, oauth.getToken(), oauth.getTokenString(), oauth.getRefreshToken(), realmConfig, resourceMetadata, adapterConfig);
securityContext.authenticationComplete(account, "KEYCLOAK", true);
login(exchange, account);
}
protected void login(HttpServerExchange exchange, KeycloakUndertowAccount account) {
// complete
}

View file

@ -28,7 +28,10 @@ class KeycloakIdentityManager implements IdentityManager {
public Account verify(Account account) {
log.info("Verifying account in IdentityManager");
KeycloakUndertowAccount keycloakAccount = (KeycloakUndertowAccount)account;
if (keycloakAccount.getAccessToken().isActive()) return account;
if (keycloakAccount.getAccessToken().isActive()) {
log.info("account is still active. Time left: " + (keycloakAccount.getAccessToken().getExpiration() - (System.currentTimeMillis()/1000)) );
return account;
}
keycloakAccount.refreshExpiredToken();
if (!keycloakAccount.getAccessToken().isActive()) return null;
return account;

View file

@ -86,7 +86,7 @@ public class KeycloakUndertowAccount implements Account {
public void refreshExpiredToken() {
if (accessToken.isActive()) return;
log.debug("Doing refresh");
log.info("Doing refresh");
AccessTokenResponse response = null;
try {
response = TokenGrantRequest.invokeRefresh(realmConfiguration, getRefreshToken());
@ -97,11 +97,12 @@ public class KeycloakUndertowAccount implements Account {
log.error("Refresh token failure status: " + httpFailure.getStatus() + " " + httpFailure.getError());
return;
}
log.info("received refresh response");
String tokenString = response.getToken();
AccessToken token = null;
try {
token = RSATokenVerifier.verifyToken(tokenString, realmConfiguration.getMetadata().getRealmKey(), realmConfiguration.getMetadata().getRealm());
log.debug("Token Verification succeeded!");
log.info("Token Verification succeeded!");
} catch (VerificationException e) {
log.error("failed verification of token");
}

View file

@ -84,6 +84,7 @@ public class ServletAdminActionsHandler implements HttpHandler {
SessionManager manager = servletRequestContext.getDeployment().getSessionManager();
String requestUri = exchange.getRequestURI();
if (requestUri.endsWith(AdapterConstants.K_LOGOUT)) {
log.info("K_LOGOUT sent");
JWSInput token = verifyAdminRequest(request, response);
if (token == null) return;
userSessionManagement.remoteLogout(token, manager, response);

View file

@ -37,24 +37,13 @@ public class ServletKeycloakAuthenticationMechanism extends KeycloakAuthenticati
return new ServletOAuthAuthenticator(exchange, realmConfig, portManager);
}
/*
@Override
protected void propagateBearer(HttpServerExchange exchange, KeycloakAuthenticatedSession skSession, KeycloakPrincipal principal) {
super.propagateBearer(exchange, skSession, principal);
protected void login(HttpServerExchange exchange, KeycloakUndertowAccount account) {
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
req.setAttribute(KeycloakAuthenticatedSession.class.getName(), skSession);
HttpSession session = req.getSession(true);
userSessionManagement.login(servletRequestContext.getDeployment().getSessionManager(), session, account.getPrincipal().getName());
}
@Override
protected void propagateOauth(HttpServerExchange exchange, KeycloakAuthenticatedSession skSession, KeycloakPrincipal principal) {
super.propagateBearer(exchange, skSession, principal);
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
req.setAttribute(KeycloakAuthenticatedSession.class.getName(), skSession);
HttpSession session = req.getSession(true);
session.setAttribute(KeycloakAuthenticatedSession.class.getName(), skSession);
userSessionManagement.login(servletRequestContext.getDeployment().getSessionManager(), session, principal.getName());
}
*/
}

View file

@ -41,7 +41,7 @@ public class UserSessionManagement implements SessionListener {
public void remoteLogout(JWSInput token, SessionManager manager, HttpServletResponse response) throws IOException {
try {
log.debug("->> remoteLogout: ");
log.info("->> remoteLogout: ");
LogoutAction action = JsonSerialization.readValue(token.getContent(), LogoutAction.class);
if (action.isExpired()) {
log.warn("admin request failed, expired token");
@ -56,10 +56,10 @@ public class UserSessionManagement implements SessionListener {
}
String user = action.getUser();
if (user != null) {
log.debug("logout of session for: " + user);
log.info("logout of session for: " + user);
logout(manager, user);
} else {
log.debug("logout of all sessions");
log.info("logout of all sessions");
logoutAll(manager);
}
} catch (Exception e) {
@ -118,13 +118,13 @@ public class UserSessionManagement implements SessionListener {
}
public void logout(SessionManager manager, String user) {
log.debug("logoutUser: " + user);
log.info("logoutUser: " + user);
Set<String> map = userSessionMap.remove(user);
if (map == null) {
log.debug("no session for user: " + user);
log.info("no session for user: " + user);
return;
}
log.debug("found session for user");
log.info("found session for user");
synchronized (map) {
for (String id : map) {
log.debug("invalidating session for user: " + user);

View file

@ -46,7 +46,8 @@ public class ApplianceBootstrap {
realm.addRequiredCredential(CredentialRepresentation.PASSWORD);
realm.addRequiredOAuthClientCredential(CredentialRepresentation.PASSWORD);
realm.addRequiredResourceCredential(CredentialRepresentation.PASSWORD);
realm.setAccessTokenLifespan(300);
realm.setAccessTokenLifespan(60);
realm.setRefreshTokenLifespan(3600);
realm.setAccessCodeLifespan(60);
realm.setAccessCodeLifespanUserAction(300);
realm.setSslNotRequired(true);

View file

@ -36,7 +36,7 @@ import java.util.Set;
* @version $Revision: 1 $
*/
public class AuthenticationManager {
protected Logger logger = Logger.getLogger(AuthenticationManager.class);
protected static Logger logger = Logger.getLogger(AuthenticationManager.class);
public static final String FORM_USERNAME = "username";
public static final String KEYCLOAK_IDENTITY_COOKIE = "KEYCLOAK_IDENTITY";
@ -127,20 +127,26 @@ public class AuthenticationManager {
}
public UserModel authenticateIdentityCookie(RealmModel realm, UriInfo uriInfo, HttpHeaders headers) {
return authenticateIdentityCookie(realm, uriInfo, headers, true);
}
public UserModel authenticateIdentityCookie(RealmModel realm, UriInfo uriInfo, HttpHeaders headers, boolean checkActive) {
logger.info("authenticateIdentityCookie");
String cookieName = KEYCLOAK_IDENTITY_COOKIE;
Auth auth = authenticateIdentityCookie(realm, uriInfo, headers, cookieName);
Auth auth = authenticateIdentityCookie(realm, uriInfo, headers, cookieName, checkActive);
return auth != null ? auth.getUser() : null;
}
public UserModel authenticateSaasIdentityCookie(RealmModel realm, UriInfo uriInfo, HttpHeaders headers) {
String cookieName = AdminService.SAAS_IDENTITY_COOKIE;
Auth auth = authenticateIdentityCookie(realm, uriInfo, headers, cookieName);
Auth auth = authenticateIdentityCookie(realm, uriInfo, headers, cookieName, true);
return auth != null ? auth.getUser() : null;
}
public Auth authenticateAccountIdentityCookie(RealmModel realm, UriInfo uriInfo, HttpHeaders headers) {
String cookieName = AccountService.ACCOUNT_IDENTITY_COOKIE;
return authenticateIdentityCookie(realm, uriInfo, headers, cookieName);
return authenticateIdentityCookie(realm, uriInfo, headers, cookieName, true);
}
public UserModel authenticateSaasIdentity(RealmModel realm, UriInfo uriInfo, HttpHeaders headers) {
@ -159,18 +165,20 @@ public class AuthenticationManager {
}
protected Auth authenticateIdentityCookie(RealmModel realm, UriInfo uriInfo, HttpHeaders headers, String cookieName) {
protected Auth authenticateIdentityCookie(RealmModel realm, UriInfo uriInfo, HttpHeaders headers, String cookieName, boolean checkActive) {
logger.info("authenticateIdentityCookie");
Cookie cookie = headers.getCookies().get(cookieName);
if (cookie == null) {
logger.debug("authenticateCookie could not find cookie: {0}", cookieName);
logger.info("authenticateCookie could not find cookie: {0}", cookieName);
return null;
}
String tokenString = cookie.getValue();
try {
AccessToken token = RSATokenVerifier.verifyToken(tokenString, realm.getPublicKey(), realm.getName());
if (!token.isActive()) {
logger.debug("identity cookie expired");
AccessToken token = RSATokenVerifier.verifyToken(tokenString, realm.getPublicKey(), realm.getName(), checkActive);
logger.info("identity token verified");
if (checkActive && !token.isActive()) {
logger.info("identity cookie expired");
expireIdentityCookie(realm, uriInfo);
return null;
}
@ -179,7 +187,7 @@ public class AuthenticationManager {
UserModel user = realm.getUserById(token.getSubject());
if (user == null || !user.isEnabled()) {
logger.debug("Unknown user in identity cookie");
logger.info("Unknown user in identity cookie");
expireIdentityCookie(realm, uriInfo);
return null;
}
@ -188,7 +196,7 @@ public class AuthenticationManager {
if (token.getIssuedFor() != null) {
UserModel client = realm.getUser(token.getIssuedFor());
if (client == null || !client.isEnabled()) {
logger.debug("Unknown client in identity cookie");
logger.info("Unknown client in identity cookie");
expireIdentityCookie(realm, uriInfo);
return null;
}
@ -197,7 +205,7 @@ public class AuthenticationManager {
return auth;
} catch (VerificationException e) {
logger.debug("Failed to verify identity cookie", e);
logger.info("Failed to verify identity cookie", e);
expireCookie(cookie.getName(), cookie.getPath());
}
return null;

View file

@ -72,6 +72,7 @@ public class ModelToRepresentation {
rep.setVerifyEmail(realm.isVerifyEmail());
rep.setResetPasswordAllowed(realm.isResetPasswordAllowed());
rep.setAccessTokenLifespan(realm.getAccessTokenLifespan());
rep.setRefreshTokenLifespan(realm.getRefreshTokenLifespan());
rep.setAccessCodeLifespan(realm.getAccessCodeLifespan());
rep.setAccessCodeLifespanUserAction(realm.getAccessCodeLifespanUserAction());
rep.setSmtpServer(realm.getSmtpConfig());

View file

@ -106,6 +106,7 @@ public class RealmManager {
if (rep.getAccessCodeLifespanUserAction() != null)
realm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction());
if (rep.getAccessTokenLifespan() != null) realm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
if (rep.getRefreshTokenLifespan() != null) realm.setRefreshTokenLifespan(rep.getRefreshTokenLifespan());
if (rep.getRequiredCredentials() != null) {
realm.updateRequiredCredentials(rep.getRequiredCredentials());
}

View file

@ -18,7 +18,7 @@ import java.util.List;
* @version $Revision: 1 $
*/
public class ResourceAdminManager {
protected Logger logger = Logger.getLogger(ResourceAdminManager.class);
protected static Logger logger = Logger.getLogger(ResourceAdminManager.class);
public void logoutAll(RealmModel realm) {
singleLogOut(realm, null);
@ -41,12 +41,14 @@ public class ResourceAdminManager {
if (managementUrl != null) {
LogoutAction adminAction = new LogoutAction(TokenIdGenerator.generateId(), System.currentTimeMillis() / 1000 + 30, resource.getName(), user);
String token = new TokenManager().encodeToken(realm, adminAction);
logger.debug("logout user: {0} resource: {1} url: {2}", user, resource.getName(), managementUrl);
logger.info("logout user: {0} resource: {1} url: {2}", user, resource.getName(), managementUrl);
Response response = client.target(managementUrl).path(AdapterConstants.K_LOGOUT).request().post(Entity.text(token));
boolean success = response.getStatus() == 204;
response.close();
logger.info("logout success.");
return success;
} else {
logger.info("logout failure.");
return false;
}
}

View file

@ -250,6 +250,7 @@ public class TokenManager {
token.issuer(realm.getName());
if (realm.getAccessTokenLifespan() > 0) {
token.expiration((System.currentTimeMillis() / 1000) + realm.getAccessTokenLifespan());
logger.info("Access Token expiration: " + token.getExpiration());
}
Set<String> allowedOrigins = client.getWebOrigins();
if (allowedOrigins != null) {

View file

@ -539,11 +539,14 @@ public class TokenService {
public Response logout(final @QueryParam("redirect_uri") String redirectUri) {
// todo do we care if anybody can trigger this?
UserModel user = authManager.authenticateIdentityCookie(realm, uriInfo, headers);
// authenticate identity cookie, but ignore an access token timeout as we're logging out anyways.
UserModel user = authManager.authenticateIdentityCookie(realm, uriInfo, headers, false);
if (user != null) {
logger.debug("Logging out: {0}", user.getLoginName());
logger.info("Logging out: {0}", user.getLoginName());
authManager.expireIdentityCookie(realm, uriInfo);
resourceAdminManager.singleLogOut(realm, user.getLoginName());
resourceAdminManager.singleLogOut(realm, user.getId());
} else {
logger.info("No user logged in for logout");
}
// todo manage legal redirects
return Response.status(302).location(UriBuilder.fromUri(redirectUri).build()).build();

View file

@ -58,6 +58,7 @@ public class CompositeRoleTest {
manager.generateRealmKeys(realm);
realmPublicKey = realm.getPublicKey();
realm.setAccessTokenLifespan(10000);
realm.setRefreshTokenLifespan(10000);
realm.setAccessCodeLifespanUserAction(1000);
realm.setAccessCodeLifespan(1000);
realm.setSslNotRequired(true);