commit
5eddacfee9
52 files changed
+695
-322
No files matched your search
@@ -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'
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
+31
@@ -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>
|
||||
+3
-3
@@ -10,17 +10,17 @@ import java.io.Serializable;
|
||||
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
|
||||
* @version $Revision: 1 $
|
||||
*/
|
||||
public class KeycloakAuthenticatedSession implements Serializable {
|
||||
public class KeycloakSecurityContext implements Serializable {
|
||||
protected String tokenString;
|
||||
protected AccessToken token;
|
||||
protected IDToken idToken;
|
||||
protected String idTokenString;
|
||||
protected transient ResourceMetadata metadata;
|
||||
|
||||
public KeycloakAuthenticatedSession() {
|
||||
public KeycloakSecurityContext() {
|
||||
}
|
||||
|
||||
public KeycloakAuthenticatedSession(String tokenString, AccessToken token, String idTokenString, IDToken idToken, ResourceMetadata metadata) {
|
||||
public KeycloakSecurityContext(String tokenString, AccessToken token, String idTokenString, IDToken idToken, ResourceMetadata metadata) {
|
||||
this.tokenString = tokenString;
|
||||
this.token = token;
|
||||
this.idToken = idToken;
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+26
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -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.KeycloakAuthenticatedSession;
|
||||
import org.keycloak.KeycloakSecurityContext;
|
||||
import org.keycloak.adapters.HttpClientBuilder;
|
||||
import org.keycloak.representations.IDToken;
|
||||
import org.keycloak.util.JsonSerialization;
|
||||
@@ -37,13 +37,13 @@ public class CustomerDatabaseClient {
|
||||
}
|
||||
|
||||
public static IDToken getIDToken(HttpServletRequest req) {
|
||||
KeycloakAuthenticatedSession session = (KeycloakAuthenticatedSession) req.getAttribute(KeycloakAuthenticatedSession.class.getName());
|
||||
KeycloakSecurityContext session = (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());
|
||||
return session.getIdToken();
|
||||
|
||||
}
|
||||
|
||||
public static List<String> getCustomers(HttpServletRequest req) throws Failure {
|
||||
KeycloakAuthenticatedSession session = (KeycloakAuthenticatedSession) req.getAttribute(KeycloakAuthenticatedSession.class.getName());
|
||||
KeycloakSecurityContext session = (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());
|
||||
|
||||
HttpClient client = new HttpClientBuilder()
|
||||
.trustStore(session.getMetadata().getTruststore())
|
||||
|
||||
+2
-2
@@ -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.KeycloakAuthenticatedSession;
|
||||
import org.keycloak.KeycloakSecurityContext;
|
||||
import org.keycloak.adapters.HttpClientBuilder;
|
||||
import org.keycloak.util.JsonSerialization;
|
||||
|
||||
@@ -35,7 +35,7 @@ public class ProductDatabaseClient
|
||||
}
|
||||
|
||||
public static List<String> getProducts(HttpServletRequest req) throws Failure {
|
||||
KeycloakAuthenticatedSession session = (KeycloakAuthenticatedSession)req.getAttribute(KeycloakAuthenticatedSession.class.getName());
|
||||
KeycloakSecurityContext session = (KeycloakSecurityContext)req.getAttribute(KeycloakSecurityContext.class.getName());
|
||||
HttpClient client = new HttpClientBuilder()
|
||||
.trustStore(session.getMetadata().getTruststore())
|
||||
.hostnameVerification(HttpClientBuilder.HostnameVerificationPolicy.ANY).build();
|
||||
|
||||
-1
@@ -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;
|
||||
|
||||
|
||||
+2
-2
@@ -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")) {
|
||||
|
||||
+2
-2
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
+6
-6
@@ -1,6 +1,6 @@
|
||||
package org.keycloak.adapters;
|
||||
|
||||
import org.keycloak.KeycloakAuthenticatedSession;
|
||||
import org.keycloak.KeycloakSecurityContext;
|
||||
import org.keycloak.RSATokenVerifier;
|
||||
import org.keycloak.VerificationException;
|
||||
import org.keycloak.adapters.config.RealmConfiguration;
|
||||
@@ -15,7 +15,7 @@ import java.io.IOException;
|
||||
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
|
||||
* @version $Revision: 1 $
|
||||
*/
|
||||
public class RefreshableKeycloakSession extends KeycloakAuthenticatedSession {
|
||||
public class RefreshableKeycloakSession extends KeycloakSecurityContext {
|
||||
|
||||
protected static Logger log = Logger.getLogger(RefreshableKeycloakSession.class);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+1
-1
@@ -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;
|
||||
+8
@@ -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;
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -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();
|
||||
|
||||
|
||||
+8
-8
@@ -7,7 +7,7 @@ import org.apache.catalina.connector.Request;
|
||||
import org.apache.catalina.connector.Response;
|
||||
import org.apache.catalina.valves.ValveBase;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.keycloak.KeycloakAuthenticatedSession;
|
||||
import org.keycloak.KeycloakSecurityContext;
|
||||
import org.keycloak.adapters.AdapterConstants;
|
||||
import org.keycloak.representations.AccessToken;
|
||||
import org.keycloak.representations.adapters.config.AdapterConfig;
|
||||
@@ -45,7 +45,7 @@ public class AuthenticatedActionsValve extends ValveBase {
|
||||
@Override
|
||||
public void invoke(Request request, Response response) throws IOException, ServletException {
|
||||
log.debugv("AuthenticatedActionsValve.invoke {0}", request.getRequestURI());
|
||||
KeycloakAuthenticatedSession session = getSkeletonKeySession(request);
|
||||
KeycloakSecurityContext session = getSkeletonKeySession(request);
|
||||
if (corsRequest(request, response, session)) return;
|
||||
String requestUri = request.getRequestURI();
|
||||
if (requestUri.endsWith(AdapterConstants.K_QUERY_BEARER_TOKEN)) {
|
||||
@@ -55,17 +55,17 @@ public class AuthenticatedActionsValve extends ValveBase {
|
||||
getNext().invoke(request, response);
|
||||
}
|
||||
|
||||
public KeycloakAuthenticatedSession getSkeletonKeySession(Request request) {
|
||||
KeycloakAuthenticatedSession skSession = (KeycloakAuthenticatedSession) request.getAttribute(KeycloakAuthenticatedSession.class.getName());
|
||||
public KeycloakSecurityContext getSkeletonKeySession(Request request) {
|
||||
KeycloakSecurityContext skSession = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
|
||||
if (skSession != null) return skSession;
|
||||
Session session = request.getSessionInternal();
|
||||
if (session != null) {
|
||||
return (KeycloakAuthenticatedSession) session.getNote(KeycloakAuthenticatedSession.class.getName());
|
||||
return (KeycloakSecurityContext) session.getNote(KeycloakSecurityContext.class.getName());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected void queryBearerToken(Request request, Response response, KeycloakAuthenticatedSession session) throws IOException, ServletException {
|
||||
protected void queryBearerToken(Request request, Response response, KeycloakSecurityContext session) throws IOException, ServletException {
|
||||
log.debugv("queryBearerToken {0}", request.getRequestURI());
|
||||
if (abortTokenResponse(request, response, session)) return;
|
||||
response.setStatus(HttpServletResponse.SC_OK);
|
||||
@@ -75,7 +75,7 @@ public class AuthenticatedActionsValve extends ValveBase {
|
||||
|
||||
}
|
||||
|
||||
protected boolean abortTokenResponse(Request request, Response response, KeycloakAuthenticatedSession session) throws IOException {
|
||||
protected boolean abortTokenResponse(Request request, Response response, KeycloakSecurityContext session) throws IOException {
|
||||
if (session == null) {
|
||||
log.debugv("session was null, sending back 401: {0}", request.getRequestURI());
|
||||
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
@@ -92,7 +92,7 @@ public class AuthenticatedActionsValve extends ValveBase {
|
||||
return false;
|
||||
}
|
||||
|
||||
protected boolean corsRequest(Request request, Response response, KeycloakAuthenticatedSession session) throws IOException {
|
||||
protected boolean corsRequest(Request request, Response response, KeycloakSecurityContext session) throws IOException {
|
||||
if (!config.isCors()) return false;
|
||||
log.debugv("CORS enabled + request.getRequestURI()");
|
||||
String origin = request.getHeader("Origin");
|
||||
|
||||
+13
-5
@@ -2,7 +2,7 @@ package org.keycloak.adapters.as7;
|
||||
|
||||
import org.apache.catalina.connector.Request;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.keycloak.KeycloakAuthenticatedSession;
|
||||
import org.keycloak.KeycloakSecurityContext;
|
||||
import org.keycloak.KeycloakPrincipal;
|
||||
import org.keycloak.RSATokenVerifier;
|
||||
import org.keycloak.adapters.ResourceMetadata;
|
||||
@@ -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,9 +113,9 @@ 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");
|
||||
KeycloakAuthenticatedSession skSession = new KeycloakAuthenticatedSession(tokenString, token, null, null, resourceMetadata);
|
||||
request.setAttribute(KeycloakAuthenticatedSession.class.getName(), skSession);
|
||||
request.setAuthType("KEYCLOAK");
|
||||
KeycloakSecurityContext skSession = new KeycloakSecurityContext(tokenString, token, null, null, resourceMetadata);
|
||||
request.setAttribute(KeycloakSecurityContext.class.getName(), skSession);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
+39
-8
@@ -13,13 +13,14 @@ import org.apache.catalina.core.StandardContext;
|
||||
import org.apache.catalina.deploy.LoginConfig;
|
||||
import org.apache.catalina.realm.GenericPrincipal;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.keycloak.KeycloakAuthenticatedSession;
|
||||
import org.keycloak.KeycloakSecurityContext;
|
||||
import org.keycloak.KeycloakPrincipal;
|
||||
import org.keycloak.adapters.AdapterConstants;
|
||||
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;
|
||||
}
|
||||
@@ -193,7 +224,7 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
|
||||
*/
|
||||
protected void checkKeycloakSession(Request request) {
|
||||
if (request.getSessionInternal(false) == null || request.getSessionInternal().getPrincipal() == null) return;
|
||||
RefreshableKeycloakSession session = (RefreshableKeycloakSession)request.getSessionInternal().getNote(KeycloakAuthenticatedSession.class.getName());
|
||||
RefreshableKeycloakSession session = (RefreshableKeycloakSession)request.getSessionInternal().getNote(KeycloakSecurityContext.class.getName());
|
||||
if (session == null) return;
|
||||
// just in case session got serialized
|
||||
session.setRealmConfiguration(realmConfiguration);
|
||||
@@ -205,7 +236,7 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
|
||||
session.refreshExpiredToken();
|
||||
if (session.isActive()) return;
|
||||
|
||||
request.getSessionInternal().removeNote(KeycloakAuthenticatedSession.class.getName());
|
||||
request.getSessionInternal().removeNote(KeycloakSecurityContext.class.getName());
|
||||
request.setUserPrincipal(null);
|
||||
request.setAuthType(null);
|
||||
request.getSessionInternal().setPrincipal(null);
|
||||
@@ -221,9 +252,9 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
|
||||
request.setAuthType("KEYCLOAK");
|
||||
Session session = request.getSessionInternal();
|
||||
if (session != null) {
|
||||
KeycloakAuthenticatedSession skSession = (KeycloakAuthenticatedSession) session.getNote(KeycloakAuthenticatedSession.class.getName());
|
||||
KeycloakSecurityContext skSession = (KeycloakSecurityContext) session.getNote(KeycloakSecurityContext.class.getName());
|
||||
if (skSession != null) {
|
||||
request.setAttribute(KeycloakAuthenticatedSession.class.getName(), skSession);
|
||||
request.setAttribute(KeycloakSecurityContext.class.getName(), skSession);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
@@ -262,8 +293,8 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
|
||||
Session session = request.getSessionInternal(true);
|
||||
session.setPrincipal(principal);
|
||||
session.setAuthType("OAUTH");
|
||||
KeycloakAuthenticatedSession skSession = new RefreshableKeycloakSession(oauth.getTokenString(), oauth.getToken(), oauth.getIdTokenString(), oauth.getIdToken(), resourceMetadata, realmConfiguration, oauth.getRefreshToken());
|
||||
session.setNote(KeycloakAuthenticatedSession.class.getName(), skSession);
|
||||
KeycloakSecurityContext skSession = new RefreshableKeycloakSession(oauth.getTokenString(), oauth.getToken(), oauth.getIdTokenString(), oauth.getIdToken(), resourceMetadata, realmConfiguration, oauth.getRefreshToken());
|
||||
session.setNote(KeycloakSecurityContext.class.getName(), skSession);
|
||||
|
||||
String username = token.getSubject();
|
||||
log.debug("userSessionManage.login: " + username);
|
||||
|
||||
+12
-3
@@ -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);
|
||||
|
||||
+3
-3
@@ -2,7 +2,7 @@ package org.keycloak.jaxrs;
|
||||
|
||||
import org.jboss.resteasy.logging.Logger;
|
||||
import org.jboss.resteasy.spi.ResteasyProviderFactory;
|
||||
import org.keycloak.KeycloakAuthenticatedSession;
|
||||
import org.keycloak.KeycloakSecurityContext;
|
||||
import org.keycloak.KeycloakPrincipal;
|
||||
import org.keycloak.RSATokenVerifier;
|
||||
import org.keycloak.adapters.ResourceMetadata;
|
||||
@@ -67,8 +67,8 @@ public class JaxrsBearerTokenFilter implements ContainerRequestFilter {
|
||||
|
||||
try {
|
||||
AccessToken token = RSATokenVerifier.verifyToken(tokenString, resourceMetadata.getRealmKey(), resourceMetadata.getRealm());
|
||||
KeycloakAuthenticatedSession skSession = new KeycloakAuthenticatedSession(tokenString, token, null, null, resourceMetadata);
|
||||
ResteasyProviderFactory.pushContext(KeycloakAuthenticatedSession.class, skSession);
|
||||
KeycloakSecurityContext skSession = new KeycloakSecurityContext(tokenString, token, null, null, resourceMetadata);
|
||||
ResteasyProviderFactory.pushContext(KeycloakSecurityContext.class, skSession);
|
||||
String callerPrincipal = securityContext.getUserPrincipal() != null ? securityContext.getUserPrincipal().getName() : null;
|
||||
|
||||
final KeycloakPrincipal principal = new KeycloakPrincipal(token.getSubject(), callerPrincipal);
|
||||
|
||||
+7
-7
@@ -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) {
|
||||
|
||||
+8
-2
@@ -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 {
|
||||
|
||||
+42
-24
@@ -2,22 +2,16 @@ package org.keycloak.adapters.undertow;
|
||||
|
||||
import io.undertow.security.api.AuthenticationMechanism;
|
||||
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;
|
||||
import org.keycloak.adapters.RefreshableKeycloakSession;
|
||||
import org.keycloak.adapters.config.RealmConfiguration;
|
||||
import org.keycloak.adapters.ResourceMetadata;
|
||||
import org.keycloak.representations.AccessToken;
|
||||
import org.keycloak.adapters.config.RealmConfiguration;
|
||||
import org.keycloak.representations.adapters.config.AdapterConfig;
|
||||
|
||||
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 $
|
||||
@@ -26,7 +20,6 @@ public class KeycloakAuthenticationMechanism implements AuthenticationMechanism
|
||||
protected Logger log = Logger.getLogger(KeycloakAuthenticationMechanism.class);
|
||||
|
||||
public static final AttachmentKey<KeycloakChallenge> KEYCLOAK_CHALLENGE_ATTACHMENT_KEY = AttachmentKey.create(KeycloakChallenge.class);
|
||||
public static final AttachmentKey<KeycloakAuthenticatedSession> SKELETON_KEY_SESSION_ATTACHMENT_KEY = AttachmentKey.create(KeycloakAuthenticatedSession.class);
|
||||
|
||||
protected ResourceMetadata resourceMetadata;
|
||||
protected AdapterConfig adapterConfig;
|
||||
@@ -40,11 +33,6 @@ public class KeycloakAuthenticationMechanism implements AuthenticationMechanism
|
||||
this.sslRedirectPort = sslRedirectPort;
|
||||
}
|
||||
|
||||
public KeycloakAuthenticationMechanism(AdapterConfig adapterConfig, ResourceMetadata resourceMetadata) {
|
||||
this.resourceMetadata = resourceMetadata;
|
||||
this.adapterConfig = adapterConfig;
|
||||
}
|
||||
|
||||
public KeycloakAuthenticationMechanism(AdapterConfig adapterConfig, RealmConfiguration realmConfig) {
|
||||
this.resourceMetadata = realmConfig.getMetadata();
|
||||
this.adapterConfig = adapterConfig;
|
||||
@@ -53,33 +41,48 @@ 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) {
|
||||
exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, bearer.getChallenge());
|
||||
return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
|
||||
}
|
||||
else if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) {
|
||||
completeAuthentication(securityContext, bearer);
|
||||
} else if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) {
|
||||
completeAuthentication(exchange, securityContext, bearer);
|
||||
return AuthenticationMechanismOutcome.AUTHENTICATED;
|
||||
}
|
||||
else if (adapterConfig.isBearerOnly()) {
|
||||
} else if (adapterConfig.isBearerOnly()) {
|
||||
exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, bearer.getChallenge());
|
||||
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
|
||||
}
|
||||
// We cache account ourselves instead of using the Cache session handler of Undertow because
|
||||
// Undertow will return a 403 from an invalid account when calling IdentityManager.verify(Account) and
|
||||
// we want to just return NOT_ATTEMPTED so we can be redirected to relogin
|
||||
KeycloakUndertowAccount account = checkCachedAccount(exchange);
|
||||
if (account != null) {
|
||||
log.info("Cached account found");
|
||||
securityContext.authenticationComplete(account, "KEYCLOAK", false);
|
||||
propagateKeycloakContext(exchange, account);
|
||||
return AuthenticationMechanismOutcome.AUTHENTICATED;
|
||||
}
|
||||
|
||||
|
||||
OAuthAuthenticator oauth = createOAuthAuthenticator(exchange);
|
||||
outcome = oauth.authenticate();
|
||||
if (outcome == AuthenticationMechanismOutcome.NOT_AUTHENTICATED) {
|
||||
exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, oauth.getChallenge());
|
||||
return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
|
||||
}
|
||||
else if (outcome == AuthenticationMechanismOutcome.NOT_ATTEMPTED) {
|
||||
} else if (outcome == AuthenticationMechanismOutcome.NOT_ATTEMPTED) {
|
||||
exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, oauth.getChallenge());
|
||||
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
|
||||
|
||||
}
|
||||
completeAuthentication(exchange, securityContext, oauth);
|
||||
|
||||
// redirect to strip out access code and state query parameters
|
||||
exchange.getResponseHeaders().put(Headers.LOCATION, oauth.getStrippedOauthParametersRequestUri());
|
||||
exchange.setResponseCode(302);
|
||||
exchange.endExchange();
|
||||
|
||||
log.info("AUTHENTICATED");
|
||||
return AuthenticationMechanismOutcome.AUTHENTICATED;
|
||||
}
|
||||
@@ -89,14 +92,18 @@ public class KeycloakAuthenticationMechanism implements AuthenticationMechanism
|
||||
}
|
||||
|
||||
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) {
|
||||
final KeycloakPrincipal principal = new KeycloakPrincipal(oauth.getToken().getSubject(), null);
|
||||
RefreshableKeycloakSession session = new RefreshableKeycloakSession(oauth.getTokenString(), oauth.getToken(), oauth.getIdTokenString(), oauth.getIdToken(), resourceMetadata, realmConfig, oauth.getRefreshToken());
|
||||
KeycloakUndertowAccount account = new KeycloakUndertowAccount(principal, session, adapterConfig, resourceMetadata);
|
||||
securityContext.authenticationComplete(account, "KEYCLOAK", true);
|
||||
|
||||
// We cache account ourselves instead of using the Cache session handler of Undertow because
|
||||
// Undertow will return a 403 from an invalid account when calling IdentityManager.verify(Account) and
|
||||
// we want to just return NOT_ATTEMPTED so we can be redirected to relogin
|
||||
securityContext.authenticationComplete(account, "KEYCLOAK", false);
|
||||
login(exchange, account);
|
||||
}
|
||||
|
||||
@@ -104,12 +111,17 @@ public class KeycloakAuthenticationMechanism implements AuthenticationMechanism
|
||||
// complete
|
||||
}
|
||||
|
||||
protected void propagateKeycloakContext(HttpServerExchange exchange, KeycloakUndertowAccount account) {
|
||||
// complete
|
||||
}
|
||||
|
||||
protected void completeAuthentication(SecurityContext securityContext, BearerTokenAuthenticator bearer) {
|
||||
|
||||
protected void completeAuthentication(HttpServerExchange exchange, SecurityContext securityContext, BearerTokenAuthenticator bearer) {
|
||||
final KeycloakPrincipal principal = new KeycloakPrincipal(bearer.getToken().getSubject(), bearer.getSurrogate());
|
||||
RefreshableKeycloakSession session = new RefreshableKeycloakSession(bearer.getTokenString(), bearer.getToken(), null, null, resourceMetadata, realmConfig, null);
|
||||
KeycloakUndertowAccount account = new KeycloakUndertowAccount(principal, session, adapterConfig, resourceMetadata);
|
||||
securityContext.authenticationComplete(account, "KEYCLOAK", false);
|
||||
propagateKeycloakContext(exchange, account);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -120,4 +132,10 @@ public class KeycloakAuthenticationMechanism implements AuthenticationMechanism
|
||||
}
|
||||
return new ChallengeResult(false);
|
||||
}
|
||||
|
||||
protected KeycloakUndertowAccount checkCachedAccount(HttpServerExchange exchange) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+4
-11
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+18
-8
@@ -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
|
||||
@@ -92,10 +88,24 @@ public class KeycloakServletExtension implements ServletExtension {
|
||||
return theAuth;
|
||||
}
|
||||
}); // authentication
|
||||
deploymentInfo.addInnerHandlerChainWrapper(ServletPropagateSessionHandler.WRAPPER); // propagates SkeletonKeySession
|
||||
deploymentInfo.addInnerHandlerChainWrapper(actions); // handles authenticated actions and cors.
|
||||
|
||||
deploymentInfo.setIdentityManager(new KeycloakIdentityManager(keycloakConfig, realmConfiguration));
|
||||
deploymentInfo.setIdentityManager(new IdentityManager() {
|
||||
@Override
|
||||
public Account verify(Account account) {
|
||||
return account;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Account verify(String id, Credential credential) {
|
||||
throw new IllegalStateException("Should never be called in Keycloak flow");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Account verify(Credential credential) {
|
||||
throw new IllegalStateException("Should never be called in Keycloak flow");
|
||||
}
|
||||
});
|
||||
|
||||
log.info("Setting jsession cookie path to: " + deploymentInfo.getContextPath());
|
||||
ServletSessionConfig cookieConfig = new ServletSessionConfig();
|
||||
|
||||
+12
-2
@@ -69,10 +69,20 @@ 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());
|
||||
if (session.isActive()) return true;
|
||||
log.info("realmConfig notBefore: " + realmConfiguration.getNotBefore());
|
||||
if (session.isActive()) {
|
||||
log.info("session is active");
|
||||
return true;
|
||||
}
|
||||
|
||||
log.info("session is not active try refresh");
|
||||
session.refreshExpiredToken();
|
||||
if (!session.isActive()) return false;
|
||||
if (!session.isActive()) {
|
||||
log.info("session is not active return with failure");
|
||||
|
||||
return false;
|
||||
}
|
||||
log.info("refresh succeeded");
|
||||
|
||||
setRoles(session.getToken(), config, realmConfiguration.getMetadata());
|
||||
return true;
|
||||
|
||||
+20
-4
@@ -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;
|
||||
}
|
||||
|
||||
+34
-2
@@ -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;
|
||||
}
|
||||
}
|
||||
+32
-10
@@ -3,10 +3,8 @@ package org.keycloak.adapters.undertow;
|
||||
import io.undertow.server.HttpServerExchange;
|
||||
import io.undertow.servlet.api.ConfidentialPortManager;
|
||||
import io.undertow.servlet.handlers.ServletRequestContext;
|
||||
import org.keycloak.KeycloakAuthenticatedSession;
|
||||
import org.keycloak.KeycloakPrincipal;
|
||||
import org.keycloak.KeycloakSecurityContext;
|
||||
import org.keycloak.adapters.config.RealmConfiguration;
|
||||
import org.keycloak.adapters.ResourceMetadata;
|
||||
import org.keycloak.representations.adapters.config.AdapterConfig;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
@@ -26,24 +24,48 @@ public class ServletKeycloakAuthenticationMechanism extends KeycloakAuthenticati
|
||||
this.userSessionManagement = userSessionManagement;
|
||||
}
|
||||
|
||||
public ServletKeycloakAuthenticationMechanism(AdapterConfig config, ResourceMetadata metadata, ConfidentialPortManager portManager) {
|
||||
super(config, metadata);
|
||||
this.portManager = portManager;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected OAuthAuthenticator createOAuthAuthenticator(HttpServerExchange exchange) {
|
||||
return new ServletOAuthAuthenticator(exchange, realmConfig, portManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected KeycloakUndertowAccount checkCachedAccount(HttpServerExchange exchange) {
|
||||
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
|
||||
HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
|
||||
HttpSession session = req.getSession(false);
|
||||
if (session == null) {
|
||||
log.info("session was null, returning null");
|
||||
return null;
|
||||
}
|
||||
KeycloakUndertowAccount account = (KeycloakUndertowAccount)session.getAttribute(KeycloakUndertowAccount.class.getName());
|
||||
if (account == null) {
|
||||
log.info("Account was not in session, returning null");
|
||||
return null;
|
||||
}
|
||||
if (account.isActive(realmConfig, adapterConfig)) return account;
|
||||
log.info("Account was not active, returning null");
|
||||
session.setAttribute(KeycloakUndertowAccount.class.getName(), null);
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void propagateKeycloakContext(HttpServerExchange exchange, KeycloakUndertowAccount account) {
|
||||
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
|
||||
HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
|
||||
req.setAttribute(KeycloakSecurityContext.class.getName(), account.getSession());
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
protected void login(HttpServerExchange exchange, KeycloakUndertowAccount account) {
|
||||
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
|
||||
HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
|
||||
req.setAttribute(KeycloakSecurityContext.class.getName(), account.getSession());
|
||||
HttpSession session = req.getSession(true);
|
||||
session.setAttribute(KeycloakUndertowAccount.class.getName(), account);
|
||||
userSessionManagement.login(servletRequestContext.getDeployment().getSessionManager(), session, account.getPrincipal().getName());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-57
@@ -1,57 +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.jboss.logging.Logger;
|
||||
import org.keycloak.KeycloakAuthenticatedSession;
|
||||
|
||||
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 ServletPropagateSessionHandler implements HttpHandler {
|
||||
|
||||
private static final Logger log = Logger.getLogger(ServletPropagateSessionHandler.class);
|
||||
|
||||
protected HttpHandler next;
|
||||
|
||||
protected ServletPropagateSessionHandler(HttpHandler next) {
|
||||
this.next = next;
|
||||
}
|
||||
|
||||
public static final HandlerWrapper WRAPPER = new HandlerWrapper() {
|
||||
@Override
|
||||
public HttpHandler wrap(HttpHandler handler) {
|
||||
return new ServletPropagateSessionHandler(handler);
|
||||
}
|
||||
};
|
||||
|
||||
@Override
|
||||
public void handleRequest(HttpServerExchange exchange) throws Exception {
|
||||
log.debug("handleRequest");
|
||||
KeycloakUndertowAccount account = (KeycloakUndertowAccount)exchange.getSecurityContext().getAuthenticatedAccount();
|
||||
if (account == null) {
|
||||
log.debug("Not logged in, nothing to propagate");
|
||||
next.handleRequest(exchange);
|
||||
return;
|
||||
}
|
||||
|
||||
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
|
||||
HttpServletRequest req = (HttpServletRequest) servletRequestContext.getServletRequest();
|
||||
req.setAttribute(KeycloakAuthenticatedSession.class.getName(), account.getSession());
|
||||
|
||||
HttpSession session = req.getSession(false);
|
||||
if (session == null) {
|
||||
next.handleRequest(exchange);
|
||||
return;
|
||||
}
|
||||
log.debug("propagating to HTTP Session");
|
||||
session.setAttribute(KeycloakAuthenticatedSession.class.getName(), account.getSession());
|
||||
next.handleRequest(exchange);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+11
@@ -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();
|
||||
|
||||
+10
@@ -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;
|
||||
|
||||
@@ -40,6 +40,7 @@ public class AuthenticationManager {
|
||||
public static final String KEYCLOAK_REMEMBER_ME = "KEYCLOAK_REMEMBER_ME";
|
||||
|
||||
public AccessToken createIdentityToken(RealmModel realm, UserModel user) {
|
||||
logger.info("createIdentityToken");
|
||||
AccessToken token = new AccessToken();
|
||||
token.id(KeycloakModelUtils.generateId());
|
||||
token.issuedNow();
|
||||
@@ -52,6 +53,7 @@ public class AuthenticationManager {
|
||||
}
|
||||
|
||||
public NewCookie createLoginCookie(RealmModel realm, UserModel user, UriInfo uriInfo, boolean rememberMe) {
|
||||
logger.info("createLoginCookie");
|
||||
String cookieName = KEYCLOAK_IDENTITY_COOKIE;
|
||||
String cookiePath = getIdentityCookiePath(realm, uriInfo);
|
||||
return createLoginCookie(realm, user, null, cookieName, cookiePath, rememberMe);
|
||||
@@ -140,10 +142,17 @@ public class AuthenticationManager {
|
||||
try {
|
||||
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;
|
||||
if (checkActive) {
|
||||
logger.info("Checking if identity token is active");
|
||||
if (!token.isActive() || token.getIssuedAt() < realm.getNotBefore()) {
|
||||
logger.info("identity cookie expired");
|
||||
expireIdentityCookie(realm, uriInfo);
|
||||
return null;
|
||||
} else {
|
||||
logger.info("token.isActive() : " + token.isActive());
|
||||
logger.info("token.issuedAt: " + token.getIssuedAt());
|
||||
logger.info("real.notbefore: " + realm.getNotBefore());
|
||||
}
|
||||
}
|
||||
|
||||
UserModel user = realm.getUserById(token.getSubject());
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user