revocation phase 1

This commit is contained in:
Bill Burke 2014-02-28 19:47:05 -05:00
parent 0d309d058c
commit 7b30cc59b8
45 changed files with 568 additions and 194 deletions

View file

@ -35,6 +35,7 @@ module.config([ '$routeProvider', function($routeProvider) {
controller : 'RealmDetailCtrl'
})
*/
.when('/create/realm', {
templateUrl : 'partials/realm-create.html',
resolve : {
@ -518,6 +519,16 @@ module.config([ '$routeProvider', function($routeProvider) {
},
controller : 'RealmDetailCtrl'
})
.when('/realms/:realm/sessions/revocation', {
templateUrl : 'partials/session-revocation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmRevocationCtrl'
})
.otherwise({
templateUrl : 'partials/notfound.html'
});

View file

@ -690,6 +690,51 @@ module.controller('RealmKeysDetailCtrl', function($scope, Realm, realm, $http, $
};
});
module.controller('RealmRevocationCtrl', function($scope, Realm, RealmPushRevocation, realm, $http, $location, Dialog, Notifications) {
$scope.realm = realm;
var setNotBefore = function() {
if ($scope.realm.notBefore == 0) {
$scope.notBefore = "None";
} else {
$scope.notBefore = new Date($scope.realm.notBefore * 1000);
}
};
if (realm.notBefore == 0) {
$scope.notBefore = "None";
} else {
$scope.notBefore = new Date(realm.notBefore);
}
$scope.clear = function() {
Realm.update({ realm: realm.realm, notBefore : 0 }, function () {
$scope.notBefore = "None";
Notifications.success('Not Before cleared for realm.');
Realm.get({ id : realm.realm }, function(updated) {
$scope.realm = updated;
setNotBefore();
})
});
}
$scope.setNotBeforeNow = function() {
Realm.update({ realm: realm.realm, notBefore : new Date().getTime()/1000}, function () {
Notifications.success('Not Before cleared for realm.');
Realm.get({ id : realm.realm }, function(updated) {
$scope.realm = updated;
setNotBefore();
})
});
}
$scope.pushRevocation = function() {
RealmPushRevocation.save({ realm: realm.realm}, function () {
Notifications.success('Push sent for realm.');
});
}
});
module.controller('RoleListCtrl', function($scope, $location, realm, roles) {
$scope.realm = realm;

View file

@ -235,6 +235,12 @@ module.factory('RoleRealmComposites', function($resource) {
});
});
module.factory('RealmPushRevocation', function($resource) {
return $resource('/auth/rest/admin/realms/:realm/push-revocation', {
realm : '@realm'
});
});
module.factory('RoleApplicationComposites', function($resource) {
return $resource('/auth/rest/admin/realms/:realm/roles-by-id/:role/composites/applications/:application', {
realm : '@realm',

View file

@ -6,4 +6,5 @@
</li>
<li data-ng-show="access.viewApplications" data-ng-class="(path[2] == 'applications' || path[1] == 'application' || path[3] == 'applications') && 'active'"><a href="#/realms/{{realm.realm}}/applications">Applications</a></li>
<li data-ng-show="access.viewClients" data-ng-class="(path[2] == 'oauth-clients' || path[1] == 'oauth-client') && 'active'"><a href="#/realms/{{realm.realm}}/oauth-clients">OAuth Clients</a></li>
<li data-ng-show="access.viewRealm" data-ng-class="(path[2] == 'sessions') && 'active'"><a href="#/realms/{{realm.realm}}/sessions/revocation">Sessions</a></li>
</ul>

View file

@ -1,122 +1,122 @@
<div class="bs-sidebar col-sm-3 " data-ng-include data-src="'partials/realm-menu.html'"></div>
<div id="content-area" class="col-sm-9" role="main">
<data-kc-navigation data-kc-current="token" data-kc-realm="realm.realm" data-kc-social="realm.social"></data-kc-navigation>
<div id="content">
<ol class="breadcrumb">
<li><a href="#/realms/{{realm.realm}}">{{realm.realm}}</a></li>
<li><a href="#/realms/{{realm.realm}}">Settings</a></li>
<li class="active">Token</li>
</ol>
<h2><span>{{realm.realm}}</span> Token Settings</h2>
<form class="form-horizontal" name="realmForm" novalidate kc-read-only="!access.manageRealm">
<fieldset class="border-top">
<div class="form-group">
<label class="col-sm-2 control-label" for="rememberMe">Remember Me</label>
<div class="col-sm-4">
<input ng-model="realm.rememberMe" name="rememberMe" id="rememberMe" onoffswitch />
</div>
</div>
<div class="form-group input-select">
<label class="col-sm-2 control-label" for="centralLoginLifespan">Central Login lifespan</label>
<div class="col-sm-10">
<div class="row">
<div class="col-sm-2">
<input class="form-control" type="number" required min="1"
max="31536000" data-ng-model="realm.centralLoginLifespan"
id="centralLoginLifespan" name="centralLoginLifespan"/>
</div>
<div class="col-sm-2 select-kc">
<select name="centralLoginLifespanUnit" data-ng-model="realm.centralLoginLifespanUnit" >
<option data-ng-selected="!realm.centralLoginLifespanUnit">Seconds</option>
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group input-select">
<label class="col-sm-2 control-label" for="accessTokenLifespan">Access token lifespan</label>
<div class="col-sm-10">
<div class="row">
<div class="col-sm-2">
<input class="form-control" type="number" required min="1"
max="31536000" data-ng-model="realm.accessTokenLifespan"
id="accessTokenLifespan" name="accessTokenLifespan"/>
</div>
<div class="col-sm-2 select-kc">
<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>
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="accessCodeLifespan">Access code lifespan</label>
<div class="col-sm-10">
<div class="row">
<div class="col-sm-2">
<input class="form-control" type="number" required min="1" max="31536000" data-ng-model="realm.accessCodeLifespan" id="accessCodeLifespan" name="accessCodeLifespan">
</div>
<div class="col-sm-2 select-kc">
<select name="accessCodeLifespanUnit" data-ng-model="realm.accessCodeLifespanUnit">
<option data-ng-selected="!realm.accessCodeLifespanUnit">Seconds</option>
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group input-select">
<label class="col-sm-2 control-label" for="accessCodeLifespanUserAction" class="two-lines">Access code user action lifespan</label>
<div class="col-sm-10">
<div class="row">
<div class="col-sm-2">
<input class="form-control" type="number" required min="1" max="31536000" data-ng-model="realm.accessCodeLifespanUserAction" id="accessCodeLifespanUserAction" name="accessCodeLifespanUserAction">
</div>
<div class="col-sm-2 select-kc">
<select name="accessCodeLifespanUserActionUnit" data-ng-model="realm.accessCodeLifespanUserActionUnit">
<option data-ng-selected="!realm.accessCodeLifespanUserActionUnit">Seconds</option>
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group input-select">
<label class="col-sm-2 control-label" for="refreshTokenLifespan">Refresh token lifespan</label>
<div class="col-sm-10">
<div class="row">
<div class="col-sm-2">
<input class="form-control" type="number" required min="1"
max="31536000" data-ng-model="realm.refreshTokenLifespan"
id="refreshTokenLifespan" name="refreshTokenLifespan"/>
</div>
<div class="col-sm-2 select-kc">
<select name="refreshTokenLifespanUnit" data-ng-model="realm.refreshTokenLifespanUnit" >
<option data-ng-selected="!realm.refreshTokenLifespanUnit">Seconds</option>
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
</select>
</div>
</div>
</div>
</div>
</fieldset>
<div class="pull-right form-actions" data-ng-show="access.manageRealm">
<button kc-reset data-ng-show="changed">Clear changes</button>
<button kc-save data-ng-show="changed">Save</button>
</div>
</form>
</div>
<div class="bs-sidebar col-sm-3 " data-ng-include data-src="'partials/realm-menu.html'"></div>
<div id="content-area" class="col-sm-9" role="main">
<data-kc-navigation data-kc-current="token" data-kc-realm="realm.realm" data-kc-social="realm.social"></data-kc-navigation>
<div id="content">
<ol class="breadcrumb">
<li><a href="#/realms/{{realm.realm}}">{{realm.realm}}</a></li>
<li><a href="#/realms/{{realm.realm}}">Settings</a></li>
<li class="active">Token</li>
</ol>
<h2><span>{{realm.realm}}</span> Token Settings</h2>
<form class="form-horizontal" name="realmForm" novalidate kc-read-only="!access.manageRealm">
<fieldset class="border-top">
<div class="form-group">
<label class="col-sm-2 control-label" for="rememberMe">Remember Me</label>
<div class="col-sm-4">
<input ng-model="realm.rememberMe" name="rememberMe" id="rememberMe" onoffswitch />
</div>
</div>
<div class="form-group input-select">
<label class="col-sm-2 control-label" for="centralLoginLifespan">Central Login lifespan</label>
<div class="col-sm-10">
<div class="row">
<div class="col-sm-2">
<input class="form-control" type="number" required min="1"
max="31536000" data-ng-model="realm.centralLoginLifespan"
id="centralLoginLifespan" name="centralLoginLifespan"/>
</div>
<div class="col-sm-2 select-kc">
<select name="centralLoginLifespanUnit" data-ng-model="realm.centralLoginLifespanUnit" >
<option data-ng-selected="!realm.centralLoginLifespanUnit">Seconds</option>
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group input-select">
<label class="col-sm-2 control-label" for="accessTokenLifespan">Access token lifespan</label>
<div class="col-sm-10">
<div class="row">
<div class="col-sm-2">
<input class="form-control" type="number" required min="1"
max="31536000" data-ng-model="realm.accessTokenLifespan"
id="accessTokenLifespan" name="accessTokenLifespan"/>
</div>
<div class="col-sm-2 select-kc">
<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>
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="accessCodeLifespan">Access code lifespan</label>
<div class="col-sm-10">
<div class="row">
<div class="col-sm-2">
<input class="form-control" type="number" required min="1" max="31536000" data-ng-model="realm.accessCodeLifespan" id="accessCodeLifespan" name="accessCodeLifespan">
</div>
<div class="col-sm-2 select-kc">
<select name="accessCodeLifespanUnit" data-ng-model="realm.accessCodeLifespanUnit">
<option data-ng-selected="!realm.accessCodeLifespanUnit">Seconds</option>
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group input-select">
<label class="col-sm-2 control-label" for="accessCodeLifespanUserAction" class="two-lines">Access code user action lifespan</label>
<div class="col-sm-10">
<div class="row">
<div class="col-sm-2">
<input class="form-control" type="number" required min="1" max="31536000" data-ng-model="realm.accessCodeLifespanUserAction" id="accessCodeLifespanUserAction" name="accessCodeLifespanUserAction">
</div>
<div class="col-sm-2 select-kc">
<select name="accessCodeLifespanUserActionUnit" data-ng-model="realm.accessCodeLifespanUserActionUnit">
<option data-ng-selected="!realm.accessCodeLifespanUserActionUnit">Seconds</option>
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group input-select">
<label class="col-sm-2 control-label" for="refreshTokenLifespan">Refresh token lifespan</label>
<div class="col-sm-10">
<div class="row">
<div class="col-sm-2">
<input class="form-control" type="number" required min="1"
max="31536000" data-ng-model="realm.refreshTokenLifespan"
id="refreshTokenLifespan" name="refreshTokenLifespan"/>
</div>
<div class="col-sm-2 select-kc">
<select name="refreshTokenLifespanUnit" data-ng-model="realm.refreshTokenLifespanUnit" >
<option data-ng-selected="!realm.refreshTokenLifespanUnit">Seconds</option>
<option>Minutes</option>
<option>Hours</option>
<option>Days</option>
</select>
</div>
</div>
</div>
</div>
</fieldset>
<div class="pull-right form-actions" data-ng-show="access.manageRealm">
<button kc-reset data-ng-show="changed">Clear changes</button>
<button kc-save data-ng-show="changed">Save</button>
</div>
</form>
</div>
</div>

View file

@ -0,0 +1,31 @@
<div class="bs-sidebar col-md-3 clearfix" data-ng-include data-src="'partials/realm-menu.html'"></div>
<div id="content-area" class="col-md-9" role="main">
<ul class="nav nav-tabs nav-tabs-pf" data-ng-show="!create">
<li class="active"><a href="#/realms/{{realm.realm}}/sessions/revocation">Revocation</a></li>
</ul>
<div id="content">
<ol class="breadcrumb">
<li><a href="#/realms/{{realm.realm}}">{{realm.realm}}</a></li>
<li class="active">Revocation</li>
</ol>
<h2 data-ng-hide="create"><span>{{realm.realm}}</span> Revocation Policies</h2>
<form class="form-horizontal" name="credentialForm" novalidate kc-read-only="!access.manageRealm">
<fieldset class="border-top">
<div class="form-group">
<label class="col-sm-2 control-label" for="notBefore">Not Before</label>
<div class="col-sm-4">
<input ng-disabled="true" class="form-control" type="text" id="notBefore" name="notBefore" data-ng-model="notBefore" autofocus>
</div>
</div>
</fieldset>
<div class="pull-right form-actions" data-ng-show="access.manageApplications">
<button type="submit" data-ng-click="clear()" class="btn btn-default btn-lg">Clear
</button>
<button type="submit" data-ng-click="setNotBeforeNow()" class="btn btn-primary btn-lg">Set To Now
</button>
<button type="submit" data-ng-click="pushRevocation()" class="btn btn-primary btn-lg">Push
</button>
</div>
</form>
</div>
</div>

View file

@ -8,6 +8,7 @@ public interface AdapterConstants {
// URL endpoints
public static final String K_LOGOUT = "k_logout";
public static final String K_PUSH_NOT_BEFORE = "k_push_not_before";
public static final String K_QUERY_BEARER_TOKEN = "k_query_bearer_token";
// This param name is defined again in Keycloak Subsystem class

View file

@ -139,7 +139,7 @@ public class AccessToken extends IDToken {
@Override
public AccessToken issuedAt(long issuedAt) {
public AccessToken issuedAt(int issuedAt) {
return (AccessToken) super.issuedAt(issuedAt);
}

View file

@ -24,6 +24,9 @@ public class AccessTokenResponse {
@JsonProperty("id_token")
protected String idToken;
@JsonProperty("not-before-policy")
protected int notBeforePolicy;
public String getToken() {
return token;
}
@ -63,4 +66,12 @@ public class AccessTokenResponse {
public void setIdToken(String idToken) {
this.idToken = idToken;
}
public int getNotBeforePolicy() {
return notBeforePolicy;
}
public void setNotBeforePolicy(int notBeforePolicy) {
this.notBeforePolicy = notBeforePolicy;
}
}

View file

@ -17,7 +17,7 @@ public class JsonWebToken implements Serializable {
@JsonProperty("nbf")
protected long notBefore;
@JsonProperty("iat")
protected long issuedAt;
protected int issuedAt;
@JsonProperty("iss")
protected String issuer;
@JsonProperty("aud")
@ -80,7 +80,7 @@ public class JsonWebToken implements Serializable {
return (!isExpired() || expiration == 0) && (isNotBefore() || notBefore == 0);
}
public long getIssuedAt() {
public int getIssuedAt() {
return issuedAt;
}
@ -89,11 +89,11 @@ public class JsonWebToken implements Serializable {
*/
@JsonIgnore
public JsonWebToken issuedNow() {
issuedAt = System.currentTimeMillis() / 1000;
issuedAt = (int)(System.currentTimeMillis() / 1000);
return this;
}
public JsonWebToken issuedAt(long issuedAt) {
public JsonWebToken issuedAt(int issuedAt) {
this.issuedAt = issuedAt;
return this;
}

View file

@ -10,13 +10,13 @@ import org.codehaus.jackson.annotate.JsonIgnore;
*/
public class AdminAction {
protected String id;
protected long expiration;
protected int expiration;
protected String resource;
public AdminAction() {
}
public AdminAction(String id, long expiration, String resource) {
public AdminAction(String id, int expiration, String resource) {
this.id = id;
this.expiration = expiration;
this.resource = resource;
@ -36,11 +36,16 @@ public class AdminAction {
return time > expiration;
}
public long getExpiration() {
/**
* Time in seconds since epoc
*
* @return
*/
public int getExpiration() {
return expiration;
}
public void setExpiration(long expiration) {
public void setExpiration(int expiration) {
this.expiration = expiration;
}

View file

@ -10,7 +10,7 @@ public class LogoutAction extends AdminAction {
public LogoutAction() {
}
public LogoutAction(String id, long expiration, String resource, String user) {
public LogoutAction(String id, int expiration, String resource, String user) {
super(id, expiration, resource);
this.user = user;
}

View file

@ -0,0 +1,26 @@
package org.keycloak.representations.adapters.action;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class PushNotBeforeAction extends AdminAction {
protected int notBefore;
public PushNotBeforeAction() {
}
public PushNotBeforeAction(String id, int expiration, String resource, int notBefore) {
super(id, expiration, resource);
this.notBefore = notBefore;
}
public int getNotBefore() {
return notBefore;
}
public void setNotBefore(int notBefore) {
this.notBefore = notBefore;
}
}

View file

@ -28,6 +28,9 @@ public class PublishedRealmRepresentation {
@JsonProperty("admin-api")
protected String adminApiUrl;
@JsonProperty("tokens-not-before")
protected int notBefore;
@JsonIgnore
protected volatile transient PublicKey publicKey;
@ -100,4 +103,12 @@ public class PublishedRealmRepresentation {
public void setAdminApiUrl(String adminApiUrl) {
this.adminApiUrl = adminApiUrl;
}
public int getNotBefore() {
return notBefore;
}
public void setNotBefore(int notBefore) {
this.notBefore = notBefore;
}
}

View file

@ -13,6 +13,7 @@ public class RealmRepresentation {
protected String self; // link
protected String id;
protected String realm;
protected Integer notBefore;
protected Integer accessTokenLifespan;
protected Integer refreshTokenLifespan;
protected Integer centralLoginLifespan;
@ -344,4 +345,12 @@ public class RealmRepresentation {
public void setAccountTheme(String accountTheme) {
this.accountTheme = accountTheme;
}
public Integer getNotBefore() {
return notBefore;
}
public void setNotBefore(Integer notBefore) {
this.notBefore = notBefore;
}
}

View file

@ -5,7 +5,6 @@ import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.jboss.logging.Logger;
import org.keycloak.adapters.TokenGrantRequest;
import org.keycloak.servlet.ServletOAuthClient;
import org.keycloak.util.JsonSerialization;

View file

@ -14,7 +14,7 @@ import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.keycloak.adapters.TokenGrantRequest;
import org.keycloak.adapters.ServerRequest;
import org.keycloak.servlet.ServletOAuthClient;
/**
@ -45,7 +45,7 @@ public class RefreshTokenFilter implements Filter {
try {
String accessToken = oauthClient.getBearerToken(request).getToken();
userData.setAccessToken(accessToken);
} catch (TokenGrantRequest.HttpFailure e) {
} catch (ServerRequest.HttpFailure e) {
throw new ServletException(e);
}
} else if (reqParams.containsKey("error")) {

View file

@ -4,7 +4,7 @@ import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.keycloak.adapters.TokenGrantRequest;
import org.keycloak.adapters.ServerRequest;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.servlet.ServletOAuthClient;
import org.keycloak.util.JsonSerialization;
@ -63,7 +63,7 @@ public class ProductDatabaseClient {
return oAuthClient.getBearerToken(request);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (TokenGrantRequest.HttpFailure failure) {
} catch (ServerRequest.HttpFailure failure) {
throw new RuntimeException(failure);
}

View file

@ -44,7 +44,7 @@ public class RefreshableKeycloakSession extends KeycloakAuthenticatedSession {
}
public boolean isActive() {
return this.token.isActive();
return this.token.isActive() && this.token.getIssuedAt() > realmConfiguration.getNotBefore();
}
public void setRealmConfiguration(RealmConfiguration realmConfiguration) {
@ -52,17 +52,17 @@ public class RefreshableKeycloakSession extends KeycloakAuthenticatedSession {
}
public void refreshExpiredToken() {
if (this.token.isActive()) return;
if (isActive()) return;
if (this.realmConfiguration == null || refreshToken == null) return; // Might be serialized in HttpSession?
log.info("Doing refresh");
AccessTokenResponse response = null;
try {
response = TokenGrantRequest.invokeRefresh(realmConfiguration, refreshToken);
response = ServerRequest.invokeRefresh(realmConfiguration, refreshToken);
} catch (IOException e) {
log.error("Refresh token failure", e);
return;
} catch (TokenGrantRequest.HttpFailure httpFailure) {
} catch (ServerRequest.HttpFailure httpFailure) {
log.error("Refresh token failure status: " + httpFailure.getStatus() + " " + httpFailure.getError());
return;
}

View file

@ -26,7 +26,7 @@ import java.util.Map;
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class TokenGrantRequest {
public class ServerRequest {
public static class HttpFailure extends Exception {
private int status;

View file

@ -20,6 +20,7 @@ public class RealmConfiguration {
protected Map<String, String> resourceCredentials = new HashMap<String, String>();
protected boolean sslRequired = true;
protected String stateCookieName = "OAuth_Token_Request_State";
protected volatile int notBefore;
public RealmConfiguration() {
}
@ -89,4 +90,11 @@ public class RealmConfiguration {
this.resourceCredentials = resourceCredentials;
}
public int getNotBefore() {
return notBefore;
}
public void setNotBefore(int notBefore) {
this.notBefore = notBefore;
}
}

View file

@ -28,9 +28,12 @@ public class RealmConfigurationLoader extends AdapterConfigLoader {
}
protected void initRealmConfiguration(boolean setupClient) {
realmConfiguration = new RealmConfiguration();
realmConfiguration.setMetadata(resourceMetadata);
realmConfiguration.setSslRequired(!adapterConfig.isSslNotRequired());
realmConfiguration.setResourceCredentials(adapterConfig.getCredentials());
if (!setupClient || adapterConfig.isBearerOnly()) return;
initClient();
realmConfiguration = new RealmConfiguration();
if (adapterConfig.getAuthServerUrl() == null) {
throw new RuntimeException("You must specify auth-url");
}
@ -39,9 +42,6 @@ public class RealmConfigurationLoader extends AdapterConfigLoader {
String tokenUrl = serverBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_ACCESS_CODE_PATH).build(adapterConfig.getRealm()).toString();
String refreshUrl = serverBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_REFRESH_PATH).build(adapterConfig.getRealm()).toString();
realmConfiguration.setMetadata(resourceMetadata);
realmConfiguration.setSslRequired(!adapterConfig.isSslNotRequired());
realmConfiguration.setResourceCredentials(adapterConfig.getCredentials());
HttpClient client = getClient();

View file

@ -29,11 +29,13 @@ public class CatalinaBearerTokenAuthenticator {
protected AccessToken token;
private Principal principal;
protected boolean useResourceRoleMappings;
protected int notBefore;
public CatalinaBearerTokenAuthenticator(ResourceMetadata resourceMetadata, boolean challenge, boolean useResourceRoleMappings) {
public CatalinaBearerTokenAuthenticator(ResourceMetadata resourceMetadata, int notBefore, boolean challenge, boolean useResourceRoleMappings) {
this.resourceMetadata = resourceMetadata;
this.challenge = challenge;
this.useResourceRoleMappings = useResourceRoleMappings;
this.notBefore = notBefore;
}
public ResourceMetadata getResourceMetadata() {
@ -76,6 +78,12 @@ public class CatalinaBearerTokenAuthenticator {
log.error("Failed to verify token", e);
challengeResponse(response, "invalid_token", e.getMessage());
}
if (token.getIssuedAt() < notBefore) {
log.error("Stale token");
challengeResponse(response, "invalid_token", "Stale token");
}
boolean verifyCaller = false;
Set<String> roles = new HashSet<String>();
if (useResourceRoleMappings) {
@ -105,7 +113,7 @@ public class CatalinaBearerTokenAuthenticator {
KeycloakPrincipal skeletonKeyPrincipal = new KeycloakPrincipal(token.getSubject(), surrogate);
principal = new CatalinaSecurityContextHelper().createPrincipal(request.getContext().getRealm(), skeletonKeyPrincipal, roles);
request.setUserPrincipal(principal);
request.setAuthType("OAUTH_BEARER");
request.setAuthType("KEYCLOAK");
KeycloakAuthenticatedSession skSession = new KeycloakAuthenticatedSession(tokenString, token, null, null, resourceMetadata);
request.setAttribute(KeycloakAuthenticatedSession.class.getName(), skSession);

View file

@ -20,6 +20,7 @@ import org.keycloak.adapters.RefreshableKeycloakSession;
import org.keycloak.adapters.ResourceMetadata;
import org.keycloak.adapters.as7.config.CatalinaAdapterConfigLoader;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.adapters.action.PushNotBeforeAction;
import org.keycloak.representations.adapters.config.AdapterConfig;
import org.keycloak.adapters.config.RealmConfiguration;
import org.keycloak.adapters.config.RealmConfigurationLoader;
@ -92,6 +93,12 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
}
remoteLogout(input, response);
return;
} else if (requestURI.endsWith(AdapterConstants.K_PUSH_NOT_BEFORE)) {
JWSInput input = verifyAdminRequest(request, response);
if (input == null) {
return; // we failed to verify the request
}
pushNotBefore(input, response);
}
checkKeycloakSession(request);
super.invoke(request, response);
@ -147,6 +154,30 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
return input;
}
protected void pushNotBefore(JWSInput token, HttpServletResponse response) throws IOException {
try {
log.debug("->> pushNotBefore: ");
PushNotBeforeAction action = JsonSerialization.readValue(token.getContent(), PushNotBeforeAction.class);
if (action.isExpired()) {
log.warn("admin request failed, expired token");
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Expired token");
return;
}
if (!resourceMetadata.getResourceName().equals(action.getResource())) {
log.warn("Resource name does not match");
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Resource name does not match");
return;
}
realmConfiguration.setNotBefore(action.getNotBefore());
} catch (Exception e) {
log.warn("failed to logout", e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to logout");
}
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
protected void remoteLogout(JWSInput token, HttpServletResponse response) throws IOException {
try {
log.debug("->> remoteLogout: ");
@ -179,7 +210,7 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
protected boolean bearer(boolean challenge, Request request, HttpServletResponse response) throws LoginException, IOException {
boolean useResourceRoleMappings = adapterConfig.isUseResourceRoleMappings();
CatalinaBearerTokenAuthenticator bearer = new CatalinaBearerTokenAuthenticator(resourceMetadata, challenge, useResourceRoleMappings);
CatalinaBearerTokenAuthenticator bearer = new CatalinaBearerTokenAuthenticator(resourceMetadata, realmConfiguration.getNotBefore(), challenge, useResourceRoleMappings);
if (bearer.login(request, response)) {
return true;
}

View file

@ -3,7 +3,7 @@ package org.keycloak.adapters.as7;
import org.jboss.logging.Logger;
import org.keycloak.RSATokenVerifier;
import org.keycloak.VerificationException;
import org.keycloak.adapters.TokenGrantRequest;
import org.keycloak.adapters.ServerRequest;
import org.keycloak.adapters.config.RealmConfiguration;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.representations.AccessToken;
@ -242,8 +242,8 @@ public class ServletOAuthLogin {
String redirectUri = stripOauthParametersFromRedirect();
AccessTokenResponse tokenResponse = null;
try {
tokenResponse = TokenGrantRequest.invokeAccessCodeToToken(realmInfo, code, redirectUri);
} catch (TokenGrantRequest.HttpFailure failure) {
tokenResponse = ServerRequest.invokeAccessCodeToToken(realmInfo, code, redirectUri);
} catch (ServerRequest.HttpFailure failure) {
log.error("failed to turn code into token");
log.error("status from server: " + failure.getStatus());
if (failure.getStatus() == HttpServletResponse.SC_BAD_REQUEST && failure.getError() != null) {
@ -275,6 +275,15 @@ public class ServletOAuthLogin {
sendError(HttpServletResponse.SC_FORBIDDEN);
return false;
}
if (tokenResponse.getNotBeforePolicy() > realmInfo.getNotBefore()) {
realmInfo.setNotBefore(tokenResponse.getNotBeforePolicy());
}
if (token.getIssuedAt() < realmInfo.getNotBefore()) {
log.error("Stale token");
sendError(HttpServletResponse.SC_FORBIDDEN);
return false;
}
refreshToken = tokenResponse.getRefreshToken();
// redirect to URL without oauth query parameters
sendRedirect(redirectUri);

View file

@ -3,7 +3,7 @@ package org.keycloak.servlet;
import org.apache.http.client.HttpClient;
import org.keycloak.AbstractOAuthClient;
import org.keycloak.adapters.HttpClientBuilder;
import org.keycloak.adapters.TokenGrantRequest;
import org.keycloak.adapters.ServerRequest;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.representations.AccessTokenResponse;
import org.keycloak.representations.IDToken;
@ -48,8 +48,8 @@ public class ServletOAuthClient extends AbstractOAuthClient {
this.client = client;
}
public AccessTokenResponse resolveBearerToken(String redirectUri, String code) throws IOException, TokenGrantRequest.HttpFailure {
return TokenGrantRequest.invokeAccessCodeToToken(client, code, codeUrl, redirectUri, clientId, credentials);
public AccessTokenResponse resolveBearerToken(String redirectUri, String code) throws IOException, ServerRequest.HttpFailure {
return ServerRequest.invokeAccessCodeToToken(client, code, codeUrl, redirectUri, clientId, credentials);
}
/**
@ -134,9 +134,9 @@ public class ServletOAuthClient extends AbstractOAuthClient {
* @param request
* @return
* @throws IOException
* @throws org.keycloak.adapters.TokenGrantRequest.HttpFailure
* @throws org.keycloak.adapters.ServerRequest.HttpFailure
*/
public AccessTokenResponse getBearerToken(HttpServletRequest request) throws IOException, TokenGrantRequest.HttpFailure {
public AccessTokenResponse getBearerToken(HttpServletRequest request) throws IOException, ServerRequest.HttpFailure {
String error = request.getParameter("error");
if (error != null) throw new IOException("OAuth error: " + error);
String redirectUri = request.getRequestURL().append("?").append(request.getQueryString()).toString();
@ -154,8 +154,8 @@ public class ServletOAuthClient extends AbstractOAuthClient {
return resolveBearerToken(redirectUri, code);
}
public AccessTokenResponse refreshToken(String refreshToken) throws IOException, TokenGrantRequest.HttpFailure {
return TokenGrantRequest.invokeRefresh(client, refreshToken, refreshUrl, clientId, credentials);
public AccessTokenResponse refreshToken(String refreshToken) throws IOException, ServerRequest.HttpFailure {
return ServerRequest.invokeRefresh(client, refreshToken, refreshUrl, clientId, credentials);
}
public static IDToken extractIdToken(String idToken) {

View file

@ -30,10 +30,12 @@ public class BearerTokenAuthenticator {
protected boolean useResourceRoleMappings;
protected String surrogate;
protected KeycloakChallenge challenge;
protected int notBefore;
public BearerTokenAuthenticator(ResourceMetadata resourceMetadata, boolean useResourceRoleMappings) {
public BearerTokenAuthenticator(ResourceMetadata resourceMetadata, int notBefore, boolean useResourceRoleMappings) {
this.resourceMetadata = resourceMetadata;
this.useResourceRoleMappings = useResourceRoleMappings;
this.notBefore = notBefore;
}
public KeycloakChallenge getChallenge() {
@ -83,8 +85,12 @@ public class BearerTokenAuthenticator {
challenge = challengeResponse(exchange, "invalid_token", e.getMessage());
return AuthenticationMechanism.AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
}
if (token.getIssuedAt() < notBefore) {
log.error("Stale token");
challenge = challengeResponse(exchange, "invalid_token", "Stale token");
return AuthenticationMechanism.AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
}
boolean verifyCaller = false;
Set<String> roles = new HashSet<String>();
if (useResourceRoleMappings) {
verifyCaller = token.isVerifyCaller(resourceMetadata.getResourceName());
} else {

View file

@ -5,6 +5,7 @@ import io.undertow.security.api.SecurityContext;
import io.undertow.security.idm.Account;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.AttachmentKey;
import io.undertow.util.Headers;
import org.jboss.logging.Logger;
import org.keycloak.KeycloakAuthenticatedSession;
import org.keycloak.KeycloakPrincipal;
@ -53,6 +54,7 @@ public class KeycloakAuthenticationMechanism implements AuthenticationMechanism
@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
log.info("--> authenticate()");
BearerTokenAuthenticator bearer = createBearerTokenAuthenticator();
AuthenticationMechanismOutcome outcome = bearer.authenticate(exchange);
if (outcome == AuthenticationMechanismOutcome.NOT_AUTHENTICATED) {
@ -80,16 +82,26 @@ public class KeycloakAuthenticationMechanism implements AuthenticationMechanism
}
completeAuthentication(exchange, securityContext, oauth);
exchange.getResponseHeaders().put(Headers.LOCATION, oauth.getStrippedOauthParametersRequestUri());
exchange.setResponseCode(302);
exchange.endExchange();
log.info("AUTHENTICATED");
return AuthenticationMechanismOutcome.AUTHENTICATED;
}
public static void sendRedirect(final HttpServerExchange exchange, final String location) {
// TODO - String concatenation to construct URLS is extremely error prone - switch to a URI which will better handle this.
String loc = exchange.getRequestScheme() + "://" + exchange.getHostAndPort() + location;
}
protected OAuthAuthenticator createOAuthAuthenticator(HttpServerExchange exchange) {
return new OAuthAuthenticator(exchange, realmConfig, sslRedirectPort);
}
protected BearerTokenAuthenticator createBearerTokenAuthenticator() {
return new BearerTokenAuthenticator(resourceMetadata, adapterConfig.isUseResourceRoleMappings());
return new BearerTokenAuthenticator(resourceMetadata, realmConfig.getNotBefore(), adapterConfig.isUseResourceRoleMappings());
}
protected void completeAuthentication(HttpServerExchange exchange, SecurityContext securityContext, OAuthAuthenticator oauth) {

View file

@ -3,20 +3,10 @@ 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 $
@ -35,7 +25,10 @@ class KeycloakIdentityManager implements IdentityManager {
public Account verify(Account account) {
log.info("Verifying account in IdentityManager");
KeycloakUndertowAccount keycloakAccount = (KeycloakUndertowAccount)account;
if (!keycloakAccount.isActive(realmConfiguration, adapterConfig)) return null;
if (!keycloakAccount.isActive(realmConfiguration, adapterConfig)) {
log.info("account.isActive() returned false, returning null");
return null;
}
return account;
}

View file

@ -70,21 +70,17 @@ public class KeycloakServletExtension implements ServletExtension {
PreflightCorsHandler.Wrapper preflight = new PreflightCorsHandler.Wrapper(keycloakConfig);
UserSessionManagement userSessionManagement = new UserSessionManagement(realmConfiguration);
ServletKeycloakAuthenticationMechanism auth = null;
if (keycloakConfig.isBearerOnly()) {
auth = new ServletKeycloakAuthenticationMechanism(keycloakConfig, loader.getResourceMetadata(), deploymentInfo.getConfidentialPortManager());
} else {
auth = new ServletKeycloakAuthenticationMechanism(
auth = new ServletKeycloakAuthenticationMechanism(
userSessionManagement,
keycloakConfig,
realmConfiguration,
deploymentInfo.getConfidentialPortManager());
}
AuthenticatedActionsHandler.Wrapper actions = new AuthenticatedActionsHandler.Wrapper(keycloakConfig);
// setup handlers
deploymentInfo.addInitialHandlerChainWrapper(preflight); // cors preflight
deploymentInfo.addOuterHandlerChainWrapper(new ServletAdminActionsHandler.Wrapper(realmConfiguration, userSessionManagement));
deploymentInfo.addOuterHandlerChainWrapper(new ServletAdminActionsHandler.Wrapper(realmConfiguration, loader.getResourceMetadata(), userSessionManagement));
final ServletKeycloakAuthenticationMechanism theAuth = auth;
deploymentInfo.addAuthenticationMechanism("KEYCLOAK", new AuthenticationMechanismFactory() {
@Override

View file

@ -69,6 +69,7 @@ public class KeycloakUndertowAccount implements Account, Serializable {
// this object may have been serialized, so we need to reset realm config/metadata
session.setRealmConfiguration(realmConfiguration);
session.setMetadata(realmConfiguration.getMetadata());
log.info("realmConfig notBefore: " + realmConfiguration.getNotBefore());
if (session.isActive()) return true;
session.refreshExpiredToken();

View file

@ -9,9 +9,9 @@ import io.undertow.util.Headers;
import io.undertow.util.StatusCodes;
import org.jboss.logging.Logger;
import org.keycloak.RSATokenVerifier;
import org.keycloak.adapters.ServerRequest;
import org.keycloak.adapters.config.RealmConfiguration;
import org.keycloak.VerificationException;
import org.keycloak.adapters.TokenGrantRequest;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.AccessTokenResponse;
@ -39,6 +39,7 @@ public class OAuthAuthenticator {
protected HttpServerExchange exchange;
protected KeycloakChallenge challenge;
protected String refreshToken;
protected String strippedOauthParametersRequestUri;
public OAuthAuthenticator(HttpServerExchange exchange, RealmConfiguration realmInfo, int sslRedirectPort) {
this.exchange = exchange;
@ -78,6 +79,14 @@ public class OAuthAuthenticator {
this.idToken = idToken;
}
public String getStrippedOauthParametersRequestUri() {
return strippedOauthParametersRequestUri;
}
public void setStrippedOauthParametersRequestUri(String strippedOauthParametersRequestUri) {
this.strippedOauthParametersRequestUri = strippedOauthParametersRequestUri;
}
protected String getRequestUrl() {
KeycloakUriBuilder uriBuilder = KeycloakUriBuilder.fromUri(exchange.getRequestURI())
.replaceQuery(exchange.getQueryString());
@ -257,10 +266,10 @@ public class OAuthAuthenticator {
if (challenge != null) return challenge;
AccessTokenResponse tokenResponse = null;
String redirectUri = stripOauthParametersFromRedirect();
strippedOauthParametersRequestUri = stripOauthParametersFromRedirect();
try {
tokenResponse = TokenGrantRequest.invokeAccessCodeToToken(realmInfo, code, redirectUri);
} catch (TokenGrantRequest.HttpFailure failure) {
tokenResponse = ServerRequest.invokeAccessCodeToToken(realmInfo, code, strippedOauthParametersRequestUri);
} catch (ServerRequest.HttpFailure failure) {
log.error("failed to turn code into token");
log.error("status from server: " + failure.getStatus());
if (failure.getStatus() == StatusCodes.BAD_REQUEST && failure.getError() != null) {
@ -291,6 +300,13 @@ public class OAuthAuthenticator {
log.error("failed verification of token");
return challenge(StatusCodes.FORBIDDEN);
}
if (tokenResponse.getNotBeforePolicy() > realmInfo.getNotBefore()) {
realmInfo.setNotBefore(tokenResponse.getNotBeforePolicy());
}
if (token.getIssuedAt() < realmInfo.getNotBefore()) {
log.error("Stale token");
return challenge(StatusCodes.FORBIDDEN);
}
log.info("successful authenticated");
return null;
}

View file

@ -8,9 +8,12 @@ import io.undertow.servlet.handlers.ServletRequestContext;
import io.undertow.util.StatusCodes;
import org.jboss.logging.Logger;
import org.keycloak.adapters.AdapterConstants;
import org.keycloak.adapters.ResourceMetadata;
import org.keycloak.adapters.config.RealmConfiguration;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.representations.adapters.action.PushNotBeforeAction;
import org.keycloak.util.JsonSerialization;
import org.keycloak.util.StreamUtil;
import javax.servlet.http.HttpServletRequest;
@ -26,26 +29,32 @@ public class ServletAdminActionsHandler implements HttpHandler {
protected HttpHandler next;
protected UserSessionManagement userSessionManagement;
protected RealmConfiguration realmConfig;
protected ResourceMetadata resourceMetadata;
public static class Wrapper implements HandlerWrapper {
protected RealmConfiguration realmConfig;
protected ResourceMetadata resourceMetadata;
protected UserSessionManagement userSessionManagement;
public Wrapper(RealmConfiguration realmConfig, UserSessionManagement userSessionManagement) {
public Wrapper(RealmConfiguration realmConfig, ResourceMetadata resourceMetadata, UserSessionManagement userSessionManagement) {
this.realmConfig = realmConfig;
this.resourceMetadata = resourceMetadata;
this.userSessionManagement = userSessionManagement;
}
@Override
public HttpHandler wrap(HttpHandler handler) {
return new ServletAdminActionsHandler(realmConfig, userSessionManagement, handler);
return new ServletAdminActionsHandler(realmConfig, resourceMetadata, userSessionManagement, handler);
}
}
protected ServletAdminActionsHandler(RealmConfiguration realmConfig,
ResourceMetadata resourceMetadata,
UserSessionManagement userSessionManagement,
HttpHandler next) {
this.next = next;
this.resourceMetadata = resourceMetadata;
this.userSessionManagement = userSessionManagement;
this.realmConfig = realmConfig;
}
@ -89,9 +98,32 @@ public class ServletAdminActionsHandler implements HttpHandler {
if (token == null) return;
userSessionManagement.remoteLogout(token, manager, response);
return;
} else if (requestUri.endsWith(AdapterConstants.K_PUSH_NOT_BEFORE)) {
handlePushNotBefore(request, response);
return;
} else {
next.handleRequest(exchange);
return;
}
}
protected void handlePushNotBefore(HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("K_PUSH_NOT_BEFORE sent");
JWSInput token = verifyAdminRequest(request, response);
if (token == null) return;
PushNotBeforeAction action = JsonSerialization.readValue(token.getContent(), PushNotBeforeAction.class);
if (action.isExpired()) {
log.warn("admin request failed, expired token");
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Expired token");
return;
}
if (!resourceMetadata.getResourceName().equals(action.getResource())) {
log.warn("Resource name does not match");
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Resource name does not match");
return;
}
realmConfig.setNotBefore(action.getNotBefore());
return;
}
}

View file

@ -1,8 +1,10 @@
package org.keycloak.adapters.undertow;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.session.Session;
import io.undertow.servlet.api.ConfidentialPortManager;
import io.undertow.servlet.handlers.ServletRequestContext;
import io.undertow.servlet.spec.HttpSessionImpl;
import org.keycloak.KeycloakAuthenticatedSession;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.adapters.config.RealmConfiguration;
@ -10,7 +12,10 @@ import org.keycloak.adapters.ResourceMetadata;
import org.keycloak.representations.adapters.config.AdapterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.AccessController;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
@ -45,5 +50,4 @@ public class ServletKeycloakAuthenticationMechanism extends KeycloakAuthenticati
userSessionManagement.login(servletRequestContext.getDeployment().getSessionManager(), session, account.getPrincipal().getName());
}
}

View file

@ -173,4 +173,13 @@ public interface RealmModel extends RoleContainerModel, RoleMapperModel, ScopeMa
void setAccountTheme(String name);
boolean hasScope(ClientModel client, RoleModel role);
/**
* Time in seconds since epoc
*
* @return
*/
int getNotBefore();
void setNotBefore(int notBefore);
}

View file

@ -139,6 +139,16 @@ public class RealmAdapter implements RealmModel {
em.flush();
}
@Override
public int getNotBefore() {
return realm.getNotBefore();
}
@Override
public void setNotBefore(int notBefore) {
realm.setNotBefore(notBefore);
}
@Override
public int getAccessTokenLifespan() {
return realm.getAccessTokenLifespan();

View file

@ -49,6 +49,7 @@ public class RealmEntity {
protected int accessCodeLifespan;
protected int accessCodeLifespanUserAction;
protected int refreshTokenLifespan;
protected int notBefore;
@Column(length = 2048)
protected String publicKeyPem;
@ -298,5 +299,13 @@ public class RealmEntity {
public void setAccountTheme(String theme) {
this.accountTheme = theme;
}
public int getNotBefore() {
return notBefore;
}
public void setNotBefore(int notBefore) {
this.notBefore = notBefore;
}
}

View file

@ -179,6 +179,17 @@ public class RealmAdapter extends AbstractAdapter implements RealmModel {
updateRealm();
}
@Override
public int getNotBefore() {
return realm.getNotBefore();
}
@Override
public void setNotBefore(int notBefore) {
realm.setNotBefore(notBefore);
}
@Override
public int getAccessTokenLifespan() {
return realm.getAccessTokenLifespan();

View file

@ -35,6 +35,7 @@ public class RealmEntity extends AbstractMongoIdentifiableEntity implements Mong
private int accessCodeLifespan;
private int accessCodeLifespanUserAction;
private int refreshTokenLifespan;
private int notBefore;
private String publicKeyPem;
private String privateKeyPem;
@ -140,6 +141,15 @@ public class RealmEntity extends AbstractMongoIdentifiableEntity implements Mong
this.passwordPolicy = passwordPolicy;
}
@MongoField
public int getNotBefore() {
return notBefore;
}
public void setNotBefore(int notBefore) {
this.notBefore = notBefore;
}
@MongoField
public int getCentralLoginLifespan() {
return centralLoginLifespan;

View file

@ -67,6 +67,7 @@ public class ModelToRepresentation {
rep.setRealm(realm.getName());
rep.setEnabled(realm.isEnabled());
rep.setSocial(realm.isSocial());
rep.setNotBefore(realm.getNotBefore());
rep.setUpdateProfileOnInitialSocialLogin(realm.isUpdateProfileOnInitialSocialLogin());
rep.setSslNotRequired(realm.isSslNotRequired());
rep.setPublicKey(realm.getPublicKeyPem());

View file

@ -121,6 +121,7 @@ public class RealmManager {
if (rep.getAccessCodeLifespan() != null) realm.setAccessCodeLifespan(rep.getAccessCodeLifespan());
if (rep.getAccessCodeLifespanUserAction() != null)
realm.setAccessCodeLifespanUserAction(rep.getAccessCodeLifespanUserAction());
if (rep.getNotBefore() != null) realm.setNotBefore(rep.getNotBefore());
if (rep.getAccessTokenLifespan() != null) realm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
if (rep.getRefreshTokenLifespan() != null) realm.setRefreshTokenLifespan(rep.getRefreshTokenLifespan());
if (rep.getCentralLoginLifespan() != null) realm.setCentralLoginLifespan(rep.getCentralLoginLifespan());
@ -201,6 +202,8 @@ public class RealmManager {
if (rep.isEnabled() != null) newRealm.setEnabled(rep.isEnabled());
if (rep.isSocial() != null) newRealm.setSocial(rep.isSocial());
if (rep.getNotBefore() != null) newRealm.setNotBefore(rep.getNotBefore());
if (rep.getAccessTokenLifespan() != null) newRealm.setAccessTokenLifespan(rep.getAccessTokenLifespan());
else newRealm.setAccessTokenLifespan(300);

View file

@ -8,6 +8,7 @@ import org.keycloak.adapters.AdapterConstants;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.RealmModel;
import org.keycloak.representations.adapters.action.LogoutAction;
import org.keycloak.representations.adapters.action.PushNotBeforeAction;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
@ -20,26 +21,26 @@ import java.util.List;
public class ResourceAdminManager {
protected static Logger logger = Logger.getLogger(ResourceAdminManager.class);
public void logoutAll(RealmModel realm) {
singleLogOut(realm, null);
}
public void singleLogOut(RealmModel realm, String user) {
ResteasyClient client = new ResteasyClientBuilder()
.disableTrustManager() // todo fix this, should have a trust manager or a good default
.build();
List<ApplicationModel> resources = realm.getApplications();
logger.debug("logging out {0} resources ", resources.size());
for (ApplicationModel resource : resources) {
logoutResource(realm, resource, user, client);
try {
List<ApplicationModel> resources = realm.getApplications();
logger.debug("logging out {0} resources ", resources.size());
for (ApplicationModel resource : resources) {
logoutResource(realm, resource, user, client);
}
} finally {
client.close();
}
}
protected boolean logoutResource(RealmModel realm, ApplicationModel resource, String user, ResteasyClient client) {
String managementUrl = resource.getManagementUrl();
if (managementUrl != null) {
LogoutAction adminAction = new LogoutAction(TokenIdGenerator.generateId(), System.currentTimeMillis() / 1000 + 30, resource.getName(), user);
LogoutAction adminAction = new LogoutAction(TokenIdGenerator.generateId(), (int)(System.currentTimeMillis() / 1000) + 30, resource.getName(), user);
String token = new TokenManager().encodeToken(realm, adminAction);
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));
@ -53,4 +54,37 @@ public class ResourceAdminManager {
}
}
public void pushRevocationPolicies(RealmModel realm) {
ResteasyClient client = new ResteasyClientBuilder()
.disableTrustManager() // todo fix this, should have a trust manager or a good default
.build();
try {
for (ApplicationModel application : realm.getApplications()) {
pushRevocationPolicies(realm, application, client);
}
} finally {
client.close();
}
}
public boolean pushRevocationPolicies(RealmModel realm, ApplicationModel resource, ResteasyClient client) {
if (realm.getNotBefore() <= 0) return false;
String managementUrl = resource.getManagementUrl();
if (managementUrl != null) {
PushNotBeforeAction adminAction = new PushNotBeforeAction(TokenIdGenerator.generateId(), (int)(System.currentTimeMillis() / 1000) + 30, resource.getName(), realm.getNotBefore());
String token = new TokenManager().encodeToken(realm, adminAction);
logger.info("pushRevocation resource: {0} url: {1}", resource.getName(), managementUrl);
Response response = client.target(managementUrl).path(AdapterConstants.K_PUSH_NOT_BEFORE).request().post(Entity.text(token));
boolean success = response.getStatus() == 204;
response.close();
logger.info("pushRevocation success.");
return success;
} else {
logger.info("no management URL for application: " + resource.getName());
return false;
}
}
}

View file

@ -132,6 +132,10 @@ public class TokenManager {
throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Refresh token expired");
}
if (refreshToken.getIssuedAt() < realm.getNotBefore()) {
throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Stale refresh token");
}
UserModel user = realm.getUserById(refreshToken.getSubject());
if (user == null) {
throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid refresh token", "Unknown user");
@ -459,6 +463,7 @@ public class TokenManager {
String encodedToken = new JWSBuilder().jsonContent(refreshToken).rsa256(realm.getPrivateKey());
res.setRefreshToken(encodedToken);
}
res.setNotBeforePolicy(realm.getNotBefore());
return res;
}
}

View file

@ -44,6 +44,7 @@ public class PublicRealmResource {
rep.setAccountServiceUrl(AccountService.accountServiceBaseUrl(uriInfo).build(realm.getId()).toString());
rep.setAdminApiUrl(AdminService.adminApiUrl(uriInfo).build(realm.getId()).toString());
rep.setPublicKeyPem(realm.getPublicKeyPem());
rep.setNotBefore(realm.getNotBefore());
return rep;
}

View file

@ -3,12 +3,14 @@ package org.keycloak.services.resources.admin;
import org.jboss.resteasy.annotations.cache.NoCache;
import org.jboss.resteasy.logging.Logger;
import org.keycloak.models.AdminRoles;
import org.keycloak.models.ApplicationModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.services.managers.Auth;
import org.keycloak.services.managers.ModelToRepresentation;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.services.managers.ResourceAdminManager;
import org.keycloak.services.managers.TokenManager;
import javax.ws.rs.*;
@ -106,4 +108,11 @@ public class RealmAdminResource {
return resource;
}
@Path("push-revocation")
@POST
public void pushRevocation() {
auth.requireManage();
new ResourceAdminManager().pushRevocationPolicies(realm);
}
}