KEYCLOAK-1385 Introduce end-of-line normalization

This commit is contained in:
Stian Thorgersen committed 2015-07-17 13:46:51 +02:00
1 parent be8aa93cca
commit 1642ac2394
888 files changed
+110680 -110660

No files matched your search

+112 -112
View File
@@ -1,112 +1,112 @@
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>keycloak-parent</artifactId>
<groupId>org.keycloak</groupId>
<version>1.4.0.Final-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>keycloak-core</artifactId>
<name>Keycloak Core</name>
<packaging>jar</packaging>
<description/>
<properties>
<timestamp>${maven.build.timestamp}</timestamp>
<maven.build.timestamp.format>yyyy-MM-dd HH:mm</maven.build.timestamp.format>
<keycloak.osgi.export>
org.keycloak.*
</keycloak.osgi.export>
<keycloak.osgi.import>
net.iharder;version=${base64.version},
*;resolution:=optional
</keycloak.osgi.import>
</properties>
<dependencies>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.iharder</groupId>
<artifactId>base64</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<!-- Adding OSGI metadata to the JAR without changing the packaging type. -->
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<executions>
<execution>
<id>bundle-manifest</id>
<phase>process-classes</phase>
<goals>
<goal>manifest</goal>
</goals>
</execution>
</executions>
<configuration>
<instructions>
<Bundle-ClassPath>.</Bundle-ClassPath>
<Bundle-Name>${project.name}</Bundle-Name>
<Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
<Import-Package>${keycloak.osgi.import}</Import-Package>
<Export-Package>${keycloak.osgi.export}</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>keycloak-parent</artifactId>
<groupId>org.keycloak</groupId>
<version>1.4.0.Final-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>keycloak-core</artifactId>
<name>Keycloak Core</name>
<packaging>jar</packaging>
<description/>
<properties>
<timestamp>${maven.build.timestamp}</timestamp>
<maven.build.timestamp.format>yyyy-MM-dd HH:mm</maven.build.timestamp.format>
<keycloak.osgi.export>
org.keycloak.*
</keycloak.osgi.export>
<keycloak.osgi.import>
net.iharder;version=${base64.version},
*;resolution:=optional
</keycloak.osgi.import>
</properties>
<dependencies>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.iharder</groupId>
<artifactId>base64</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<!-- Adding OSGI metadata to the JAR without changing the packaging type. -->
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<executions>
<execution>
<id>bundle-manifest</id>
<phase>process-classes</phase>
<goals>
<goal>manifest</goal>
</goals>
</execution>
</executions>
<configuration>
<instructions>
<Bundle-ClassPath>.</Bundle-ClassPath>
<Bundle-Name>${project.name}</Bundle-Name>
<Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
<Import-Package>${keycloak.osgi.import}</Import-Package>
<Export-Package>${keycloak.osgi.export}</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -1,111 +1,111 @@
package org.keycloak;
import org.keycloak.enums.RelativeUrlsUsed;
import org.keycloak.util.KeycloakUriBuilder;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class AbstractOAuthClient {
private static final String OAUTH_TOKEN_REQUEST_STATE = "OAuth_Token_Request_State";
private final AtomicLong counter = new AtomicLong();
protected String clientId;
protected Map<String, String> credentials;
protected String authUrl;
protected String tokenUrl;
protected RelativeUrlsUsed relativeUrlsUsed;
protected String scope;
protected String stateCookieName = OAUTH_TOKEN_REQUEST_STATE;
protected String stateCookiePath;
protected boolean isSecure;
protected boolean publicClient;
protected String getStateCode() {
return counter.getAndIncrement() + "/" + UUID.randomUUID().toString();
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public Map<String, String> getCredentials() {
return credentials;
}
public void setCredentials(Map<String, String> credentials) {
this.credentials = credentials;
}
public String getAuthUrl() {
return authUrl;
}
public void setAuthUrl(String authUrl) {
this.authUrl = authUrl;
}
public String getTokenUrl() {
return tokenUrl;
}
public void setTokenUrl(String tokenUrl) {
this.tokenUrl = tokenUrl;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getStateCookieName() {
return stateCookieName;
}
public void setStateCookieName(String stateCookieName) {
this.stateCookieName = stateCookieName;
}
public String getStateCookiePath() {
return stateCookiePath;
}
public void setStateCookiePath(String stateCookiePath) {
this.stateCookiePath = stateCookiePath;
}
public boolean isPublicClient() {
return publicClient;
}
public void setPublicClient(boolean publicClient) {
this.publicClient = publicClient;
}
public RelativeUrlsUsed getRelativeUrlsUsed() {
return relativeUrlsUsed;
}
public void setRelativeUrlsUsed(RelativeUrlsUsed relativeUrlsUsed) {
this.relativeUrlsUsed = relativeUrlsUsed;
}
protected String stripOauthParametersFromRedirect(String uri) {
KeycloakUriBuilder builder = KeycloakUriBuilder.fromUri(uri)
.replaceQueryParam(OAuth2Constants.CODE, null)
.replaceQueryParam(OAuth2Constants.STATE, null);
return builder.build().toString();
}
}
package org.keycloak;
import org.keycloak.enums.RelativeUrlsUsed;
import org.keycloak.util.KeycloakUriBuilder;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class AbstractOAuthClient {
private static final String OAUTH_TOKEN_REQUEST_STATE = "OAuth_Token_Request_State";
private final AtomicLong counter = new AtomicLong();
protected String clientId;
protected Map<String, String> credentials;
protected String authUrl;
protected String tokenUrl;
protected RelativeUrlsUsed relativeUrlsUsed;
protected String scope;
protected String stateCookieName = OAUTH_TOKEN_REQUEST_STATE;
protected String stateCookiePath;
protected boolean isSecure;
protected boolean publicClient;
protected String getStateCode() {
return counter.getAndIncrement() + "/" + UUID.randomUUID().toString();
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public Map<String, String> getCredentials() {
return credentials;
}
public void setCredentials(Map<String, String> credentials) {
this.credentials = credentials;
}
public String getAuthUrl() {
return authUrl;
}
public void setAuthUrl(String authUrl) {
this.authUrl = authUrl;
}
public String getTokenUrl() {
return tokenUrl;
}
public void setTokenUrl(String tokenUrl) {
this.tokenUrl = tokenUrl;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getStateCookieName() {
return stateCookieName;
}
public void setStateCookieName(String stateCookieName) {
this.stateCookieName = stateCookieName;
}
public String getStateCookiePath() {
return stateCookiePath;
}
public void setStateCookiePath(String stateCookiePath) {
this.stateCookiePath = stateCookiePath;
}
public boolean isPublicClient() {
return publicClient;
}
public void setPublicClient(boolean publicClient) {
this.publicClient = publicClient;
}
public RelativeUrlsUsed getRelativeUrlsUsed() {
return relativeUrlsUsed;
}
public void setRelativeUrlsUsed(RelativeUrlsUsed relativeUrlsUsed) {
this.relativeUrlsUsed = relativeUrlsUsed;
}
protected String stripOauthParametersFromRedirect(String uri) {
KeycloakUriBuilder builder = KeycloakUriBuilder.fromUri(uri)
.replaceQueryParam(OAuth2Constants.CODE, null)
.replaceQueryParam(OAuth2Constants.STATE, null);
return builder.build().toString();
}
}
@@ -1,13 +1,13 @@
package org.keycloak;
/**
* Information about the client connection
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface ClientConnection {
String getRemoteAddr();
String getRemoteHost();
int getReportPort();
}
package org.keycloak;
/**
* Information about the client connection
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface ClientConnection {
String getRemoteAddr();
String getRemoteHost();
int getReportPort();
}
+163 -163
View File
@@ -1,163 +1,163 @@
package org.keycloak;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class Config {
private static ConfigProvider configProvider = new SystemPropertiesConfigProvider();
public static void init(ConfigProvider configProvider) {
Config.configProvider = configProvider;
}
public static String getAdminRealm() {
return configProvider.scope("admin").get("realm", "master");
}
public static String getProvider(String spi) {
String provider = configProvider.getProvider(spi);
if (provider == null || provider.trim().equals("")) {
return null;
} else {
return provider;
}
}
public static Scope scope(String... scope) {
return configProvider.scope(scope);
}
public static interface ConfigProvider {
String getProvider(String spi);
Scope scope(String... scope);
}
public static class SystemPropertiesConfigProvider implements ConfigProvider {
@Override
public String getProvider(String spi) {
return System.getProperties().getProperty("keycloak." + spi + ".provider");
}
@Override
public Scope scope(String... scope) {
StringBuilder sb = new StringBuilder();
sb.append("keycloak.");
for (String s : scope) {
sb.append(s);
sb.append(".");
}
return new SystemPropertiesScope(sb.toString());
}
}
public static class SystemPropertiesScope implements Scope {
private String prefix;
public SystemPropertiesScope(String prefix) {
this.prefix = prefix;
}
@Override
public String get(String key) {
return get(key, null);
}
@Override
public String get(String key, String defaultValue) {
return System.getProperty(prefix + key, defaultValue);
}
@Override
public String[] getArray(String key) {
String value = get(key);
if (value != null) {
String[] a = value.split(",");
for (int i = 0; i < a.length; i++) {
a[i] = a[i].trim();
}
return a;
} else {
return null;
}
}
@Override
public Integer getInt(String key) {
return getInt(key, null);
}
@Override
public Integer getInt(String key, Integer defaultValue) {
String v = get(key, null);
return v != null ? Integer.parseInt(v) : defaultValue;
}
@Override
public Long getLong(String key) {
return getLong(key, null);
}
@Override
public Long getLong(String key, Long defaultValue) {
String v = get(key, null);
return v != null ? Long.parseLong(v) : defaultValue;
}
@Override
public Boolean getBoolean(String key) {
return getBoolean(key, null);
}
@Override
public Boolean getBoolean(String key, Boolean defaultValue) {
String v = get(key, null);
return v != null ? Boolean.parseBoolean(v) : defaultValue;
}
@Override
public Scope scope(String... scope) {
StringBuilder sb = new StringBuilder();
sb.append(prefix + ".");
for (String s : scope) {
sb.append(s);
sb.append(".");
}
return new SystemPropertiesScope(sb.toString());
}
}
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public static interface Scope {
String get(String key);
String get(String key, String defaultValue);
String[] getArray(String key);
Integer getInt(String key);
Integer getInt(String key, Integer defaultValue);
Long getLong(String key);
Long getLong(String key, Long defaultValue);
Boolean getBoolean(String key);
Boolean getBoolean(String key, Boolean defaultValue);
Scope scope(String... scope);
}
}
package org.keycloak;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class Config {
private static ConfigProvider configProvider = new SystemPropertiesConfigProvider();
public static void init(ConfigProvider configProvider) {
Config.configProvider = configProvider;
}
public static String getAdminRealm() {
return configProvider.scope("admin").get("realm", "master");
}
public static String getProvider(String spi) {
String provider = configProvider.getProvider(spi);
if (provider == null || provider.trim().equals("")) {
return null;
} else {
return provider;
}
}
public static Scope scope(String... scope) {
return configProvider.scope(scope);
}
public static interface ConfigProvider {
String getProvider(String spi);
Scope scope(String... scope);
}
public static class SystemPropertiesConfigProvider implements ConfigProvider {
@Override
public String getProvider(String spi) {
return System.getProperties().getProperty("keycloak." + spi + ".provider");
}
@Override
public Scope scope(String... scope) {
StringBuilder sb = new StringBuilder();
sb.append("keycloak.");
for (String s : scope) {
sb.append(s);
sb.append(".");
}
return new SystemPropertiesScope(sb.toString());
}
}
public static class SystemPropertiesScope implements Scope {
private String prefix;
public SystemPropertiesScope(String prefix) {
this.prefix = prefix;
}
@Override
public String get(String key) {
return get(key, null);
}
@Override
public String get(String key, String defaultValue) {
return System.getProperty(prefix + key, defaultValue);
}
@Override
public String[] getArray(String key) {
String value = get(key);
if (value != null) {
String[] a = value.split(",");
for (int i = 0; i < a.length; i++) {
a[i] = a[i].trim();
}
return a;
} else {
return null;
}
}
@Override
public Integer getInt(String key) {
return getInt(key, null);
}
@Override
public Integer getInt(String key, Integer defaultValue) {
String v = get(key, null);
return v != null ? Integer.parseInt(v) : defaultValue;
}
@Override
public Long getLong(String key) {
return getLong(key, null);
}
@Override
public Long getLong(String key, Long defaultValue) {
String v = get(key, null);
return v != null ? Long.parseLong(v) : defaultValue;
}
@Override
public Boolean getBoolean(String key) {
return getBoolean(key, null);
}
@Override
public Boolean getBoolean(String key, Boolean defaultValue) {
String v = get(key, null);
return v != null ? Boolean.parseBoolean(v) : defaultValue;
}
@Override
public Scope scope(String... scope) {
StringBuilder sb = new StringBuilder();
sb.append(prefix + ".");
for (String s : scope) {
sb.append(s);
sb.append(".");
}
return new SystemPropertiesScope(sb.toString());
}
}
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public static interface Scope {
String get(String key);
String get(String key, String defaultValue);
String[] getArray(String key);
Integer getInt(String key);
Integer getInt(String key, Integer defaultValue);
Long getLong(String key);
Long getLong(String key, Long defaultValue);
Boolean getBoolean(String key);
Boolean getBoolean(String key, Boolean defaultValue);
Scope scope(String... scope);
}
}
@@ -1,49 +1,49 @@
package org.keycloak;
import java.io.Serializable;
import java.security.Principal;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class KeycloakPrincipal<T extends KeycloakSecurityContext> implements Principal, Serializable {
protected final String name;
protected final T context;
public KeycloakPrincipal(String name, T context) {
this.name = name;
this.context = context;
}
public T getKeycloakSecurityContext() {
return context;
}
@Override
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
KeycloakPrincipal that = (KeycloakPrincipal) o;
if (!name.equals(that.name)) return false;
return true;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return name;
}
}
package org.keycloak;
import java.io.Serializable;
import java.security.Principal;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class KeycloakPrincipal<T extends KeycloakSecurityContext> implements Principal, Serializable {
protected final String name;
protected final T context;
public KeycloakPrincipal(String name, T context) {
this.name = name;
this.context = context;
}
public T getKeycloakSecurityContext() {
return context;
}
@Override
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
KeycloakPrincipal that = (KeycloakPrincipal) o;
if (!name.equals(that.name)) return false;
return true;
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return name;
}
}
@@ -1,82 +1,82 @@
package org.keycloak;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.IDToken;
import org.keycloak.util.Base64Url;
import org.keycloak.util.JsonSerialization;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class KeycloakSecurityContext implements Serializable {
protected String tokenString;
protected String idTokenString;
// Don't store parsed tokens into HTTP session
protected transient AccessToken token;
protected transient IDToken idToken;
public KeycloakSecurityContext() {
}
public KeycloakSecurityContext(String tokenString, AccessToken token, String idTokenString, IDToken idToken) {
this.tokenString = tokenString;
this.token = token;
this.idToken = idToken;
this.idTokenString = idTokenString;
}
public AccessToken getToken() {
return token;
}
public String getTokenString() {
return tokenString;
}
public IDToken getIdToken() {
return idToken;
}
public String getIdTokenString() {
return idTokenString;
}
public String getRealm() {
// Assumption that issuer contains realm name
return token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1);
}
// SERIALIZATION
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
token = parseToken(tokenString, AccessToken.class);
idToken = parseToken(idTokenString, IDToken.class);
}
// Just decode token without any verifications
private <T> T parseToken(String encoded, Class<T> clazz) throws IOException {
if (encoded == null)
return null;
String[] parts = encoded.split("\\.");
if (parts.length < 2 || parts.length > 3) throw new IllegalArgumentException("Parsing error");
byte[] bytes = Base64Url.decode(parts[1]);
return JsonSerialization.readValue(bytes, clazz);
}
}
package org.keycloak;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.IDToken;
import org.keycloak.util.Base64Url;
import org.keycloak.util.JsonSerialization;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class KeycloakSecurityContext implements Serializable {
protected String tokenString;
protected String idTokenString;
// Don't store parsed tokens into HTTP session
protected transient AccessToken token;
protected transient IDToken idToken;
public KeycloakSecurityContext() {
}
public KeycloakSecurityContext(String tokenString, AccessToken token, String idTokenString, IDToken idToken) {
this.tokenString = tokenString;
this.token = token;
this.idToken = idToken;
this.idTokenString = idTokenString;
}
public AccessToken getToken() {
return token;
}
public String getTokenString() {
return tokenString;
}
public IDToken getIdToken() {
return idToken;
}
public String getIdTokenString() {
return idTokenString;
}
public String getRealm() {
// Assumption that issuer contains realm name
return token.getIssuer().substring(token.getIssuer().lastIndexOf('/') + 1);
}
// SERIALIZATION
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
token = parseToken(tokenString, AccessToken.class);
idToken = parseToken(idTokenString, IDToken.class);
}
// Just decode token without any verifications
private <T> T parseToken(String encoded, Class<T> clazz) throws IOException {
if (encoded == null)
return null;
String[] parts = encoded.split("\\.");
if (parts.length < 2 || parts.length > 3) throw new IllegalArgumentException("Parsing error");
byte[] bytes = Base64Url.decode(parts[1]);
return JsonSerialization.readValue(bytes, clazz);
}
}
@@ -1,64 +1,64 @@
package org.keycloak;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class OAuthErrorException extends Exception {
public static final String INVALID_REQUEST = "invalid_request";
public static final String INVALID_CLIENT = "invalid_client";
public static final String INVALID_GRANT = "invalid_grant";
public static final String INVALID_SCOPE = "invalid_grant";
public static final String UNAUTHORIZED_CLIENT = "unauthorized_client";
public static final String UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type";
public OAuthErrorException(String error, String description, String message, Throwable cause) {
super(message, cause);
this.error = error;
this.description = description;
}
public OAuthErrorException(String error, String description, String message) {
super(message);
this.error = error;
this.description = description;
}
public OAuthErrorException(String error, String description) {
super(description);
this.error = error;
this.description = description;
}
public OAuthErrorException(String error, String description, Throwable cause) {
super(description, cause);
this.error = error;
this.description = description;
}
public OAuthErrorException(String error) {
super(error);
this.error = error;
}
public OAuthErrorException(String error, Throwable cause) {
super(error, cause);
this.error = error;
}
protected String error;
protected String description;
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
package org.keycloak;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class OAuthErrorException extends Exception {
public static final String INVALID_REQUEST = "invalid_request";
public static final String INVALID_CLIENT = "invalid_client";
public static final String INVALID_GRANT = "invalid_grant";
public static final String INVALID_SCOPE = "invalid_grant";
public static final String UNAUTHORIZED_CLIENT = "unauthorized_client";
public static final String UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type";
public OAuthErrorException(String error, String description, String message, Throwable cause) {
super(message, cause);
this.error = error;
this.description = description;
}
public OAuthErrorException(String error, String description, String message) {
super(message);
this.error = error;
this.description = description;
}
public OAuthErrorException(String error, String description) {
super(description);
this.error = error;
this.description = description;
}
public OAuthErrorException(String error, String description, Throwable cause) {
super(description, cause);
this.error = error;
this.description = description;
}
public OAuthErrorException(String error) {
super(error);
this.error = error;
}
public OAuthErrorException(String error, Throwable cause) {
super(error, cause);
this.error = error;
}
protected String error;
protected String description;
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
@@ -1,59 +1,59 @@
package org.keycloak;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.representations.AccessToken;
import java.io.IOException;
import java.security.PublicKey;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class RSATokenVerifier {
public static AccessToken verifyToken(String tokenString, PublicKey realmKey, String realmUrl) throws VerificationException {
return verifyToken(tokenString, realmKey, realmUrl, true);
}
public static AccessToken verifyToken(String tokenString, PublicKey realmKey, String realmUrl, boolean checkActive) throws VerificationException {
JWSInput input = null;
try {
input = new JWSInput(tokenString);
} catch (Exception e) {
throw new VerificationException("Couldn't parse token", e);
}
if (!isPublicKeyValid(input, realmKey)) throw new VerificationException("Invalid token signature.");
AccessToken token;
try {
token = input.readJsonContent(AccessToken.class);
} catch (IOException e) {
throw new VerificationException("Couldn't parse token signature", e);
}
String user = token.getSubject();
if (user == null) {
throw new VerificationException("Token user was null.");
}
if (realmUrl == null) {
throw new VerificationException("Realm URL is null. Make sure to add auth-server-url to the configuration of your adapter!");
}
if (!realmUrl.equals(token.getIssuer())) {
throw new VerificationException("Token audience doesn't match domain. Token issuer is " + token.getIssuer() + ", but URL from configuration is " + realmUrl);
}
if (checkActive && !token.isActive()) {
throw new VerificationException("Token is not active.");
}
return token;
}
private static boolean isPublicKeyValid(JWSInput input, PublicKey realmKey) throws VerificationException {
try {
return RSAProvider.verify(input, realmKey);
} catch (Exception e) {
throw new VerificationException("Token signature not validated.", e);
}
}
}
package org.keycloak;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.representations.AccessToken;
import java.io.IOException;
import java.security.PublicKey;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class RSATokenVerifier {
public static AccessToken verifyToken(String tokenString, PublicKey realmKey, String realmUrl) throws VerificationException {
return verifyToken(tokenString, realmKey, realmUrl, true);
}
public static AccessToken verifyToken(String tokenString, PublicKey realmKey, String realmUrl, boolean checkActive) throws VerificationException {
JWSInput input = null;
try {
input = new JWSInput(tokenString);
} catch (Exception e) {
throw new VerificationException("Couldn't parse token", e);
}
if (!isPublicKeyValid(input, realmKey)) throw new VerificationException("Invalid token signature.");
AccessToken token;
try {
token = input.readJsonContent(AccessToken.class);
} catch (IOException e) {
throw new VerificationException("Couldn't parse token signature", e);
}
String user = token.getSubject();
if (user == null) {
throw new VerificationException("Token user was null.");
}
if (realmUrl == null) {
throw new VerificationException("Realm URL is null. Make sure to add auth-server-url to the configuration of your adapter!");
}
if (!realmUrl.equals(token.getIssuer())) {
throw new VerificationException("Token audience doesn't match domain. Token issuer is " + token.getIssuer() + ", but URL from configuration is " + realmUrl);
}
if (checkActive && !token.isActive()) {
throw new VerificationException("Token is not active.");
}
return token;
}
private static boolean isPublicKeyValid(JWSInput input, PublicKey realmKey) throws VerificationException {
try {
return RSAProvider.verify(input, realmKey);
} catch (Exception e) {
throw new VerificationException("Token signature not validated.", e);
}
}
}
@@ -1,16 +1,16 @@
package org.keycloak;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class TokenIdGenerator {
private static final AtomicLong counter = new AtomicLong();
public static String generateId() {
return UUID.randomUUID().toString() + "-" + System.currentTimeMillis();
}
}
package org.keycloak;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class TokenIdGenerator {
private static final AtomicLong counter = new AtomicLong();
public static String generateId() {
return UUID.randomUUID().toString() + "-" + System.currentTimeMillis();
}
}
+48 -48
View File
@@ -1,48 +1,48 @@
package org.keycloak;
import org.codehaus.jackson.annotate.JsonProperty;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class Version {
public static String VERSION;
public static String RESOURCES_VERSION;
public static String BUILD_TIME;
public static final String UNKNOWN = "UNKNOWN";
public static final Version SINGLETON;
private final String version = VERSION;
private final String buildTime = BUILD_TIME;
static {
Properties props = new Properties();
InputStream is = Version.class.getResourceAsStream("/keycloak-version.properties");
try {
props.load(is);
VERSION = props.getProperty("version");
BUILD_TIME = props.getProperty("build-time");
RESOURCES_VERSION = VERSION.toLowerCase();
} catch (IOException e) {
VERSION=UNKNOWN;
BUILD_TIME=UNKNOWN;
}
SINGLETON = new Version();
}
@JsonProperty("version")
public String getVersion() {
return version;
}
@JsonProperty("build-time")
public String getBuildTime() {
return buildTime;
}
}
package org.keycloak;
import org.codehaus.jackson.annotate.JsonProperty;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class Version {
public static String VERSION;
public static String RESOURCES_VERSION;
public static String BUILD_TIME;
public static final String UNKNOWN = "UNKNOWN";
public static final Version SINGLETON;
private final String version = VERSION;
private final String buildTime = BUILD_TIME;
static {
Properties props = new Properties();
InputStream is = Version.class.getResourceAsStream("/keycloak-version.properties");
try {
props.load(is);
VERSION = props.getProperty("version");
BUILD_TIME = props.getProperty("build-time");
RESOURCES_VERSION = VERSION.toLowerCase();
} catch (IOException e) {
VERSION=UNKNOWN;
BUILD_TIME=UNKNOWN;
}
SINGLETON = new Version();
}
@JsonProperty("version")
public String getVersion() {
return version;
}
@JsonProperty("build-time")
public String getBuildTime() {
return buildTime;
}
}
@@ -1,35 +1,35 @@
package org.keycloak.constants;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface AdapterConstants {
// URL endpoints
public static final String K_LOGOUT = "k_logout";
public static final String K_VERSION = "k_version";
public static final String K_PUSH_NOT_BEFORE = "k_push_not_before";
public static final String K_TEST_AVAILABLE = "k_test_available";
public static final String K_QUERY_BEARER_TOKEN = "k_query_bearer_token";
// This param name is defined again in Keycloak Subsystem class
// org.keycloak.subsystem.extensionKeycloakAdapterConfigDeploymentProcessor. We have this value in
// two places to avoid dependency between Keycloak Subsystem and Keyclaok Undertow Integration.
String AUTH_DATA_PARAM_NAME = "org.keycloak.json.adapterConfig";
// Attribute passed in codeToToken request from adapter to Keycloak and saved in ClientSession. Contains ID of HttpSession on adapter
public static final String CLIENT_SESSION_STATE = "client_session_state";
// Attribute passed in codeToToken request from adapter to Keycloak and saved in ClientSession. Contains hostname of adapter where HttpSession is served
public static final String CLIENT_SESSION_HOST = "client_session_host";
// Attribute passed in registerNode request for register new application cluster node once he joined cluster
public static final String CLIENT_CLUSTER_HOST = "client_cluster_host";
// Cookie used on adapter side to store token info. Used only when tokenStore is 'COOKIE'
public static final String KEYCLOAK_ADAPTER_STATE_COOKIE = "KEYCLOAK_ADAPTER_STATE";
// Request parameter used to specify the identifier of the identity provider that should be used to authenticate an user
String KC_IDP_HINT = "kc_idp_hint";
}
package org.keycloak.constants;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface AdapterConstants {
// URL endpoints
public static final String K_LOGOUT = "k_logout";
public static final String K_VERSION = "k_version";
public static final String K_PUSH_NOT_BEFORE = "k_push_not_before";
public static final String K_TEST_AVAILABLE = "k_test_available";
public static final String K_QUERY_BEARER_TOKEN = "k_query_bearer_token";
// This param name is defined again in Keycloak Subsystem class
// org.keycloak.subsystem.extensionKeycloakAdapterConfigDeploymentProcessor. We have this value in
// two places to avoid dependency between Keycloak Subsystem and Keyclaok Undertow Integration.
String AUTH_DATA_PARAM_NAME = "org.keycloak.json.adapterConfig";
// Attribute passed in codeToToken request from adapter to Keycloak and saved in ClientSession. Contains ID of HttpSession on adapter
public static final String CLIENT_SESSION_STATE = "client_session_state";
// Attribute passed in codeToToken request from adapter to Keycloak and saved in ClientSession. Contains hostname of adapter where HttpSession is served
public static final String CLIENT_SESSION_HOST = "client_session_host";
// Attribute passed in registerNode request for register new application cluster node once he joined cluster
public static final String CLIENT_CLUSTER_HOST = "client_cluster_host";
// Cookie used on adapter side to store token info. Used only when tokenStore is 'COOKIE'
public static final String KEYCLOAK_ADAPTER_STATE_COOKIE = "KEYCLOAK_ADAPTER_STATE";
// Request parameter used to specify the identifier of the identity provider that should be used to authenticate an user
String KC_IDP_HINT = "kc_idp_hint";
}
@@ -1,17 +1,17 @@
package org.keycloak.constants;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface ServiceUrlConstants {
public static final String AUTH_PATH = "/realms/{realm-name}/protocol/openid-connect/auth";
public static final String TOKEN_PATH = "/realms/{realm-name}/protocol/openid-connect/token";
public static final String TOKEN_SERVICE_LOGOUT_PATH = "/realms/{realm-name}/protocol/openid-connect/logout";
public static final String ACCOUNT_SERVICE_PATH = "/realms/{realm-name}/account";
public static final String REALM_INFO_PATH = "/realms/{realm-name}";
public static final String CLIENTS_MANAGEMENT_REGISTER_NODE_PATH = "/realms/{realm-name}/clients-managements/register-node";
public static final String CLIENTS_MANAGEMENT_UNREGISTER_NODE_PATH = "/realms/{realm-name}/clients-managements/unregister-node";
}
package org.keycloak.constants;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface ServiceUrlConstants {
public static final String AUTH_PATH = "/realms/{realm-name}/protocol/openid-connect/auth";
public static final String TOKEN_PATH = "/realms/{realm-name}/protocol/openid-connect/token";
public static final String TOKEN_SERVICE_LOGOUT_PATH = "/realms/{realm-name}/protocol/openid-connect/logout";
public static final String ACCOUNT_SERVICE_PATH = "/realms/{realm-name}/account";
public static final String REALM_INFO_PATH = "/realms/{realm-name}";
public static final String CLIENTS_MANAGEMENT_REGISTER_NODE_PATH = "/realms/{realm-name}/clients-managements/register-node";
public static final String CLIENTS_MANAGEMENT_UNREGISTER_NODE_PATH = "/realms/{realm-name}/clients-managements/unregister-node";
}
@@ -1,32 +1,32 @@
package org.keycloak.jose.jws;
import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.jose.jws.crypto.SignatureProvider;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public enum Algorithm {
none(null),
HS256(null),
HS384(null),
HS512(null),
RS256(new RSAProvider()),
RS384(new RSAProvider()),
RS512(new RSAProvider()),
ES256(null),
ES384(null),
ES512(null)
;
private SignatureProvider provider;
Algorithm(SignatureProvider provider) {
this.provider = provider;
}
public SignatureProvider getProvider() {
return provider;
}
}
package org.keycloak.jose.jws;
import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.jose.jws.crypto.SignatureProvider;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public enum Algorithm {
none(null),
HS256(null),
HS384(null),
HS512(null),
RS256(new RSAProvider()),
RS384(new RSAProvider()),
RS512(new RSAProvider()),
ES256(null),
ES384(null),
ES512(null)
;
private SignatureProvider provider;
Algorithm(SignatureProvider provider) {
this.provider = provider;
}
public SignatureProvider getProvider() {
return provider;
}
}
@@ -1,205 +1,205 @@
package org.keycloak.jose.jws;
import org.keycloak.jose.jws.crypto.HMACProvider;
import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.util.Base64Url;
import org.keycloak.util.JsonSerialization;
import javax.crypto.SecretKey;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class JWSBuilder {
String type;
String contentType;
byte[] contentBytes;
public JWSBuilder type(String type) {
this.type = type;
return this;
}
public JWSBuilder contentType(String type) {
this.contentType = type;
return this;
}
public EncodingBuilder content(byte[] bytes) {
this.contentBytes = bytes;
return new EncodingBuilder();
}
public EncodingBuilder jsonContent(Object object) {
try {
this.contentBytes = JsonSerialization.writeValueAsBytes(object);
} catch (IOException e) {
throw new RuntimeException(e);
}
return new EncodingBuilder();
}
protected String encodeHeader(Algorithm alg) {
StringBuilder builder = new StringBuilder("{");
builder.append("\"alg\":\"").append(alg.toString()).append("\"");
if (type != null) builder.append(",\"typ\" : \"").append(type).append("\"");
if (contentType != null) builder.append(",\"cty\":\"").append(contentType).append("\"");
builder.append("}");
try {
return Base64Url.encode(builder.toString().getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
protected String encodeAll(StringBuffer encoding, byte[] signature) {
encoding.append('.');
if (signature != null) {
encoding.append(Base64Url.encode(signature));
}
return encoding.toString();
}
protected void encode(Algorithm alg, byte[] data, StringBuffer encoding) {
encoding.append(encodeHeader(alg));
encoding.append('.');
encoding.append(Base64Url.encode(data));
}
protected byte[] marshalContent() {
return contentBytes;
}
public class EncodingBuilder {
public String none() {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.none, data, buffer);
return encodeAll(buffer, null);
}
public String rsa256(PrivateKey privateKey) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.RS256, data, buffer);
byte[] signature = null;
try {
signature = RSAProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.RS256, privateKey);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String rsa384(PrivateKey privateKey) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.RS384, data, buffer);
byte[] signature = null;
try {
signature = RSAProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.RS384, privateKey);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String rsa512(PrivateKey privateKey) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.RS512, data, buffer);
byte[] signature = null;
try {
signature = RSAProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.RS512, privateKey);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String hmac256(byte[] sharedSecret) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.HS256, data, buffer);
byte[] signature = null;
try {
signature = HMACProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.HS256, sharedSecret);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String hmac384(byte[] sharedSecret) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.HS384, data, buffer);
byte[] signature = null;
try {
signature = HMACProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.HS384, sharedSecret);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String hmac512(byte[] sharedSecret) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.HS512, data, buffer);
byte[] signature = null;
try {
signature = HMACProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.HS512, sharedSecret);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String hmac256(SecretKey sharedSecret) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.HS256, data, buffer);
byte[] signature = null;
try {
signature = HMACProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.HS256, sharedSecret);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String hmac384(SecretKey sharedSecret) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.HS384, data, buffer);
byte[] signature = null;
try {
signature = HMACProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.HS384, sharedSecret);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String hmac512(SecretKey sharedSecret) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.HS512, data, buffer);
byte[] signature = null;
try {
signature = HMACProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.HS512, sharedSecret);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
}
}
package org.keycloak.jose.jws;
import org.keycloak.jose.jws.crypto.HMACProvider;
import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.util.Base64Url;
import org.keycloak.util.JsonSerialization;
import javax.crypto.SecretKey;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class JWSBuilder {
String type;
String contentType;
byte[] contentBytes;
public JWSBuilder type(String type) {
this.type = type;
return this;
}
public JWSBuilder contentType(String type) {
this.contentType = type;
return this;
}
public EncodingBuilder content(byte[] bytes) {
this.contentBytes = bytes;
return new EncodingBuilder();
}
public EncodingBuilder jsonContent(Object object) {
try {
this.contentBytes = JsonSerialization.writeValueAsBytes(object);
} catch (IOException e) {
throw new RuntimeException(e);
}
return new EncodingBuilder();
}
protected String encodeHeader(Algorithm alg) {
StringBuilder builder = new StringBuilder("{");
builder.append("\"alg\":\"").append(alg.toString()).append("\"");
if (type != null) builder.append(",\"typ\" : \"").append(type).append("\"");
if (contentType != null) builder.append(",\"cty\":\"").append(contentType).append("\"");
builder.append("}");
try {
return Base64Url.encode(builder.toString().getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
protected String encodeAll(StringBuffer encoding, byte[] signature) {
encoding.append('.');
if (signature != null) {
encoding.append(Base64Url.encode(signature));
}
return encoding.toString();
}
protected void encode(Algorithm alg, byte[] data, StringBuffer encoding) {
encoding.append(encodeHeader(alg));
encoding.append('.');
encoding.append(Base64Url.encode(data));
}
protected byte[] marshalContent() {
return contentBytes;
}
public class EncodingBuilder {
public String none() {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.none, data, buffer);
return encodeAll(buffer, null);
}
public String rsa256(PrivateKey privateKey) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.RS256, data, buffer);
byte[] signature = null;
try {
signature = RSAProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.RS256, privateKey);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String rsa384(PrivateKey privateKey) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.RS384, data, buffer);
byte[] signature = null;
try {
signature = RSAProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.RS384, privateKey);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String rsa512(PrivateKey privateKey) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.RS512, data, buffer);
byte[] signature = null;
try {
signature = RSAProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.RS512, privateKey);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String hmac256(byte[] sharedSecret) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.HS256, data, buffer);
byte[] signature = null;
try {
signature = HMACProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.HS256, sharedSecret);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String hmac384(byte[] sharedSecret) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.HS384, data, buffer);
byte[] signature = null;
try {
signature = HMACProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.HS384, sharedSecret);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String hmac512(byte[] sharedSecret) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.HS512, data, buffer);
byte[] signature = null;
try {
signature = HMACProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.HS512, sharedSecret);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String hmac256(SecretKey sharedSecret) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.HS256, data, buffer);
byte[] signature = null;
try {
signature = HMACProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.HS256, sharedSecret);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String hmac384(SecretKey sharedSecret) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.HS384, data, buffer);
byte[] signature = null;
try {
signature = HMACProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.HS384, sharedSecret);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
public String hmac512(SecretKey sharedSecret) {
StringBuffer buffer = new StringBuffer();
byte[] data = marshalContent();
encode(Algorithm.HS512, data, buffer);
byte[] signature = null;
try {
signature = HMACProvider.sign(buffer.toString().getBytes("UTF-8"), Algorithm.HS512, sharedSecret);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return encodeAll(buffer, signature);
}
}
}
@@ -1,69 +1,69 @@
package org.keycloak.jose.jws;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import java.io.IOException;
import java.io.Serializable;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class JWSHeader implements Serializable {
@JsonProperty("alg")
private Algorithm algorithm;
@JsonProperty("typ")
private String type;
@JsonProperty("cty")
private String contentType;
@JsonProperty("kid")
private String keyId;
public JWSHeader() {
}
public JWSHeader(Algorithm algorithm, String type, String contentType) {
this.algorithm = algorithm;
this.type = type;
this.contentType = contentType;
}
public Algorithm getAlgorithm() {
return algorithm;
}
public String getType() {
return type;
}
public String getContentType() {
return contentType;
}
public String getKeyId() {
return keyId;
}
private static final ObjectMapper mapper = new ObjectMapper();
static {
mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
}
public String toString() {
try {
return mapper.writeValueAsString(this);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
package org.keycloak.jose.jws;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import java.io.IOException;
import java.io.Serializable;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class JWSHeader implements Serializable {
@JsonProperty("alg")
private Algorithm algorithm;
@JsonProperty("typ")
private String type;
@JsonProperty("cty")
private String contentType;
@JsonProperty("kid")
private String keyId;
public JWSHeader() {
}
public JWSHeader(Algorithm algorithm, String type, String contentType) {
this.algorithm = algorithm;
this.type = type;
this.contentType = contentType;
}
public Algorithm getAlgorithm() {
return algorithm;
}
public String getType() {
return type;
}
public String getContentType() {
return contentType;
}
public String getKeyId() {
return keyId;
}
private static final ObjectMapper mapper = new ObjectMapper();
static {
mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
}
public String toString() {
try {
return mapper.writeValueAsString(this);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@@ -1,89 +1,89 @@
package org.keycloak.jose.jws.crypto;
import org.keycloak.jose.jws.Algorithm;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.util.Base64Url;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class HMACProvider implements SignatureProvider {
private static String getJavaAlgorithm(Algorithm alg) {
switch (alg) {
case HS256:
return "HMACSHA256";
case HS384:
return "HMACSHA384";
case HS512:
return "HMACSHA512";
default:
throw new IllegalArgumentException("Not a MAC Algorithm");
}
}
private static Mac getMAC(final Algorithm alg) {
try {
return Mac.getInstance(getJavaAlgorithm(alg));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Unsupported HMAC algorithm: " + e.getMessage(), e);
}
}
public static byte[] sign(byte[] data, Algorithm algorithm, byte[] sharedSecret) {
try {
Mac mac = getMAC(algorithm);
mac.init(new SecretKeySpec(sharedSecret, mac.getAlgorithm()));
mac.update(data);
return mac.doFinal();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static byte[] sign(byte[] data, Algorithm algorithm, SecretKey key) {
try {
Mac mac = getMAC(algorithm);
mac.init(key);
mac.update(data);
return mac.doFinal();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static boolean verify(JWSInput input, SecretKey key) {
try {
byte[] signature = sign(input.getContent(), input.getHeader().getAlgorithm(), key);
String x = Base64Url.encode(signature);
return x.equals(input.getEncodedSignature());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static boolean verify(JWSInput input, byte[] sharedSecret) {
try {
byte[] signature = sign(input.getEncodedSignatureInput().getBytes("UTF-8"), input.getHeader().getAlgorithm(), sharedSecret);
String x = Base64Url.encode(signature);
return x.equals(input.getEncodedSignature());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public boolean verify(JWSInput input, String key) {
return false;
}
}
package org.keycloak.jose.jws.crypto;
import org.keycloak.jose.jws.Algorithm;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.util.Base64Url;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class HMACProvider implements SignatureProvider {
private static String getJavaAlgorithm(Algorithm alg) {
switch (alg) {
case HS256:
return "HMACSHA256";
case HS384:
return "HMACSHA384";
case HS512:
return "HMACSHA512";
default:
throw new IllegalArgumentException("Not a MAC Algorithm");
}
}
private static Mac getMAC(final Algorithm alg) {
try {
return Mac.getInstance(getJavaAlgorithm(alg));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Unsupported HMAC algorithm: " + e.getMessage(), e);
}
}
public static byte[] sign(byte[] data, Algorithm algorithm, byte[] sharedSecret) {
try {
Mac mac = getMAC(algorithm);
mac.init(new SecretKeySpec(sharedSecret, mac.getAlgorithm()));
mac.update(data);
return mac.doFinal();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static byte[] sign(byte[] data, Algorithm algorithm, SecretKey key) {
try {
Mac mac = getMAC(algorithm);
mac.init(key);
mac.update(data);
return mac.doFinal();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static boolean verify(JWSInput input, SecretKey key) {
try {
byte[] signature = sign(input.getContent(), input.getHeader().getAlgorithm(), key);
String x = Base64Url.encode(signature);
return x.equals(input.getEncodedSignature());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static boolean verify(JWSInput input, byte[] sharedSecret) {
try {
byte[] signature = sign(input.getEncodedSignatureInput().getBytes("UTF-8"), input.getHeader().getAlgorithm(), sharedSecret);
String x = Base64Url.encode(signature);
return x.equals(input.getEncodedSignature());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public boolean verify(JWSInput input, String key) {
return false;
}
}
@@ -1,11 +1,11 @@
package org.keycloak.jose.jws.crypto;
import org.keycloak.jose.jws.JWSInput;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface SignatureProvider {
boolean verify(JWSInput input, String key);
}
package org.keycloak.jose.jws.crypto;
import org.keycloak.jose.jws.JWSInput;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface SignatureProvider {
boolean verify(JWSInput input, String key);
}
@@ -1,211 +1,211 @@
package org.keycloak.representations;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class AccessToken extends IDToken {
public static class Access implements Serializable {
@JsonProperty("roles")
protected Set<String> roles;
@JsonProperty("verify_caller")
protected Boolean verifyCaller;
public Access() {
}
public Access clone() {
Access access = new Access();
access.verifyCaller = verifyCaller;
if (roles != null) {
access.roles = new HashSet<String>();
access.roles.addAll(roles);
}
return access;
}
public Set<String> getRoles() {
return roles;
}
public Access roles(Set<String> roles) {
this.roles = roles;
return this;
}
@JsonIgnore
public boolean isUserInRole(String role) {
if (roles == null) return false;
return roles.contains(role);
}
public Access addRole(String role) {
if (roles == null) roles = new HashSet<String>();
roles.add(role);
return this;
}
public Boolean getVerifyCaller() {
return verifyCaller;
}
public Access verifyCaller(Boolean required) {
this.verifyCaller = required;
return this;
}
}
@JsonProperty("client_session")
protected String clientSession;
@JsonProperty("trusted-certs")
protected Set<String> trustedCertificates;
@JsonProperty("allowed-origins")
protected Set<String> allowedOrigins;
@JsonProperty("realm_access")
protected Access realmAccess;
@JsonProperty("resource_access")
protected Map<String, Access> resourceAccess = new HashMap<String, Access>();
public Map<String, Access> getResourceAccess() {
return resourceAccess;
}
public void setResourceAccess(Map<String, Access> resourceAccess) {
this.resourceAccess = resourceAccess;
}
/**
* Does the realm require verifying the caller?
*
* @return
*/
@JsonIgnore
public boolean isVerifyCaller() {
if (getRealmAccess() != null && getRealmAccess().getVerifyCaller() != null)
return getRealmAccess().getVerifyCaller().booleanValue();
return false;
}
/**
* Does the resource override the requirement of verifying the caller?
*
* @param resource
* @return
*/
@JsonIgnore
public boolean isVerifyCaller(String resource) {
Access access = getResourceAccess(resource);
if (access != null && access.getVerifyCaller() != null) return access.getVerifyCaller().booleanValue();
return false;
}
@JsonIgnore
public Access getResourceAccess(String resource) {
return resourceAccess.get(resource);
}
public String getClientSession() {
return clientSession;
}
public Access addAccess(String service) {
Access access = resourceAccess.get(service);
if (access != null) return access;
access = new Access();
resourceAccess.put(service, access);
return access;
}
public AccessToken clientSession(String session) {
this.clientSession = session;
return this;
}
@Override
public AccessToken id(String id) {
return (AccessToken) super.id(id);
}
@Override
public AccessToken expiration(int expiration) {
return (AccessToken) super.expiration(expiration);
}
@Override
public AccessToken notBefore(int notBefore) {
return (AccessToken) super.notBefore(notBefore);
}
@Override
public AccessToken issuedAt(int issuedAt) {
return (AccessToken) super.issuedAt(issuedAt);
}
@Override
public AccessToken issuer(String issuer) {
return (AccessToken) super.issuer(issuer);
}
@Override
public AccessToken audience(String audience) {
return (AccessToken) super.audience(audience);
}
@Override
public AccessToken subject(String subject) {
return (AccessToken) super.subject(subject);
}
@Override
public AccessToken type(String type) {
return (AccessToken) super.type(type);
}
public Set<String> getAllowedOrigins() {
return allowedOrigins;
}
public void setAllowedOrigins(Set<String> allowedOrigins) {
this.allowedOrigins = allowedOrigins;
}
public Access getRealmAccess() {
return realmAccess;
}
public void setRealmAccess(Access realmAccess) {
this.realmAccess = realmAccess;
}
public Set<String> getTrustedCertificates() {
return trustedCertificates;
}
public void setTrustedCertificates(Set<String> trustedCertificates) {
this.trustedCertificates = trustedCertificates;
}
@Override
public AccessToken issuedFor(String issuedFor) {
return (AccessToken)super.issuedFor(issuedFor);
}
}
package org.keycloak.representations;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class AccessToken extends IDToken {
public static class Access implements Serializable {
@JsonProperty("roles")
protected Set<String> roles;
@JsonProperty("verify_caller")
protected Boolean verifyCaller;
public Access() {
}
public Access clone() {
Access access = new Access();
access.verifyCaller = verifyCaller;
if (roles != null) {
access.roles = new HashSet<String>();
access.roles.addAll(roles);
}
return access;
}
public Set<String> getRoles() {
return roles;
}
public Access roles(Set<String> roles) {
this.roles = roles;
return this;
}
@JsonIgnore
public boolean isUserInRole(String role) {
if (roles == null) return false;
return roles.contains(role);
}
public Access addRole(String role) {
if (roles == null) roles = new HashSet<String>();
roles.add(role);
return this;
}
public Boolean getVerifyCaller() {
return verifyCaller;
}
public Access verifyCaller(Boolean required) {
this.verifyCaller = required;
return this;
}
}
@JsonProperty("client_session")
protected String clientSession;
@JsonProperty("trusted-certs")
protected Set<String> trustedCertificates;
@JsonProperty("allowed-origins")
protected Set<String> allowedOrigins;
@JsonProperty("realm_access")
protected Access realmAccess;
@JsonProperty("resource_access")
protected Map<String, Access> resourceAccess = new HashMap<String, Access>();
public Map<String, Access> getResourceAccess() {
return resourceAccess;
}
public void setResourceAccess(Map<String, Access> resourceAccess) {
this.resourceAccess = resourceAccess;
}
/**
* Does the realm require verifying the caller?
*
* @return
*/
@JsonIgnore
public boolean isVerifyCaller() {
if (getRealmAccess() != null && getRealmAccess().getVerifyCaller() != null)
return getRealmAccess().getVerifyCaller().booleanValue();
return false;
}
/**
* Does the resource override the requirement of verifying the caller?
*
* @param resource
* @return
*/
@JsonIgnore
public boolean isVerifyCaller(String resource) {
Access access = getResourceAccess(resource);
if (access != null && access.getVerifyCaller() != null) return access.getVerifyCaller().booleanValue();
return false;
}
@JsonIgnore
public Access getResourceAccess(String resource) {
return resourceAccess.get(resource);
}
public String getClientSession() {
return clientSession;
}
public Access addAccess(String service) {
Access access = resourceAccess.get(service);
if (access != null) return access;
access = new Access();
resourceAccess.put(service, access);
return access;
}
public AccessToken clientSession(String session) {
this.clientSession = session;
return this;
}
@Override
public AccessToken id(String id) {
return (AccessToken) super.id(id);
}
@Override
public AccessToken expiration(int expiration) {
return (AccessToken) super.expiration(expiration);
}
@Override
public AccessToken notBefore(int notBefore) {
return (AccessToken) super.notBefore(notBefore);
}
@Override
public AccessToken issuedAt(int issuedAt) {
return (AccessToken) super.issuedAt(issuedAt);
}
@Override
public AccessToken issuer(String issuer) {
return (AccessToken) super.issuer(issuer);
}
@Override
public AccessToken audience(String audience) {
return (AccessToken) super.audience(audience);
}
@Override
public AccessToken subject(String subject) {
return (AccessToken) super.subject(subject);
}
@Override
public AccessToken type(String type) {
return (AccessToken) super.type(type);
}
public Set<String> getAllowedOrigins() {
return allowedOrigins;
}
public void setAllowedOrigins(Set<String> allowedOrigins) {
this.allowedOrigins = allowedOrigins;
}
public Access getRealmAccess() {
return realmAccess;
}
public void setRealmAccess(Access realmAccess) {
this.realmAccess = realmAccess;
}
public Set<String> getTrustedCertificates() {
return trustedCertificates;
}
public void setTrustedCertificates(Set<String> trustedCertificates) {
this.trustedCertificates = trustedCertificates;
}
@Override
public AccessToken issuedFor(String issuedFor) {
return (AccessToken)super.issuedFor(issuedFor);
}
}
@@ -1,83 +1,83 @@
package org.keycloak.representations;
import org.codehaus.jackson.annotate.JsonProperty;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class AddressClaimSet {
public static final String FORMATTED = "formatted";
public static final String STREET_ADDRESS = "street_address";
public static final String LOCALITY = "locality";
public static final String REGION = "region";
public static final String POSTAL_CODE = "postal_code";
public static final String COUNTRY = "country";
@JsonProperty(FORMATTED)
protected String formattedAddress;
@JsonProperty(STREET_ADDRESS)
protected String streetAddress;
@JsonProperty(LOCALITY)
protected String locality;
@JsonProperty(REGION)
protected String region;
@JsonProperty(POSTAL_CODE)
protected String postalCode;
@JsonProperty(COUNTRY)
protected String country;
public String getFormattedAddress() {
return this.formattedAddress;
}
public void setFormattedAddress(String formattedAddress) {
this.formattedAddress = formattedAddress;
}
public String getStreetAddress() {
return this.streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getLocality() {
return this.locality;
}
public void setLocality(String locality) {
this.locality = locality;
}
public String getRegion() {
return this.region;
}
public void setRegion(String region) {
this.region = region;
}
public String getPostalCode() {
return this.postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
}
package org.keycloak.representations;
import org.codehaus.jackson.annotate.JsonProperty;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class AddressClaimSet {
public static final String FORMATTED = "formatted";
public static final String STREET_ADDRESS = "street_address";
public static final String LOCALITY = "locality";
public static final String REGION = "region";
public static final String POSTAL_CODE = "postal_code";
public static final String COUNTRY = "country";
@JsonProperty(FORMATTED)
protected String formattedAddress;
@JsonProperty(STREET_ADDRESS)
protected String streetAddress;
@JsonProperty(LOCALITY)
protected String locality;
@JsonProperty(REGION)
protected String region;
@JsonProperty(POSTAL_CODE)
protected String postalCode;
@JsonProperty(COUNTRY)
protected String country;
public String getFormattedAddress() {
return this.formattedAddress;
}
public void setFormattedAddress(String formattedAddress) {
this.formattedAddress = formattedAddress;
}
public String getStreetAddress() {
return this.streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getLocality() {
return this.locality;
}
public void setLocality(String locality) {
this.locality = locality;
}
public String getRegion() {
return this.region;
}
public void setRegion(String region) {
this.region = region;
}
public String getPostalCode() {
return this.postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
}
@@ -1,282 +1,282 @@
package org.keycloak.representations;
import org.codehaus.jackson.annotate.JsonAnyGetter;
import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonUnwrapped;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class IDToken extends JsonWebToken {
public static final String NONCE = "nonce";
public static final String SESSION_STATE = "session_state";
public static final String NAME = "name";
public static final String GIVEN_NAME = "given_name";
public static final String FAMILY_NAME = "family_name";
public static final String MIDDLE_NAME = "middle_name";
public static final String NICKNAME = "nickname";
public static final String PREFERRED_USERNAME = "preferred_username";
public static final String PROFILE = "profile";
public static final String PICTURE = "picture";
public static final String WEBSITE = "website";
public static final String EMAIL = "email";
public static final String EMAIL_VERIFIED = "email_verified";
public static final String GENDER = "gender";
public static final String BIRTHDATE = "birthdate";
public static final String ZONEINFO = "zoneinfo";
public static final String LOCALE = "locale";
public static final String PHONE_NUMBER = "phone_number";
public static final String PHONE_NUMBER_VERIFIED = "phone_number_verified";
public static final String ADDRESS = "address";
public static final String UPDATED_AT = "updated_at";
public static final String CLAIMS_LOCALES = "claims_locales";
// NOTE!!! WE used to use @JsonUnwrapped on a UserClaimSet object. This screws up otherClaims and the won't work
// anymore. So don't have any @JsonUnwrapped!
@JsonProperty(NONCE)
protected String nonce;
@JsonProperty(SESSION_STATE)
protected String sessionState;
@JsonProperty(NAME)
protected String name;
@JsonProperty(GIVEN_NAME)
protected String givenName;
@JsonProperty(FAMILY_NAME)
protected String familyName;
@JsonProperty(MIDDLE_NAME)
protected String middleName;
@JsonProperty(NICKNAME)
protected String nickName;
@JsonProperty(PREFERRED_USERNAME)
protected String preferredUsername;
@JsonProperty(PROFILE)
protected String profile;
@JsonProperty(PICTURE)
protected String picture;
@JsonProperty(WEBSITE)
protected String website;
@JsonProperty(EMAIL)
protected String email;
@JsonProperty(EMAIL_VERIFIED)
protected Boolean emailVerified;
@JsonProperty(GENDER)
protected String gender;
@JsonProperty(BIRTHDATE)
protected String birthdate;
@JsonProperty(ZONEINFO)
protected String zoneinfo;
@JsonProperty(LOCALE)
protected String locale;
@JsonProperty(PHONE_NUMBER)
protected String phoneNumber;
@JsonProperty(PHONE_NUMBER_VERIFIED)
protected Boolean phoneNumberVerified;
@JsonProperty(ADDRESS)
protected AddressClaimSet address;
@JsonProperty(UPDATED_AT)
protected Long updatedAt;
@JsonProperty(CLAIMS_LOCALES)
protected String claimsLocales;
public String getNonce() {
return nonce;
}
public void setNonce(String nonce) {
this.nonce = nonce;
}
public String getSessionState() {
return sessionState;
}
public void setSessionState(String sessionState) {
this.sessionState = sessionState;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getGivenName() {
return this.givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getFamilyName() {
return this.familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getMiddleName() {
return this.middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getNickName() {
return this.nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getPreferredUsername() {
return this.preferredUsername;
}
public void setPreferredUsername(String preferredUsername) {
this.preferredUsername = preferredUsername;
}
public String getProfile() {
return this.profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public String getPicture() {
return this.picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getWebsite() {
return this.website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public Boolean getEmailVerified() {
return this.emailVerified;
}
public void setEmailVerified(Boolean emailVerified) {
this.emailVerified = emailVerified;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getBirthdate() {
return this.birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getZoneinfo() {
return this.zoneinfo;
}
public void setZoneinfo(String zoneinfo) {
this.zoneinfo = zoneinfo;
}
public String getLocale() {
return this.locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Boolean getPhoneNumberVerified() {
return this.phoneNumberVerified;
}
public void setPhoneNumberVerified(Boolean phoneNumberVerified) {
this.phoneNumberVerified = phoneNumberVerified;
}
public AddressClaimSet getAddress() {
return address;
}
public void setAddress(AddressClaimSet address) {
this.address = address;
}
public Long getUpdatedAt() {
return this.updatedAt;
}
public void setUpdatedAt(Long updatedAt) {
this.updatedAt = updatedAt;
}
public String getClaimsLocales() {
return this.claimsLocales;
}
public void setClaimsLocales(String claimsLocales) {
this.claimsLocales = claimsLocales;
}
}
package org.keycloak.representations;
import org.codehaus.jackson.annotate.JsonAnyGetter;
import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonUnwrapped;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class IDToken extends JsonWebToken {
public static final String NONCE = "nonce";
public static final String SESSION_STATE = "session_state";
public static final String NAME = "name";
public static final String GIVEN_NAME = "given_name";
public static final String FAMILY_NAME = "family_name";
public static final String MIDDLE_NAME = "middle_name";
public static final String NICKNAME = "nickname";
public static final String PREFERRED_USERNAME = "preferred_username";
public static final String PROFILE = "profile";
public static final String PICTURE = "picture";
public static final String WEBSITE = "website";
public static final String EMAIL = "email";
public static final String EMAIL_VERIFIED = "email_verified";
public static final String GENDER = "gender";
public static final String BIRTHDATE = "birthdate";
public static final String ZONEINFO = "zoneinfo";
public static final String LOCALE = "locale";
public static final String PHONE_NUMBER = "phone_number";
public static final String PHONE_NUMBER_VERIFIED = "phone_number_verified";
public static final String ADDRESS = "address";
public static final String UPDATED_AT = "updated_at";
public static final String CLAIMS_LOCALES = "claims_locales";
// NOTE!!! WE used to use @JsonUnwrapped on a UserClaimSet object. This screws up otherClaims and the won't work
// anymore. So don't have any @JsonUnwrapped!
@JsonProperty(NONCE)
protected String nonce;
@JsonProperty(SESSION_STATE)
protected String sessionState;
@JsonProperty(NAME)
protected String name;
@JsonProperty(GIVEN_NAME)
protected String givenName;
@JsonProperty(FAMILY_NAME)
protected String familyName;
@JsonProperty(MIDDLE_NAME)
protected String middleName;
@JsonProperty(NICKNAME)
protected String nickName;
@JsonProperty(PREFERRED_USERNAME)
protected String preferredUsername;
@JsonProperty(PROFILE)
protected String profile;
@JsonProperty(PICTURE)
protected String picture;
@JsonProperty(WEBSITE)
protected String website;
@JsonProperty(EMAIL)
protected String email;
@JsonProperty(EMAIL_VERIFIED)
protected Boolean emailVerified;
@JsonProperty(GENDER)
protected String gender;
@JsonProperty(BIRTHDATE)
protected String birthdate;
@JsonProperty(ZONEINFO)
protected String zoneinfo;
@JsonProperty(LOCALE)
protected String locale;
@JsonProperty(PHONE_NUMBER)
protected String phoneNumber;
@JsonProperty(PHONE_NUMBER_VERIFIED)
protected Boolean phoneNumberVerified;
@JsonProperty(ADDRESS)
protected AddressClaimSet address;
@JsonProperty(UPDATED_AT)
protected Long updatedAt;
@JsonProperty(CLAIMS_LOCALES)
protected String claimsLocales;
public String getNonce() {
return nonce;
}
public void setNonce(String nonce) {
this.nonce = nonce;
}
public String getSessionState() {
return sessionState;
}
public void setSessionState(String sessionState) {
this.sessionState = sessionState;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getGivenName() {
return this.givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getFamilyName() {
return this.familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getMiddleName() {
return this.middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getNickName() {
return this.nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getPreferredUsername() {
return this.preferredUsername;
}
public void setPreferredUsername(String preferredUsername) {
this.preferredUsername = preferredUsername;
}
public String getProfile() {
return this.profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public String getPicture() {
return this.picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getWebsite() {
return this.website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public Boolean getEmailVerified() {
return this.emailVerified;
}
public void setEmailVerified(Boolean emailVerified) {
this.emailVerified = emailVerified;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getBirthdate() {
return this.birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getZoneinfo() {
return this.zoneinfo;
}
public void setZoneinfo(String zoneinfo) {
this.zoneinfo = zoneinfo;
}
public String getLocale() {
return this.locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Boolean getPhoneNumberVerified() {
return this.phoneNumberVerified;
}
public void setPhoneNumberVerified(Boolean phoneNumberVerified) {
this.phoneNumberVerified = phoneNumberVerified;
}
public AddressClaimSet getAddress() {
return address;
}
public void setAddress(AddressClaimSet address) {
this.address = address;
}
public Long getUpdatedAt() {
return this.updatedAt;
}
public void setUpdatedAt(Long updatedAt) {
this.updatedAt = updatedAt;
}
public String getClaimsLocales() {
return this.claimsLocales;
}
public void setClaimsLocales(String claimsLocales) {
this.claimsLocales = claimsLocales;
}
}
@@ -1,176 +1,176 @@
package org.keycloak.representations;
import org.codehaus.jackson.annotate.JsonAnyGetter;
import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
import org.keycloak.util.Time;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class JsonWebToken implements Serializable {
@JsonProperty("jti")
protected String id;
@JsonProperty("exp")
protected int expiration;
@JsonProperty("nbf")
protected int notBefore;
@JsonProperty("iat")
protected int issuedAt;
@JsonProperty("iss")
protected String issuer;
@JsonProperty("aud")
protected String audience;
@JsonProperty("sub")
protected String subject;
@JsonProperty("typ")
protected String type;
@JsonProperty("azp")
public String issuedFor;
protected Map<String, Object> otherClaims = new HashMap<String, Object>();
public String getId() {
return id;
}
public JsonWebToken id(String id) {
this.id = id;
return this;
}
public int getExpiration() {
return expiration;
}
public JsonWebToken expiration(int expiration) {
this.expiration = expiration;
return this;
}
@JsonIgnore
public boolean isExpired() {
return Time.currentTime() > expiration;
}
public int getNotBefore() {
return notBefore;
}
public JsonWebToken notBefore(int notBefore) {
this.notBefore = notBefore;
return this;
}
@JsonIgnore
public boolean isNotBefore() {
return Time.currentTime() >= notBefore;
}
/**
* Tests that the token is not expired and is not-before.
*
* @return
*/
@JsonIgnore
public boolean isActive() {
return (!isExpired() || expiration == 0) && (isNotBefore() || notBefore == 0);
}
public int getIssuedAt() {
return issuedAt;
}
/**
* Set issuedAt to the current time
*/
@JsonIgnore
public JsonWebToken issuedNow() {
issuedAt = Time.currentTime();
return this;
}
public JsonWebToken issuedAt(int issuedAt) {
this.issuedAt = issuedAt;
return this;
}
public String getIssuer() {
return issuer;
}
public JsonWebToken issuer(String issuer) {
this.issuer = issuer;
return this;
}
public String getAudience() {
return audience;
}
public JsonWebToken audience(String audience) {
this.audience = audience;
return this;
}
public String getSubject() {
return subject;
}
public JsonWebToken subject(String subject) {
this.subject = subject;
return this;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getType() {
return type;
}
public JsonWebToken type(String type) {
this.type = type;
return this;
}
/**
* OAuth client the token was issued for.
*
* @return
*/
public String getIssuedFor() {
return issuedFor;
}
public JsonWebToken issuedFor(String issuedFor) {
this.issuedFor = issuedFor;
return this;
}
/**
* This is a map of any other claims and data that might be in the IDToken. Could be custom claims set up by the auth server
*
* @return
*/
@JsonAnyGetter
public Map<String, Object> getOtherClaims() {
return otherClaims;
}
@JsonAnySetter
public void setOtherClaims(String name, Object value) {
otherClaims.put(name, value);
}
}
package org.keycloak.representations;
import org.codehaus.jackson.annotate.JsonAnyGetter;
import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
import org.keycloak.util.Time;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class JsonWebToken implements Serializable {
@JsonProperty("jti")
protected String id;
@JsonProperty("exp")
protected int expiration;
@JsonProperty("nbf")
protected int notBefore;
@JsonProperty("iat")
protected int issuedAt;
@JsonProperty("iss")
protected String issuer;
@JsonProperty("aud")
protected String audience;
@JsonProperty("sub")
protected String subject;
@JsonProperty("typ")
protected String type;
@JsonProperty("azp")
public String issuedFor;
protected Map<String, Object> otherClaims = new HashMap<String, Object>();
public String getId() {
return id;
}
public JsonWebToken id(String id) {
this.id = id;
return this;
}
public int getExpiration() {
return expiration;
}
public JsonWebToken expiration(int expiration) {
this.expiration = expiration;
return this;
}
@JsonIgnore
public boolean isExpired() {
return Time.currentTime() > expiration;
}
public int getNotBefore() {
return notBefore;
}
public JsonWebToken notBefore(int notBefore) {
this.notBefore = notBefore;
return this;
}
@JsonIgnore
public boolean isNotBefore() {
return Time.currentTime() >= notBefore;
}
/**
* Tests that the token is not expired and is not-before.
*
* @return
*/
@JsonIgnore
public boolean isActive() {
return (!isExpired() || expiration == 0) && (isNotBefore() || notBefore == 0);
}
public int getIssuedAt() {
return issuedAt;
}
/**
* Set issuedAt to the current time
*/
@JsonIgnore
public JsonWebToken issuedNow() {
issuedAt = Time.currentTime();
return this;
}
public JsonWebToken issuedAt(int issuedAt) {
this.issuedAt = issuedAt;
return this;
}
public String getIssuer() {
return issuer;
}
public JsonWebToken issuer(String issuer) {
this.issuer = issuer;
return this;
}
public String getAudience() {
return audience;
}
public JsonWebToken audience(String audience) {
this.audience = audience;
return this;
}
public String getSubject() {
return subject;
}
public JsonWebToken subject(String subject) {
this.subject = subject;
return this;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getType() {
return type;
}
public JsonWebToken type(String type) {
this.type = type;
return this;
}
/**
* OAuth client the token was issued for.
*
* @return
*/
public String getIssuedFor() {
return issuedFor;
}
public JsonWebToken issuedFor(String issuedFor) {
this.issuedFor = issuedFor;
return this;
}
/**
* This is a map of any other claims and data that might be in the IDToken. Could be custom claims set up by the auth server
*
* @return
*/
@JsonAnyGetter
public Map<String, Object> getOtherClaims() {
return otherClaims;
}
@JsonAnySetter
public void setOtherClaims(String name, Object value) {
otherClaims.put(name, value);
}
}
@@ -1,42 +1,42 @@
package org.keycloak.representations;
import org.codehaus.jackson.annotate.JsonProperty;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class RefreshToken extends AccessToken {
private RefreshToken() {
type("REFRESH");
}
/**
* Deep copies issuer, subject, issuedFor, sessionState, realmAccess, and resourceAccess
* from AccessToken.
*
* @param token
*/
public RefreshToken(AccessToken token) {
this();
this.clientSession = token.getClientSession();
this.issuer = token.issuer;
this.subject = token.subject;
this.issuedFor = token.issuedFor;
this.sessionState = token.sessionState;
if (token.realmAccess != null) {
realmAccess = token.realmAccess.clone();
}
if (token.resourceAccess != null) {
resourceAccess = new HashMap<String, Access>();
for (Map.Entry<String, Access> entry : token.resourceAccess.entrySet()) {
resourceAccess.put(entry.getKey(), entry.getValue().clone());
}
}
}
}
package org.keycloak.representations;
import org.codehaus.jackson.annotate.JsonProperty;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class RefreshToken extends AccessToken {
private RefreshToken() {
type("REFRESH");
}
/**
* Deep copies issuer, subject, issuedFor, sessionState, realmAccess, and resourceAccess
* from AccessToken.
*
* @param token
*/
public RefreshToken(AccessToken token) {
this();
this.clientSession = token.getClientSession();
this.issuer = token.issuer;
this.subject = token.subject;
this.issuedFor = token.issuedFor;
this.sessionState = token.sessionState;
if (token.realmAccess != null) {
realmAccess = token.realmAccess.clone();
}
if (token.resourceAccess != null) {
resourceAccess = new HashMap<String, Access>();
for (Map.Entry<String, Access> entry : token.resourceAccess.entrySet()) {
resourceAccess.put(entry.getKey(), entry.getValue().clone());
}
}
}
}
@@ -1,71 +1,71 @@
package org.keycloak.representations.adapters.action;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.keycloak.util.Time;
/**
* Posted to managed client from admin server.
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public abstract class AdminAction {
protected String id;
protected int expiration;
protected String resource;
protected String action;
public AdminAction() {
}
public AdminAction(String id, int expiration, String resource, String action) {
this.id = id;
this.expiration = expiration;
this.resource = resource;
this.action = action;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@JsonIgnore
public boolean isExpired() {
return Time.currentTime() > expiration;
}
/**
* Time in seconds since epoc
*
* @return
*/
public int getExpiration() {
return expiration;
}
public void setExpiration(int expiration) {
this.expiration = expiration;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public abstract boolean validate();
}
package org.keycloak.representations.adapters.action;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.keycloak.util.Time;
/**
* Posted to managed client from admin server.
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public abstract class AdminAction {
protected String id;
protected int expiration;
protected String resource;
protected String action;
public AdminAction() {
}
public AdminAction(String id, int expiration, String resource, String action) {
this.id = id;
this.expiration = expiration;
this.resource = resource;
this.action = action;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@JsonIgnore
public boolean isExpired() {
return Time.currentTime() > expiration;
}
/**
* Time in seconds since epoc
*
* @return
*/
public int getExpiration() {
return expiration;
}
public void setExpiration(int expiration) {
this.expiration = expiration;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public abstract boolean validate();
}
@@ -1,50 +1,50 @@
package org.keycloak.representations.adapters.action;
import java.util.List;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class LogoutAction extends AdminAction {
public static final String LOGOUT = "LOGOUT";
protected List<String> adapterSessionIds;
protected int notBefore;
protected List<String> keycloakSessionIds;
public LogoutAction() {
}
public LogoutAction(String id, int expiration, String resource, List<String> adapterSessionIds, int notBefore, List<String> keycloakSessionIds) {
super(id, expiration, resource, LOGOUT);
this.adapterSessionIds = adapterSessionIds;
this.notBefore = notBefore;
this.keycloakSessionIds = keycloakSessionIds;
}
public int getNotBefore() {
return notBefore;
}
public void setNotBefore(int notBefore) {
this.notBefore = notBefore;
}
public List<String> getAdapterSessionIds() {
return adapterSessionIds;
}
public List<String> getKeycloakSessionIds() {
return keycloakSessionIds;
}
public void setKeycloakSessionIds(List<String> keycloakSessionIds) {
this.keycloakSessionIds = keycloakSessionIds;
}
@Override
public boolean validate() {
return LOGOUT.equals(action);
}
}
package org.keycloak.representations.adapters.action;
import java.util.List;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class LogoutAction extends AdminAction {
public static final String LOGOUT = "LOGOUT";
protected List<String> adapterSessionIds;
protected int notBefore;
protected List<String> keycloakSessionIds;
public LogoutAction() {
}
public LogoutAction(String id, int expiration, String resource, List<String> adapterSessionIds, int notBefore, List<String> keycloakSessionIds) {
super(id, expiration, resource, LOGOUT);
this.adapterSessionIds = adapterSessionIds;
this.notBefore = notBefore;
this.keycloakSessionIds = keycloakSessionIds;
}
public int getNotBefore() {
return notBefore;
}
public void setNotBefore(int notBefore) {
this.notBefore = notBefore;
}
public List<String> getAdapterSessionIds() {
return adapterSessionIds;
}
public List<String> getKeycloakSessionIds() {
return keycloakSessionIds;
}
public void setKeycloakSessionIds(List<String> keycloakSessionIds) {
this.keycloakSessionIds = keycloakSessionIds;
}
@Override
public boolean validate() {
return LOGOUT.equals(action);
}
}
@@ -1,33 +1,33 @@
package org.keycloak.representations.adapters.action;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class PushNotBeforeAction extends AdminAction {
public static final String PUSH_NOT_BEFORE = "PUSH_NOT_BEFORE";
protected int notBefore;
public PushNotBeforeAction() {
}
public PushNotBeforeAction(String id, int expiration, String resource, int notBefore) {
super(id, expiration, resource, PUSH_NOT_BEFORE);
this.notBefore = notBefore;
}
public int getNotBefore() {
return notBefore;
}
public void setNotBefore(int notBefore) {
this.notBefore = notBefore;
}
@Override
public boolean validate() {
return PUSH_NOT_BEFORE.equals(action);
}
}
package org.keycloak.representations.adapters.action;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class PushNotBeforeAction extends AdminAction {
public static final String PUSH_NOT_BEFORE = "PUSH_NOT_BEFORE";
protected int notBefore;
public PushNotBeforeAction() {
}
public PushNotBeforeAction(String id, int expiration, String resource, int notBefore) {
super(id, expiration, resource, PUSH_NOT_BEFORE);
this.notBefore = notBefore;
}
public int getNotBefore() {
return notBefore;
}
public void setNotBefore(int notBefore) {
this.notBefore = notBefore;
}
@Override
public boolean validate() {
return PUSH_NOT_BEFORE.equals(action);
}
}
@@ -1,165 +1,165 @@
package org.keycloak.representations.adapters.config;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
/**
* Configuration for Java based adapters
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@JsonPropertyOrder({"realm", "realm-public-key", "auth-server-url", "ssl-required",
"resource", "public-client", "credentials",
"use-resource-role-mappings",
"enable-cors", "cors-max-age", "cors-allowed-methods",
"expose-token", "bearer-only",
"connection-pool-size",
"allow-any-hostname", "disable-trust-manager", "truststore", "truststore-password",
"client-keystore", "client-keystore-password", "client-key-password",
"auth-server-url-for-backend-requests", "always-refresh-token",
"register-node-at-startup", "register-node-period", "token-store", "principal-attribute"
})
public class AdapterConfig extends BaseAdapterConfig {
@JsonProperty("allow-any-hostname")
protected boolean allowAnyHostname;
@JsonProperty("disable-trust-manager")
protected boolean disableTrustManager;
@JsonProperty("truststore")
protected String truststore;
@JsonProperty("truststore-password")
protected String truststorePassword;
@JsonProperty("client-keystore")
protected String clientKeystore;
@JsonProperty("client-keystore-password")
protected String clientKeystorePassword;
@JsonProperty("client-key-password")
protected String clientKeyPassword;
@JsonProperty("connection-pool-size")
protected int connectionPoolSize = 20;
@JsonProperty("auth-server-url-for-backend-requests")
protected String authServerUrlForBackendRequests;
@JsonProperty("always-refresh-token")
protected boolean alwaysRefreshToken = false;
@JsonProperty("register-node-at-startup")
protected boolean registerNodeAtStartup = false;
@JsonProperty("register-node-period")
protected int registerNodePeriod = -1;
@JsonProperty("token-store")
protected String tokenStore;
@JsonProperty("principal-attribute")
protected String principalAttribute;
public boolean isAllowAnyHostname() {
return allowAnyHostname;
}
public void setAllowAnyHostname(boolean allowAnyHostname) {
this.allowAnyHostname = allowAnyHostname;
}
public boolean isDisableTrustManager() {
return disableTrustManager;
}
public void setDisableTrustManager(boolean disableTrustManager) {
this.disableTrustManager = disableTrustManager;
}
public String getTruststore() {
return truststore;
}
public void setTruststore(String truststore) {
this.truststore = truststore;
}
public String getTruststorePassword() {
return truststorePassword;
}
public void setTruststorePassword(String truststorePassword) {
this.truststorePassword = truststorePassword;
}
public String getClientKeystore() {
return clientKeystore;
}
public void setClientKeystore(String clientKeystore) {
this.clientKeystore = clientKeystore;
}
public String getClientKeystorePassword() {
return clientKeystorePassword;
}
public void setClientKeystorePassword(String clientKeystorePassword) {
this.clientKeystorePassword = clientKeystorePassword;
}
public String getClientKeyPassword() {
return clientKeyPassword;
}
public void setClientKeyPassword(String clientKeyPassword) {
this.clientKeyPassword = clientKeyPassword;
}
public int getConnectionPoolSize() {
return connectionPoolSize;
}
public void setConnectionPoolSize(int connectionPoolSize) {
this.connectionPoolSize = connectionPoolSize;
}
public String getAuthServerUrlForBackendRequests() {
return authServerUrlForBackendRequests;
}
public void setAuthServerUrlForBackendRequests(String authServerUrlForBackendRequests) {
this.authServerUrlForBackendRequests = authServerUrlForBackendRequests;
}
public boolean isAlwaysRefreshToken() {
return alwaysRefreshToken;
}
public void setAlwaysRefreshToken(boolean alwaysRefreshToken) {
this.alwaysRefreshToken = alwaysRefreshToken;
}
public boolean isRegisterNodeAtStartup() {
return registerNodeAtStartup;
}
public void setRegisterNodeAtStartup(boolean registerNodeAtStartup) {
this.registerNodeAtStartup = registerNodeAtStartup;
}
public int getRegisterNodePeriod() {
return registerNodePeriod;
}
public void setRegisterNodePeriod(int registerNodePeriod) {
this.registerNodePeriod = registerNodePeriod;
}
public String getTokenStore() {
return tokenStore;
}
public void setTokenStore(String tokenStore) {
this.tokenStore = tokenStore;
}
public String getPrincipalAttribute() {
return principalAttribute;
}
public void setPrincipalAttribute(String principalAttribute) {
this.principalAttribute = principalAttribute;
}
}
package org.keycloak.representations.adapters.config;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
/**
* Configuration for Java based adapters
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@JsonPropertyOrder({"realm", "realm-public-key", "auth-server-url", "ssl-required",
"resource", "public-client", "credentials",
"use-resource-role-mappings",
"enable-cors", "cors-max-age", "cors-allowed-methods",
"expose-token", "bearer-only",
"connection-pool-size",
"allow-any-hostname", "disable-trust-manager", "truststore", "truststore-password",
"client-keystore", "client-keystore-password", "client-key-password",
"auth-server-url-for-backend-requests", "always-refresh-token",
"register-node-at-startup", "register-node-period", "token-store", "principal-attribute"
})
public class AdapterConfig extends BaseAdapterConfig {
@JsonProperty("allow-any-hostname")
protected boolean allowAnyHostname;
@JsonProperty("disable-trust-manager")
protected boolean disableTrustManager;
@JsonProperty("truststore")
protected String truststore;
@JsonProperty("truststore-password")
protected String truststorePassword;
@JsonProperty("client-keystore")
protected String clientKeystore;
@JsonProperty("client-keystore-password")
protected String clientKeystorePassword;
@JsonProperty("client-key-password")
protected String clientKeyPassword;
@JsonProperty("connection-pool-size")
protected int connectionPoolSize = 20;
@JsonProperty("auth-server-url-for-backend-requests")
protected String authServerUrlForBackendRequests;
@JsonProperty("always-refresh-token")
protected boolean alwaysRefreshToken = false;
@JsonProperty("register-node-at-startup")
protected boolean registerNodeAtStartup = false;
@JsonProperty("register-node-period")
protected int registerNodePeriod = -1;
@JsonProperty("token-store")
protected String tokenStore;
@JsonProperty("principal-attribute")
protected String principalAttribute;
public boolean isAllowAnyHostname() {
return allowAnyHostname;
}
public void setAllowAnyHostname(boolean allowAnyHostname) {
this.allowAnyHostname = allowAnyHostname;
}
public boolean isDisableTrustManager() {
return disableTrustManager;
}
public void setDisableTrustManager(boolean disableTrustManager) {
this.disableTrustManager = disableTrustManager;
}
public String getTruststore() {
return truststore;
}
public void setTruststore(String truststore) {
this.truststore = truststore;
}
public String getTruststorePassword() {
return truststorePassword;
}
public void setTruststorePassword(String truststorePassword) {
this.truststorePassword = truststorePassword;
}
public String getClientKeystore() {
return clientKeystore;
}
public void setClientKeystore(String clientKeystore) {
this.clientKeystore = clientKeystore;
}
public String getClientKeystorePassword() {
return clientKeystorePassword;
}
public void setClientKeystorePassword(String clientKeystorePassword) {
this.clientKeystorePassword = clientKeystorePassword;
}
public String getClientKeyPassword() {
return clientKeyPassword;
}
public void setClientKeyPassword(String clientKeyPassword) {
this.clientKeyPassword = clientKeyPassword;
}
public int getConnectionPoolSize() {
return connectionPoolSize;
}
public void setConnectionPoolSize(int connectionPoolSize) {
this.connectionPoolSize = connectionPoolSize;
}
public String getAuthServerUrlForBackendRequests() {
return authServerUrlForBackendRequests;
}
public void setAuthServerUrlForBackendRequests(String authServerUrlForBackendRequests) {
this.authServerUrlForBackendRequests = authServerUrlForBackendRequests;
}
public boolean isAlwaysRefreshToken() {
return alwaysRefreshToken;
}
public void setAlwaysRefreshToken(boolean alwaysRefreshToken) {
this.alwaysRefreshToken = alwaysRefreshToken;
}
public boolean isRegisterNodeAtStartup() {
return registerNodeAtStartup;
}
public void setRegisterNodeAtStartup(boolean registerNodeAtStartup) {
this.registerNodeAtStartup = registerNodeAtStartup;
}
public int getRegisterNodePeriod() {
return registerNodePeriod;
}
public void setRegisterNodePeriod(int registerNodePeriod) {
this.registerNodePeriod = registerNodePeriod;
}
public String getTokenStore() {
return tokenStore;
}
public void setTokenStore(String tokenStore) {
this.tokenStore = tokenStore;
}
public String getPrincipalAttribute() {
return principalAttribute;
}
public void setPrincipalAttribute(String principalAttribute) {
this.principalAttribute = principalAttribute;
}
}
@@ -1,132 +1,132 @@
package org.keycloak.representations.adapters.config;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
import java.util.HashMap;
import java.util.Map;
/**
* Common Adapter configuration
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@JsonPropertyOrder({"realm", "realm-public-key", "auth-server-url", "ssl-required",
"resource", "public-client", "credentials",
"use-resource-role-mappings",
"enable-cors", "cors-max-age", "cors-allowed-methods",
"expose-token", "bearer-only", "enable-basic-auth"})
public class BaseAdapterConfig extends BaseRealmConfig {
@JsonProperty("resource")
protected String resource;
@JsonProperty("use-resource-role-mappings")
protected boolean useResourceRoleMappings;
@JsonProperty("enable-cors")
protected boolean cors;
@JsonProperty("cors-max-age")
protected int corsMaxAge = -1;
@JsonProperty("cors-allowed-headers")
protected String corsAllowedHeaders;
@JsonProperty("cors-allowed-methods")
protected String corsAllowedMethods;
@JsonProperty("expose-token")
protected boolean exposeToken;
@JsonProperty("bearer-only")
protected boolean bearerOnly;
@JsonProperty("enable-basic-auth")
protected boolean enableBasicAuth;
@JsonProperty("public-client")
protected boolean publicClient;
@JsonProperty("credentials")
protected Map<String, String> credentials = new HashMap<String, String>();
public boolean isUseResourceRoleMappings() {
return useResourceRoleMappings;
}
public void setUseResourceRoleMappings(boolean useResourceRoleMappings) {
this.useResourceRoleMappings = useResourceRoleMappings;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public boolean isCors() {
return cors;
}
public void setCors(boolean cors) {
this.cors = cors;
}
public int getCorsMaxAge() {
return corsMaxAge;
}
public void setCorsMaxAge(int corsMaxAge) {
this.corsMaxAge = corsMaxAge;
}
public String getCorsAllowedHeaders() {
return corsAllowedHeaders;
}
public void setCorsAllowedHeaders(String corsAllowedHeaders) {
this.corsAllowedHeaders = corsAllowedHeaders;
}
public String getCorsAllowedMethods() {
return corsAllowedMethods;
}
public void setCorsAllowedMethods(String corsAllowedMethods) {
this.corsAllowedMethods = corsAllowedMethods;
}
public boolean isExposeToken() {
return exposeToken;
}
public void setExposeToken(boolean exposeToken) {
this.exposeToken = exposeToken;
}
public boolean isBearerOnly() {
return bearerOnly;
}
public void setBearerOnly(boolean bearerOnly) {
this.bearerOnly = bearerOnly;
}
public boolean isEnableBasicAuth() {
return enableBasicAuth;
}
public void setEnableBasicAuth(boolean enableBasicAuth) {
this.enableBasicAuth = enableBasicAuth;
}
public Map<String, String> getCredentials() {
return credentials;
}
public void setCredentials(Map<String, String> credentials) {
this.credentials = credentials;
}
public boolean isPublicClient() {
return publicClient;
}
public void setPublicClient(boolean publicClient) {
this.publicClient = publicClient;
}
}
package org.keycloak.representations.adapters.config;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
import java.util.HashMap;
import java.util.Map;
/**
* Common Adapter configuration
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@JsonPropertyOrder({"realm", "realm-public-key", "auth-server-url", "ssl-required",
"resource", "public-client", "credentials",
"use-resource-role-mappings",
"enable-cors", "cors-max-age", "cors-allowed-methods",
"expose-token", "bearer-only", "enable-basic-auth"})
public class BaseAdapterConfig extends BaseRealmConfig {
@JsonProperty("resource")
protected String resource;
@JsonProperty("use-resource-role-mappings")
protected boolean useResourceRoleMappings;
@JsonProperty("enable-cors")
protected boolean cors;
@JsonProperty("cors-max-age")
protected int corsMaxAge = -1;
@JsonProperty("cors-allowed-headers")
protected String corsAllowedHeaders;
@JsonProperty("cors-allowed-methods")
protected String corsAllowedMethods;
@JsonProperty("expose-token")
protected boolean exposeToken;
@JsonProperty("bearer-only")
protected boolean bearerOnly;
@JsonProperty("enable-basic-auth")
protected boolean enableBasicAuth;
@JsonProperty("public-client")
protected boolean publicClient;
@JsonProperty("credentials")
protected Map<String, String> credentials = new HashMap<String, String>();
public boolean isUseResourceRoleMappings() {
return useResourceRoleMappings;
}
public void setUseResourceRoleMappings(boolean useResourceRoleMappings) {
this.useResourceRoleMappings = useResourceRoleMappings;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public boolean isCors() {
return cors;
}
public void setCors(boolean cors) {
this.cors = cors;
}
public int getCorsMaxAge() {
return corsMaxAge;
}
public void setCorsMaxAge(int corsMaxAge) {
this.corsMaxAge = corsMaxAge;
}
public String getCorsAllowedHeaders() {
return corsAllowedHeaders;
}
public void setCorsAllowedHeaders(String corsAllowedHeaders) {
this.corsAllowedHeaders = corsAllowedHeaders;
}
public String getCorsAllowedMethods() {
return corsAllowedMethods;
}
public void setCorsAllowedMethods(String corsAllowedMethods) {
this.corsAllowedMethods = corsAllowedMethods;
}
public boolean isExposeToken() {
return exposeToken;
}
public void setExposeToken(boolean exposeToken) {
this.exposeToken = exposeToken;
}
public boolean isBearerOnly() {
return bearerOnly;
}
public void setBearerOnly(boolean bearerOnly) {
this.bearerOnly = bearerOnly;
}
public boolean isEnableBasicAuth() {
return enableBasicAuth;
}
public void setEnableBasicAuth(boolean enableBasicAuth) {
this.enableBasicAuth = enableBasicAuth;
}
public Map<String, String> getCredentials() {
return credentials;
}
public void setCredentials(Map<String, String> credentials) {
this.credentials = credentials;
}
public boolean isPublicClient() {
return publicClient;
}
public void setPublicClient(boolean publicClient) {
this.publicClient = publicClient;
}
}
@@ -1,54 +1,54 @@
package org.keycloak.representations.adapters.config;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
/**
* Common Realm Configuration
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@JsonPropertyOrder({"realm", "realm-public-key", "auth-server-url", "ssl-required"})
public class BaseRealmConfig {
@JsonProperty("realm")
protected String realm;
@JsonProperty("realm-public-key")
protected String realmKey;
@JsonProperty("auth-server-url")
protected String authServerUrl;
@JsonProperty("ssl-required")
protected String sslRequired;
public String getSslRequired() {
return sslRequired;
}
public void setSslRequired(String sslRequired) {
this.sslRequired = sslRequired;
}
public String getRealm() {
return realm;
}
public void setRealm(String realm) {
this.realm = realm;
}
public String getRealmKey() {
return realmKey;
}
public void setRealmKey(String realmKey) {
this.realmKey = realmKey;
}
public String getAuthServerUrl() {
return authServerUrl;
}
public void setAuthServerUrl(String authServerUrl) {
this.authServerUrl = authServerUrl;
}
}
package org.keycloak.representations.adapters.config;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
/**
* Common Realm Configuration
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@JsonPropertyOrder({"realm", "realm-public-key", "auth-server-url", "ssl-required"})
public class BaseRealmConfig {
@JsonProperty("realm")
protected String realm;
@JsonProperty("realm-public-key")
protected String realmKey;
@JsonProperty("auth-server-url")
protected String authServerUrl;
@JsonProperty("ssl-required")
protected String sslRequired;
public String getSslRequired() {
return sslRequired;
}
public void setSslRequired(String sslRequired) {
this.sslRequired = sslRequired;
}
public String getRealm() {
return realm;
}
public void setRealm(String realm) {
this.realm = realm;
}
public String getRealmKey() {
return realmKey;
}
public void setRealmKey(String realmKey) {
this.realmKey = realmKey;
}
public String getAuthServerUrl() {
return authServerUrl;
}
public void setAuthServerUrl(String authServerUrl) {
this.authServerUrl = authServerUrl;
}
}
@@ -1,87 +1,87 @@
package org.keycloak.representations.idm;
import java.io.Serializable;
import java.util.Comparator;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class AuthenticationExecutionRepresentation implements Serializable {
private static final long serialVersionUID = 1L;
private String authenticatorConfig;
private String authenticator;
private String flowAlias;
private boolean autheticatorFlow;
private String requirement;
private boolean userSetupAllowed;
private int priority;
public String getAuthenticatorConfig() {
return authenticatorConfig;
}
public void setAuthenticatorConfig(String authenticatorConfig) {
this.authenticatorConfig = authenticatorConfig;
}
public String getAuthenticator() {
return authenticator;
}
public void setAuthenticator(String authenticator) {
this.authenticator = authenticator;
}
public String getRequirement() {
return requirement;
}
public void setRequirement(String requirement) {
this.requirement = requirement;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public boolean isUserSetupAllowed() {
return userSetupAllowed;
}
public void setUserSetupAllowed(boolean userSetupAllowed) {
this.userSetupAllowed = userSetupAllowed;
}
/**
* If this execution is a flow, this is the flowId pointing to an AuthenticationFlowModel
*
* @return
*/
public String getFlowAlias() {
return flowAlias;
}
public void setFlowAlias(String flowId) {
this.flowAlias = flowId;
}
/**
* Is the referenced authenticator a flow?
*
* @return
*/
public boolean isAutheticatorFlow() {
return autheticatorFlow;
}
public void setAutheticatorFlow(boolean autheticatorFlow) {
this.autheticatorFlow = autheticatorFlow;
}
}
package org.keycloak.representations.idm;
import java.io.Serializable;
import java.util.Comparator;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class AuthenticationExecutionRepresentation implements Serializable {
private static final long serialVersionUID = 1L;
private String authenticatorConfig;
private String authenticator;
private String flowAlias;
private boolean autheticatorFlow;
private String requirement;
private boolean userSetupAllowed;
private int priority;
public String getAuthenticatorConfig() {
return authenticatorConfig;
}
public void setAuthenticatorConfig(String authenticatorConfig) {
this.authenticatorConfig = authenticatorConfig;
}
public String getAuthenticator() {
return authenticator;
}
public void setAuthenticator(String authenticator) {
this.authenticator = authenticator;
}
public String getRequirement() {
return requirement;
}
public void setRequirement(String requirement) {
this.requirement = requirement;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public boolean isUserSetupAllowed() {
return userSetupAllowed;
}
public void setUserSetupAllowed(boolean userSetupAllowed) {
this.userSetupAllowed = userSetupAllowed;
}
/**
* If this execution is a flow, this is the flowId pointing to an AuthenticationFlowModel
*
* @return
*/
public String getFlowAlias() {
return flowAlias;
}
public void setFlowAlias(String flowId) {
this.flowAlias = flowId;
}
/**
* Is the referenced authenticator a flow?
*
* @return
*/
public boolean isAutheticatorFlow() {
return autheticatorFlow;
}
public void setAutheticatorFlow(boolean autheticatorFlow) {
this.autheticatorFlow = autheticatorFlow;
}
}
@@ -1,67 +1,67 @@
package org.keycloak.representations.idm;
import java.io.Serializable;
import java.util.List;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class AuthenticationFlowRepresentation implements Serializable {
private static final long serialVersionUID = 1L;
private String alias;
private String description;
private String providerId;
private boolean topLevel;
private boolean builtIn;
protected List<AuthenticationExecutionRepresentation> authenticationExecutions;
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getProviderId() {
return providerId;
}
public void setProviderId(String providerId) {
this.providerId = providerId;
}
public boolean isTopLevel() {
return topLevel;
}
public void setTopLevel(boolean topLevel) {
this.topLevel = topLevel;
}
public boolean isBuiltIn() {
return builtIn;
}
public void setBuiltIn(boolean builtIn) {
this.builtIn = builtIn;
}
public List<AuthenticationExecutionRepresentation> getAuthenticationExecutions() {
return authenticationExecutions;
}
public void setAuthenticationExecutions(List<AuthenticationExecutionRepresentation> authenticationExecutions) {
this.authenticationExecutions = authenticationExecutions;
}
}
package org.keycloak.representations.idm;
import java.io.Serializable;
import java.util.List;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class AuthenticationFlowRepresentation implements Serializable {
private static final long serialVersionUID = 1L;
private String alias;
private String description;
private String providerId;
private boolean topLevel;
private boolean builtIn;
protected List<AuthenticationExecutionRepresentation> authenticationExecutions;
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getProviderId() {
return providerId;
}
public void setProviderId(String providerId) {
this.providerId = providerId;
}
public boolean isTopLevel() {
return topLevel;
}
public void setTopLevel(boolean topLevel) {
this.topLevel = topLevel;
}
public boolean isBuiltIn() {
return builtIn;
}
public void setBuiltIn(boolean builtIn) {
this.builtIn = builtIn;
}
public List<AuthenticationExecutionRepresentation> getAuthenticationExecutions() {
return authenticationExecutions;
}
public void setAuthenticationExecutions(List<AuthenticationExecutionRepresentation> authenticationExecutions) {
this.authenticationExecutions = authenticationExecutions;
}
}
@@ -1,35 +1,35 @@
package org.keycloak.representations.idm;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class AuthenticatorConfigRepresentation implements Serializable {
private static final long serialVersionUID = 1L;
private String alias;
private Map<String, String> config = new HashMap<String, String>();
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public Map<String, String> getConfig() {
return config;
}
public void setConfig(Map<String, String> config) {
this.config = config;
}
}
package org.keycloak.representations.idm;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class AuthenticatorConfigRepresentation implements Serializable {
private static final long serialVersionUID = 1L;
private String alias;
private Map<String, String> config = new HashMap<String, String>();
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public Map<String, String> getConfig() {
return config;
}
public void setConfig(Map<String, String> config) {
this.config = config;
}
}
@@ -1,134 +1,134 @@
package org.keycloak.representations.idm;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ClaimRepresentation {
protected boolean name;
protected boolean username;
protected boolean profile;
protected boolean picture;
protected boolean website;
protected boolean email;
protected boolean gender;
protected boolean locale;
protected boolean address;
protected boolean phone;
public boolean getName() {
return name;
}
public void setName(boolean name) {
this.name = name;
}
public boolean getUsername() {
return username;
}
public void setUsername(boolean username) {
this.username = username;
}
public boolean getProfile() {
return profile;
}
public void setProfile(boolean profile) {
this.profile = profile;
}
public boolean getPicture() {
return picture;
}
public void setPicture(boolean picture) {
this.picture = picture;
}
public boolean getWebsite() {
return website;
}
public void setWebsite(boolean website) {
this.website = website;
}
public boolean getEmail() {
return email;
}
public void setEmail(boolean email) {
this.email = email;
}
public boolean getGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public boolean getLocale() {
return locale;
}
public void setLocale(boolean locale) {
this.locale = locale;
}
public boolean getAddress() {
return address;
}
public void setAddress(boolean address) {
this.address = address;
}
public boolean getPhone() {
return phone;
}
public void setPhone(boolean phone) {
this.phone = phone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ClaimRepresentation that = (ClaimRepresentation) o;
if (address != that.address) return false;
if (email != that.email) return false;
if (gender != that.gender) return false;
if (locale != that.locale) return false;
if (name != that.name) return false;
if (phone != that.phone) return false;
if (picture != that.picture) return false;
if (profile != that.profile) return false;
if (username != that.username) return false;
if (website != that.website) return false;
return true;
}
@Override
public int hashCode() {
int result = (name ? 1 : 0);
result = 31 * result + (username ? 1 : 0);
result = 31 * result + (profile ? 1 : 0);
result = 31 * result + (picture ? 1 : 0);
result = 31 * result + (website ? 1 : 0);
result = 31 * result + (email ? 1 : 0);
result = 31 * result + (gender ? 1 : 0);
result = 31 * result + (locale ? 1 : 0);
result = 31 * result + (address ? 1 : 0);
result = 31 * result + (phone ? 1 : 0);
return result;
}
}
package org.keycloak.representations.idm;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ClaimRepresentation {
protected boolean name;
protected boolean username;
protected boolean profile;
protected boolean picture;
protected boolean website;
protected boolean email;
protected boolean gender;
protected boolean locale;
protected boolean address;
protected boolean phone;
public boolean getName() {
return name;
}
public void setName(boolean name) {
this.name = name;
}
public boolean getUsername() {
return username;
}
public void setUsername(boolean username) {
this.username = username;
}
public boolean getProfile() {
return profile;
}
public void setProfile(boolean profile) {
this.profile = profile;
}
public boolean getPicture() {
return picture;
}
public void setPicture(boolean picture) {
this.picture = picture;
}
public boolean getWebsite() {
return website;
}
public void setWebsite(boolean website) {
this.website = website;
}
public boolean getEmail() {
return email;
}
public void setEmail(boolean email) {
this.email = email;
}
public boolean getGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public boolean getLocale() {
return locale;
}
public void setLocale(boolean locale) {
this.locale = locale;
}
public boolean getAddress() {
return address;
}
public void setAddress(boolean address) {
this.address = address;
}
public boolean getPhone() {
return phone;
}
public void setPhone(boolean phone) {
this.phone = phone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ClaimRepresentation that = (ClaimRepresentation) o;
if (address != that.address) return false;
if (email != that.email) return false;
if (gender != that.gender) return false;
if (locale != that.locale) return false;
if (name != that.name) return false;
if (phone != that.phone) return false;
if (picture != that.picture) return false;
if (profile != that.profile) return false;
if (username != that.username) return false;
if (website != that.website) return false;
return true;
}
@Override
public int hashCode() {
int result = (name ? 1 : 0);
result = 31 * result + (username ? 1 : 0);
result = 31 * result + (profile ? 1 : 0);
result = 31 * result + (picture ? 1 : 0);
result = 31 * result + (website ? 1 : 0);
result = 31 * result + (email ? 1 : 0);
result = 31 * result + (gender ? 1 : 0);
result = 31 * result + (locale ? 1 : 0);
result = 31 * result + (address ? 1 : 0);
result = 31 * result + (phone ? 1 : 0);
return result;
}
}
@@ -1,38 +1,38 @@
package org.keycloak.representations.idm;
import java.util.List;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ClientMappingsRepresentation {
protected String id;
protected String client;
protected List<RoleRepresentation> mappings;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public List<RoleRepresentation> getMappings() {
return mappings;
}
public void setMappings(List<RoleRepresentation> mappings) {
this.mappings = mappings;
}
}
package org.keycloak.representations.idm;
import java.util.List;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ClientMappingsRepresentation {
protected String id;
protected String client;
protected List<RoleRepresentation> mappings;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public List<RoleRepresentation> getMappings() {
return mappings;
}
public void setMappings(List<RoleRepresentation> mappings) {
this.mappings = mappings;
}
}
@@ -1,53 +1,53 @@
package org.keycloak.representations.idm;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ConfigPropertyRepresentation {
protected String name;
protected String label;
protected String helpText;
protected String type;
protected Object defaultValue;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Object getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(Object defaultValue) {
this.defaultValue = defaultValue;
}
public String getHelpText() {
return helpText;
}
public void setHelpText(String helpText) {
this.helpText = helpText;
}
}
package org.keycloak.representations.idm;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ConfigPropertyRepresentation {
protected String name;
protected String label;
protected String helpText;
protected String type;
protected Object defaultValue;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Object getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(Object defaultValue) {
this.defaultValue = defaultValue;
}
public String getHelpText() {
return helpText;
}
public void setHelpText(String helpText) {
this.helpText = helpText;
}
}
@@ -1,83 +1,83 @@
package org.keycloak.representations.idm;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class CredentialRepresentation {
public static final String SECRET = "secret";
public static final String PASSWORD = "password";
public static final String PASSWORD_TOKEN = "password-token";
public static final String TOTP = "totp";
public static final String CLIENT_CERT = "cert";
public static final String KERBEROS = "kerberos";
protected String type;
protected String device;
// Plain-text value of credential (used for example during import from manually created JSON file)
protected String value;
// Value stored in DB (used for example during export/import)
protected String hashedSaltedValue;
protected String salt;
protected Integer hashIterations;
// only used when updating a credential. Might set required action
protected boolean temporary;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDevice() {
return device;
}
public void setDevice(String device) {
this.device = device;
}
public String getHashedSaltedValue() {
return hashedSaltedValue;
}
public void setHashedSaltedValue(String hashedSaltedValue) {
this.hashedSaltedValue = hashedSaltedValue;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public Integer getHashIterations() {
return hashIterations;
}
public void setHashIterations(Integer hashIterations) {
this.hashIterations = hashIterations;
}
public boolean isTemporary() {
return temporary;
}
public void setTemporary(boolean temporary) {
this.temporary = temporary;
}
}
package org.keycloak.representations.idm;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class CredentialRepresentation {
public static final String SECRET = "secret";
public static final String PASSWORD = "password";
public static final String PASSWORD_TOKEN = "password-token";
public static final String TOTP = "totp";
public static final String CLIENT_CERT = "cert";
public static final String KERBEROS = "kerberos";
protected String type;
protected String device;
// Plain-text value of credential (used for example during import from manually created JSON file)
protected String value;
// Value stored in DB (used for example during export/import)
protected String hashedSaltedValue;
protected String salt;
protected Integer hashIterations;
// only used when updating a credential. Might set required action
protected boolean temporary;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDevice() {
return device;
}
public void setDevice(String device) {
this.device = device;
}
public String getHashedSaltedValue() {
return hashedSaltedValue;
}
public void setHashedSaltedValue(String hashedSaltedValue) {
this.hashedSaltedValue = hashedSaltedValue;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public Integer getHashIterations() {
return hashIterations;
}
public void setHashIterations(Integer hashIterations) {
this.hashIterations = hashIterations;
}
public boolean isTemporary() {
return temporary;
}
public void setTemporary(boolean temporary) {
this.temporary = temporary;
}
}
@@ -1,57 +1,57 @@
package org.keycloak.representations.idm;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class IdentityProviderMapperRepresentation {
protected String id;
protected String name;
protected String identityProviderAlias;
protected String identityProviderMapper;
protected Map<String, String> config = new HashMap<String, String>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdentityProviderAlias() {
return identityProviderAlias;
}
public void setIdentityProviderAlias(String identityProviderAlias) {
this.identityProviderAlias = identityProviderAlias;
}
public String getIdentityProviderMapper() {
return identityProviderMapper;
}
public void setIdentityProviderMapper(String identityProviderMapper) {
this.identityProviderMapper = identityProviderMapper;
}
public Map<String, String> getConfig() {
return config;
}
public void setConfig(Map<String, String> config) {
this.config = config;
}
}
package org.keycloak.representations.idm;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class IdentityProviderMapperRepresentation {
protected String id;
protected String name;
protected String identityProviderAlias;
protected String identityProviderMapper;
protected Map<String, String> config = new HashMap<String, String>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdentityProviderAlias() {
return identityProviderAlias;
}
public void setIdentityProviderAlias(String identityProviderAlias) {
this.identityProviderAlias = identityProviderAlias;
}
public String getIdentityProviderMapper() {
return identityProviderMapper;
}
public void setIdentityProviderMapper(String identityProviderMapper) {
this.identityProviderMapper = identityProviderMapper;
}
public Map<String, String> getConfig() {
return config;
}
public void setConfig(Map<String, String> config) {
this.config = config;
}
}
@@ -1,57 +1,57 @@
package org.keycloak.representations.idm;
import java.util.LinkedList;
import java.util.List;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class IdentityProviderMapperTypeRepresentation {
protected String id;
protected String name;
protected String category;
protected String helpText;
protected List<ConfigPropertyRepresentation> properties = new LinkedList<>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getHelpText() {
return helpText;
}
public void setHelpText(String helpText) {
this.helpText = helpText;
}
public List<ConfigPropertyRepresentation> getProperties() {
return properties;
}
public void setProperties(List<ConfigPropertyRepresentation> properties) {
this.properties = properties;
}
}
package org.keycloak.representations.idm;
import java.util.LinkedList;
import java.util.List;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class IdentityProviderMapperTypeRepresentation {
protected String id;
protected String name;
protected String category;
protected String helpText;
protected List<ConfigPropertyRepresentation> properties = new LinkedList<>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getHelpText() {
return helpText;
}
public void setHelpText(String helpText) {
this.helpText = helpText;
}
public List<ConfigPropertyRepresentation> getProperties() {
return properties;
}
public void setProperties(List<ConfigPropertyRepresentation> properties) {
this.properties = properties;
}
}
@@ -1,29 +1,29 @@
package org.keycloak.representations.idm;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class MappingsRepresentation {
protected List<RoleRepresentation> realmMappings;
protected Map<String, ClientMappingsRepresentation> clientMappings;
public List<RoleRepresentation> getRealmMappings() {
return realmMappings;
}
public void setRealmMappings(List<RoleRepresentation> realmMappings) {
this.realmMappings = realmMappings;
}
public Map<String, ClientMappingsRepresentation> getClientMappings() {
return clientMappings;
}
public void setClientMappings(Map<String, ClientMappingsRepresentation> clientMappings) {
this.clientMappings = clientMappings;
}
}
package org.keycloak.representations.idm;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class MappingsRepresentation {
protected List<RoleRepresentation> realmMappings;
protected Map<String, ClientMappingsRepresentation> clientMappings;
public List<RoleRepresentation> getRealmMappings() {
return realmMappings;
}
public void setRealmMappings(List<RoleRepresentation> realmMappings) {
this.realmMappings = realmMappings;
}
public Map<String, ClientMappingsRepresentation> getClientMappings() {
return clientMappings;
}
public void setClientMappings(Map<String, ClientMappingsRepresentation> clientMappings) {
this.clientMappings = clientMappings;
}
}
@@ -1,75 +1,75 @@
package org.keycloak.representations.idm;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ProtocolMapperRepresentation {
protected String id;
protected String name;
protected String protocol;
protected String protocolMapper;
protected boolean consentRequired;
protected String consentText;
protected Map<String, String> config = new HashMap<String, String>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getProtocolMapper() {
return protocolMapper;
}
public void setProtocolMapper(String protocolMapper) {
this.protocolMapper = protocolMapper;
}
public Map<String, String> getConfig() {
return config;
}
public void setConfig(Map<String, String> config) {
this.config = config;
}
public boolean isConsentRequired() {
return consentRequired;
}
public void setConsentRequired(boolean consentRequired) {
this.consentRequired = consentRequired;
}
public String getConsentText() {
return consentText;
}
public void setConsentText(String consentText) {
this.consentText = consentText;
}
}
package org.keycloak.representations.idm;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ProtocolMapperRepresentation {
protected String id;
protected String name;
protected String protocol;
protected String protocolMapper;
protected boolean consentRequired;
protected String consentText;
protected Map<String, String> config = new HashMap<String, String>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getProtocolMapper() {
return protocolMapper;
}
public void setProtocolMapper(String protocolMapper) {
this.protocolMapper = protocolMapper;
}
public Map<String, String> getConfig() {
return config;
}
public void setConfig(Map<String, String> config) {
this.config = config;
}
public boolean isConsentRequired() {
return consentRequired;
}
public void setConsentRequired(boolean consentRequired) {
this.consentRequired = consentRequired;
}
public String getConsentText() {
return consentText;
}
public void setConsentText(String consentText) {
this.consentText = consentText;
}
}
@@ -1,56 +1,56 @@
package org.keycloak.representations.idm;
import java.util.List;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ProtocolMapperTypeRepresentation {
protected String id;
protected String name;
protected String category;
protected String helpText;
protected List<ConfigPropertyRepresentation> properties;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getHelpText() {
return helpText;
}
public void setHelpText(String helpText) {
this.helpText = helpText;
}
public List<ConfigPropertyRepresentation> getProperties() {
return properties;
}
public void setProperties(List<ConfigPropertyRepresentation> properties) {
this.properties = properties;
}
}
package org.keycloak.representations.idm;
import java.util.List;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ProtocolMapperTypeRepresentation {
protected String id;
protected String name;
protected String category;
protected String helpText;
protected List<ConfigPropertyRepresentation> properties;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getHelpText() {
return helpText;
}
public void setHelpText(String helpText) {
this.helpText = helpText;
}
public List<ConfigPropertyRepresentation> getProperties() {
return properties;
}
public void setProperties(List<ConfigPropertyRepresentation> properties) {
this.properties = properties;
}
}
@@ -1,66 +1,66 @@
package org.keycloak.representations.idm;
import java.util.List;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class RealmEventsConfigRepresentation {
protected boolean eventsEnabled;
protected Long eventsExpiration;
protected List<String> eventsListeners;
protected List<String> enabledEventTypes;
protected Boolean adminEventsEnabled;
protected Boolean adminEventsDetailsEnabled;
public boolean isEventsEnabled() {
return eventsEnabled;
}
public void setEventsEnabled(boolean eventsEnabled) {
this.eventsEnabled = eventsEnabled;
}
public Long getEventsExpiration() {
return eventsExpiration;
}
public void setEventsExpiration(Long eventsExpiration) {
this.eventsExpiration = eventsExpiration;
}
public List<String> getEventsListeners() {
return eventsListeners;
}
public void setEventsListeners(List<String> eventsListeners) {
this.eventsListeners = eventsListeners;
}
public List<String> getEnabledEventTypes() {
return enabledEventTypes;
}
public void setEnabledEventTypes(List<String> enabledEventTypes) {
this.enabledEventTypes = enabledEventTypes;
}
public Boolean isAdminEventsEnabled() {
return adminEventsEnabled;
}
public void setAdminEventsEnabled(Boolean adminEventsEnabled) {
this.adminEventsEnabled = adminEventsEnabled;
}
public Boolean isAdminEventsDetailsEnabled() {
return adminEventsDetailsEnabled;
}
public void setAdminEventsDetailsEnabled(Boolean adminEventsDetailsEnabled) {
this.adminEventsDetailsEnabled = adminEventsDetailsEnabled;
}
}
package org.keycloak.representations.idm;
import java.util.List;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class RealmEventsConfigRepresentation {
protected boolean eventsEnabled;
protected Long eventsExpiration;
protected List<String> eventsListeners;
protected List<String> enabledEventTypes;
protected Boolean adminEventsEnabled;
protected Boolean adminEventsDetailsEnabled;
public boolean isEventsEnabled() {
return eventsEnabled;
}
public void setEventsEnabled(boolean eventsEnabled) {
this.eventsEnabled = eventsEnabled;
}
public Long getEventsExpiration() {
return eventsExpiration;
}
public void setEventsExpiration(Long eventsExpiration) {
this.eventsExpiration = eventsExpiration;
}
public List<String> getEventsListeners() {
return eventsListeners;
}
public void setEventsListeners(List<String> eventsListeners) {
this.eventsListeners = eventsListeners;
}
public List<String> getEnabledEventTypes() {
return enabledEventTypes;
}
public void setEnabledEventTypes(List<String> enabledEventTypes) {
this.enabledEventTypes = enabledEventTypes;
}
public Boolean isAdminEventsEnabled() {
return adminEventsEnabled;
}
public void setAdminEventsEnabled(Boolean adminEventsEnabled) {
this.adminEventsEnabled = adminEventsEnabled;
}
public Boolean isAdminEventsDetailsEnabled() {
return adminEventsDetailsEnabled;
}
public void setAdminEventsDetailsEnabled(Boolean adminEventsDetailsEnabled) {
this.adminEventsDetailsEnabled = adminEventsDetailsEnabled;
}
}
File diff suppressed because it is too large. Load diff
@@ -1,98 +1,98 @@
package org.keycloak.representations.idm;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class RoleRepresentation {
protected String id;
protected String name;
protected String description;
protected boolean composite;
protected Composites composites;
public static class Composites {
protected Set<String> realm;
protected Map<String, List<String>> client;
@Deprecated
protected Map<String, List<String>> application;
public Set<String> getRealm() {
return realm;
}
public void setRealm(Set<String> realm) {
this.realm = realm;
}
public Map<String, List<String>> getClient() {
return client;
}
public void setClient(Map<String, List<String>> client) {
this.client = client;
}
@Deprecated
public Map<String, List<String>> getApplication() {
return application;
}
}
public RoleRepresentation() {
}
public RoleRepresentation(String name, String description) {
this.name = name;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Composites getComposites() {
return composites;
}
public void setComposites(Composites composites) {
this.composites = composites;
}
@Override
public String toString() {
return name;
}
public boolean isComposite() {
return composite;
}
public void setComposite(boolean composite) {
this.composite = composite;
}
}
package org.keycloak.representations.idm;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class RoleRepresentation {
protected String id;
protected String name;
protected String description;
protected boolean composite;
protected Composites composites;
public static class Composites {
protected Set<String> realm;
protected Map<String, List<String>> client;
@Deprecated
protected Map<String, List<String>> application;
public Set<String> getRealm() {
return realm;
}
public void setRealm(Set<String> realm) {
this.realm = realm;
}
public Map<String, List<String>> getClient() {
return client;
}
public void setClient(Map<String, List<String>> client) {
this.client = client;
}
@Deprecated
public Map<String, List<String>> getApplication() {
return application;
}
}
public RoleRepresentation() {
}
public RoleRepresentation(String name, String description) {
this.name = name;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Composites getComposites() {
return composites;
}
public void setComposites(Composites composites) {
this.composites = composites;
}
@Override
public String toString() {
return name;
}
public boolean isComposite() {
return composite;
}
public void setComposite(boolean composite) {
this.composite = composite;
}
}
@@ -1,36 +1,36 @@
package org.keycloak.representations.idm;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class RolesRepresentation {
protected List<RoleRepresentation> realm;
protected Map<String, List<RoleRepresentation>> client;
@Deprecated
protected Map<String, List<RoleRepresentation>> application;
public List<RoleRepresentation> getRealm() {
return realm;
}
public void setRealm(List<RoleRepresentation> realm) {
this.realm = realm;
}
public Map<String, List<RoleRepresentation>> getClient() {
return client;
}
public void setClient(Map<String, List<RoleRepresentation>> client) {
this.client = client;
}
@Deprecated
public Map<String, List<RoleRepresentation>> getApplication() {
return application;
}
}
package org.keycloak.representations.idm;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class RolesRepresentation {
protected List<RoleRepresentation> realm;
protected Map<String, List<RoleRepresentation>> client;
@Deprecated
protected Map<String, List<RoleRepresentation>> application;
public List<RoleRepresentation> getRealm() {
return realm;
}
public void setRealm(List<RoleRepresentation> realm) {
this.realm = realm;
}
public Map<String, List<RoleRepresentation>> getClient() {
return client;
}
public void setClient(Map<String, List<RoleRepresentation>> client) {
this.client = client;
}
@Deprecated
public Map<String, List<RoleRepresentation>> getApplication() {
return application;
}
}
@@ -1,76 +1,76 @@
package org.keycloak.representations.idm;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class UserSessionRepresentation {
private String id;
private String username;
private String userId;
private String ipAddress;
private long start;
private long lastAccess;
private Map<String, String> clients = new HashMap<String, String>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public long getStart() {
return start;
}
public void setStart(long start) {
this.start = start;
}
public long getLastAccess() {
return lastAccess;
}
public void setLastAccess(long lastAccess) {
this.lastAccess = lastAccess;
}
public Map<String, String> getClients() {
return clients;
}
public void setClients(Map<String, String> clients) {
this.clients = clients;
}
}
package org.keycloak.representations.idm;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class UserSessionRepresentation {
private String id;
private String username;
private String userId;
private String ipAddress;
private long start;
private long lastAccess;
private Map<String, String> clients = new HashMap<String, String>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public long getStart() {
return start;
}
public void setStart(long start) {
this.start = start;
}
public long getLastAccess() {
return lastAccess;
}
public void setLastAccess(long lastAccess) {
this.lastAccess = lastAccess;
}
public Map<String, String> getClients() {
return clients;
}
public void setClients(Map<String, String> clients) {
this.clients = clients;
}
}
@@ -1,44 +1,44 @@
package org.keycloak.util;
import net.iharder.Base64;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class Base64Url {
public static String encode(byte[] bytes) {
String s = Base64.encodeBytes(bytes);
s = s.split("=")[0]; // Remove any trailing '='s
s = s.replace('+', '-'); // 62nd char of encoding
s = s.replace('/', '_'); // 63rd char of encoding
return s;
}
public static byte[] decode(String s) {
s = s.replace('-', '+'); // 62nd char of encoding
s = s.replace('_', '/'); // 63rd char of encoding
switch (s.length() % 4) // Pad with trailing '='s
{
case 0:
break; // No pad chars in this case
case 2:
s += "==";
break; // Two pad chars
case 3:
s += "=";
break; // One pad char
default:
throw new RuntimeException(
"Illegal base64url string!");
}
try {
return Base64.decode(s);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
package org.keycloak.util;
import net.iharder.Base64;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class Base64Url {
public static String encode(byte[] bytes) {
String s = Base64.encodeBytes(bytes);
s = s.split("=")[0]; // Remove any trailing '='s
s = s.replace('+', '-'); // 62nd char of encoding
s = s.replace('/', '_'); // 63rd char of encoding
return s;
}
public static byte[] decode(String s) {
s = s.replace('-', '+'); // 62nd char of encoding
s = s.replace('_', '/'); // 63rd char of encoding
switch (s.length() % 4) // Pad with trailing '='s
{
case 0:
break; // No pad chars in this case
case 2:
s += "==";
break; // Two pad chars
case 3:
s += "=";
break; // One pad char
default:
throw new RuntimeException(
"Illegal base64url string!");
}
try {
return Base64.decode(s);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -1,44 +1,44 @@
package org.keycloak.util;
import net.iharder.Base64;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class BasicAuthHelper
{
public static String createHeader(String username, String password)
{
StringBuffer buf = new StringBuffer(username);
buf.append(':').append(password);
try
{
return "Basic " + Base64.encodeBytes(buf.toString().getBytes("UTF-8"));
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
}
public static String[] parseHeader(String header)
{
if (header.length() < 6) return null;
String type = header.substring(0, 5);
type = type.toLowerCase();
if (!type.equalsIgnoreCase("Basic")) return null;
String val = header.substring(6);
try {
val = new String(Base64.decode(val.getBytes()));
} catch (IOException e) {
throw new RuntimeException(e);
}
String[] split = val.split(":");
if (split.length != 2) return null;
return split;
}
}
package org.keycloak.util;
import net.iharder.Base64;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class BasicAuthHelper
{
public static String createHeader(String username, String password)
{
StringBuffer buf = new StringBuffer(username);
buf.append(':').append(password);
try
{
return "Basic " + Base64.encodeBytes(buf.toString().getBytes("UTF-8"));
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
}
public static String[] parseHeader(String header)
{
if (header.length() < 6) return null;
String type = header.substring(0, 5);
type = type.toLowerCase();
if (!type.equalsIgnoreCase("Basic")) return null;
String val = header.substring(6);
try {
val = new String(Base64.decode(val.getBytes()));
} catch (IOException e) {
throw new RuntimeException(e);
}
String[] split = val.split(":");
if (split.length != 2) return null;
return split;
}
}
@@ -1,166 +1,166 @@
package org.keycloak.util;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.Date;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509ExtensionUtils;
import org.bouncycastle.cert.X509v1CertificateBuilder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder;
import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder;
import org.bouncycastle.operator.DigestCalculator;
import org.bouncycastle.operator.bc.BcDigestCalculatorProvider;
import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
/**
* The Class CertificateUtils provides utility functions for generation of V1 and V3 {@link java.security.cert.X509Certificate}
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @author <a href="mailto:giriraj.sharma27@gmail.com">Giriraj Sharma</a>
* @version $Revision: 2 $
*/
public class CertificateUtils {
static {
BouncyIntegration.init();
}
/**
* Generates version 3 {@link java.security.cert.X509Certificate}.
*
* @param keyPair the key pair
* @param caPrivateKey the CA private key
* @param caCert the CA certificate
* @param subject the subject name
*
* @return the x509 certificate
*
* @throws Exception the exception
*/
public static X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPrivateKey, X509Certificate caCert,
String subject) throws Exception {
try {
X500Name subjectDN = new X500Name("CN=" + subject);
// Serial Number
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
BigInteger serialNumber = BigInteger.valueOf(Math.abs(random.nextInt()));
// Validity
Date notBefore = new Date(System.currentTimeMillis());
Date notAfter = new Date(System.currentTimeMillis() + (((1000L * 60 * 60 * 24 * 30)) * 12) * 3);
// SubjectPublicKeyInfo
SubjectPublicKeyInfo subjPubKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic()
.getEncoded()));
X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()),
serialNumber, notBefore, notAfter, subjectDN, subjPubKeyInfo);
DigestCalculator digCalc = new BcDigestCalculatorProvider()
.get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);
// Subject Key Identifier
certGen.addExtension(Extension.subjectKeyIdentifier, false,
x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo));
// Authority Key Identifier
certGen.addExtension(Extension.authorityKeyIdentifier, false,
x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo));
// Key Usage
certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign
| KeyUsage.cRLSign));
// Extended Key Usage
KeyPurposeId[] EKU = new KeyPurposeId[2];
EKU[0] = KeyPurposeId.id_kp_emailProtection;
EKU[1] = KeyPurposeId.id_kp_serverAuth;
certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));
// Basic Constraints
certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0));
// Content Signer
ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC").build(caPrivateKey);
// Certificate
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
} catch (Exception e) {
throw new RuntimeException("Error creating X509v3Certificate.", e);
}
}
/**
* Generate version 1 self signed {@link java.security.cert.X509Certificate}..
*
* @param caKeyPair the CA key pair
* @param subject the subject name
*
* @return the x509 certificate
*
* @throws Exception the exception
*/
public static X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject) throws Exception {
try {
X500Name subjectDN = new X500Name("CN=" + subject);
BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis());
Date validityStartDate = new Date(System.currentTimeMillis() - 100000);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, 10);
Date validityEndDate = new Date(calendar.getTime().getTime());
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded());
X509v1CertificateBuilder builder = new X509v1CertificateBuilder(subjectDN, serialNumber, validityStartDate,
validityEndDate, subjectDN, subPubKeyInfo);
X509CertificateHolder holder = builder.build(createSigner(caKeyPair.getPrivate()));
return new JcaX509CertificateConverter().getCertificate(holder);
} catch (Exception e) {
throw new RuntimeException("Error creating X509v1Certificate.", e);
}
}
/**
* Creates the content signer for generation of Version 1 {@link java.security.cert.X509Certificate}.
*
* @param privateKey the private key
*
* @return the content signer
*/
public static ContentSigner createSigner(PrivateKey privateKey) {
try {
AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256WithRSAEncryption");
AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
return new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
.build(PrivateKeyFactory.createKey(privateKey.getEncoded()));
} catch (Exception e) {
throw new RuntimeException("Could not create content signer.", e);
}
}
}
package org.keycloak.util;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.Date;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509ExtensionUtils;
import org.bouncycastle.cert.X509v1CertificateBuilder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder;
import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder;
import org.bouncycastle.operator.DigestCalculator;
import org.bouncycastle.operator.bc.BcDigestCalculatorProvider;
import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
/**
* The Class CertificateUtils provides utility functions for generation of V1 and V3 {@link java.security.cert.X509Certificate}
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @author <a href="mailto:giriraj.sharma27@gmail.com">Giriraj Sharma</a>
* @version $Revision: 2 $
*/
public class CertificateUtils {
static {
BouncyIntegration.init();
}
/**
* Generates version 3 {@link java.security.cert.X509Certificate}.
*
* @param keyPair the key pair
* @param caPrivateKey the CA private key
* @param caCert the CA certificate
* @param subject the subject name
*
* @return the x509 certificate
*
* @throws Exception the exception
*/
public static X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPrivateKey, X509Certificate caCert,
String subject) throws Exception {
try {
X500Name subjectDN = new X500Name("CN=" + subject);
// Serial Number
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
BigInteger serialNumber = BigInteger.valueOf(Math.abs(random.nextInt()));
// Validity
Date notBefore = new Date(System.currentTimeMillis());
Date notAfter = new Date(System.currentTimeMillis() + (((1000L * 60 * 60 * 24 * 30)) * 12) * 3);
// SubjectPublicKeyInfo
SubjectPublicKeyInfo subjPubKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic()
.getEncoded()));
X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()),
serialNumber, notBefore, notAfter, subjectDN, subjPubKeyInfo);
DigestCalculator digCalc = new BcDigestCalculatorProvider()
.get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);
// Subject Key Identifier
certGen.addExtension(Extension.subjectKeyIdentifier, false,
x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo));
// Authority Key Identifier
certGen.addExtension(Extension.authorityKeyIdentifier, false,
x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo));
// Key Usage
certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign
| KeyUsage.cRLSign));
// Extended Key Usage
KeyPurposeId[] EKU = new KeyPurposeId[2];
EKU[0] = KeyPurposeId.id_kp_emailProtection;
EKU[1] = KeyPurposeId.id_kp_serverAuth;
certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));
// Basic Constraints
certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0));
// Content Signer
ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC").build(caPrivateKey);
// Certificate
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
} catch (Exception e) {
throw new RuntimeException("Error creating X509v3Certificate.", e);
}
}
/**
* Generate version 1 self signed {@link java.security.cert.X509Certificate}..
*
* @param caKeyPair the CA key pair
* @param subject the subject name
*
* @return the x509 certificate
*
* @throws Exception the exception
*/
public static X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject) throws Exception {
try {
X500Name subjectDN = new X500Name("CN=" + subject);
BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis());
Date validityStartDate = new Date(System.currentTimeMillis() - 100000);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, 10);
Date validityEndDate = new Date(calendar.getTime().getTime());
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded());
X509v1CertificateBuilder builder = new X509v1CertificateBuilder(subjectDN, serialNumber, validityStartDate,
validityEndDate, subjectDN, subPubKeyInfo);
X509CertificateHolder holder = builder.build(createSigner(caKeyPair.getPrivate()));
return new JcaX509CertificateConverter().getCertificate(holder);
} catch (Exception e) {
throw new RuntimeException("Error creating X509v1Certificate.", e);
}
}
/**
* Creates the content signer for generation of Version 1 {@link java.security.cert.X509Certificate}.
*
* @param privateKey the private key
*
* @return the content signer
*/
public static ContentSigner createSigner(PrivateKey privateKey) {
try {
AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256WithRSAEncryption");
AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
return new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
.build(PrivateKeyFactory.createKey(privateKey.getEncoded()));
} catch (Exception e) {
throw new RuntimeException("Could not create content signer.", e);
}
}
}
@@ -1,37 +1,37 @@
package org.keycloak.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public final class EnvUtil {
private static final Pattern p = Pattern.compile("[$][{]([^}]+)[}]");
private EnvUtil() {
}
/**
* Replaces any ${} strings with their corresponding environent variable.
*
* @param val
* @return
*/
public static String replace(String val) {
Matcher matcher = p.matcher(val);
StringBuffer buf = new StringBuffer();
while (matcher.find()) {
String envVar = matcher.group(1);
String envVal = System.getProperty(envVar);
if (envVal == null) envVal = "NOT-SPECIFIED";
matcher.appendReplacement(buf, envVal.replace("\\", "\\\\"));
}
matcher.appendTail(buf);
return buf.toString();
}
}
package org.keycloak.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public final class EnvUtil {
private static final Pattern p = Pattern.compile("[$][{]([^}]+)[}]");
private EnvUtil() {
}
/**
* Replaces any ${} strings with their corresponding environent variable.
*
* @param val
* @return
*/
public static String replace(String val) {
Matcher matcher = p.matcher(val);
StringBuffer buf = new StringBuffer();
while (matcher.find()) {
String envVar = matcher.group(1);
String envVal = System.getProperty(envVar);
if (envVal == null) envVal = "NOT-SPECIFIED";
matcher.appendReplacement(buf, envVal.replace("\\", "\\\\"));
}
matcher.appendTail(buf);
return buf.toString();
}
}
@@ -1,37 +1,37 @@
package org.keycloak.util;
import org.keycloak.constants.GenericConstants;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class FindFile {
public static InputStream findFile(String keycloakConfigFile) {
if (keycloakConfigFile.startsWith(GenericConstants.PROTOCOL_CLASSPATH)) {
String classPathLocation = keycloakConfigFile.replace(GenericConstants.PROTOCOL_CLASSPATH, "");
// Try current class classloader first
InputStream is = FindFile.class.getClassLoader().getResourceAsStream(classPathLocation);
if (is == null) {
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(classPathLocation);
}
if (is != null) {
return is;
} else {
throw new RuntimeException("Unable to find config from classpath: " + keycloakConfigFile);
}
} else {
// Fallback to file
try {
return new FileInputStream(keycloakConfigFile);
} catch (FileNotFoundException fnfe) {
throw new RuntimeException(fnfe);
}
}
}
}
package org.keycloak.util;
import org.keycloak.constants.GenericConstants;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class FindFile {
public static InputStream findFile(String keycloakConfigFile) {
if (keycloakConfigFile.startsWith(GenericConstants.PROTOCOL_CLASSPATH)) {
String classPathLocation = keycloakConfigFile.replace(GenericConstants.PROTOCOL_CLASSPATH, "");
// Try current class classloader first
InputStream is = FindFile.class.getClassLoader().getResourceAsStream(classPathLocation);
if (is == null) {
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(classPathLocation);
}
if (is != null) {
return is;
} else {
throw new RuntimeException("Unable to find config from classpath: " + keycloakConfigFile);
}
} else {
// Fallback to file
try {
return new FileInputStream(keycloakConfigFile);
} catch (FileNotFoundException fnfe) {
throw new RuntimeException(fnfe);
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,25 +1,25 @@
package org.keycloak.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import org.keycloak.constants.GenericConstants;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class KeystoreUtil {
public static KeyStore loadKeyStore(String filename, String password) throws Exception {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream trustStream = (filename.startsWith(GenericConstants.PROTOCOL_CLASSPATH))
?KeystoreUtil.class.getResourceAsStream(filename.replace(GenericConstants.PROTOCOL_CLASSPATH, ""))
:new FileInputStream(new File(filename));
trustStore.load(trustStream, password.toCharArray());
trustStream.close();
return trustStore;
}
}
package org.keycloak.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import org.keycloak.constants.GenericConstants;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class KeystoreUtil {
public static KeyStore loadKeyStore(String filename, String password) throws Exception {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream trustStream = (filename.startsWith(GenericConstants.PROTOCOL_CLASSPATH))
?KeystoreUtil.class.getResourceAsStream(filename.replace(GenericConstants.PROTOCOL_CLASSPATH, ""))
:new FileInputStream(new File(filename));
trustStore.load(trustStream, password.toCharArray());
trustStream.close();
return trustStore;
}
}
+110 -110
View File
@@ -1,110 +1,110 @@
package org.keycloak.util;
import net.iharder.Base64;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
/**
* Utility classes to extract PublicKey, PrivateKey, and X509Certificate from openssl generated PEM files
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public final class PemUtils {
static {
BouncyIntegration.init();
}
private PemUtils() {
}
public static X509Certificate decodeCertificate(InputStream is) throws Exception {
byte[] der = pemToDer(is);
ByteArrayInputStream bis = new ByteArrayInputStream(der);
return DerUtils.decodeCertificate(bis);
}
public static X509Certificate decodeCertificate(String cert) throws Exception {
byte[] der = pemToDer(cert);
ByteArrayInputStream bis = new ByteArrayInputStream(der);
return DerUtils.decodeCertificate(bis);
}
/**
* Extract a public key from a PEM string
*
* @param pem
* @return
* @throws Exception
*/
public static PublicKey decodePublicKey(String pem) throws Exception {
byte[] der = pemToDer(pem);
return DerUtils.decodePublicKey(der);
}
/**
* Extract a private key that is a PKCS8 pem string (base64 encoded PKCS8)
*
* @param pem
* @return
* @throws Exception
*/
public static PrivateKey decodePrivateKey(String pem) throws Exception {
byte[] der = pemToDer(pem);
return DerUtils.decodePrivateKey(der);
}
public static PrivateKey decodePrivateKey(InputStream is) throws Exception {
String pem = pemFromStream(is);
return decodePrivateKey(pem);
}
/**
* Decode a PEM file to DER format
*
* @param is
* @return
* @throws java.io.IOException
*/
public static byte[] pemToDer(InputStream is) throws IOException {
String pem = pemFromStream(is);
return pemToDer(pem);
}
/**
* Decode a PEM string to DER format
*
* @param pem
* @return
* @throws java.io.IOException
*/
public static byte[] pemToDer(String pem) throws IOException {
pem = removeBeginEnd(pem);
return Base64.decode(pem);
}
public static String removeBeginEnd(String pem) {
pem = pem.replaceAll("-----BEGIN (.*)-----", "");
pem = pem.replaceAll("-----END (.*)----", "");
pem = pem.replaceAll("\r\n", "");
pem = pem.replaceAll("\n", "");
return pem.trim();
}
public static String pemFromStream(InputStream is) throws IOException {
DataInputStream dis = new DataInputStream(is);
byte[] keyBytes = new byte[dis.available()];
dis.readFully(keyBytes);
dis.close();
return new String(keyBytes, "utf-8");
}
}
package org.keycloak.util;
import net.iharder.Base64;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
/**
* Utility classes to extract PublicKey, PrivateKey, and X509Certificate from openssl generated PEM files
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public final class PemUtils {
static {
BouncyIntegration.init();
}
private PemUtils() {
}
public static X509Certificate decodeCertificate(InputStream is) throws Exception {
byte[] der = pemToDer(is);
ByteArrayInputStream bis = new ByteArrayInputStream(der);
return DerUtils.decodeCertificate(bis);
}
public static X509Certificate decodeCertificate(String cert) throws Exception {
byte[] der = pemToDer(cert);
ByteArrayInputStream bis = new ByteArrayInputStream(der);
return DerUtils.decodeCertificate(bis);
}
/**
* Extract a public key from a PEM string
*
* @param pem
* @return
* @throws Exception
*/
public static PublicKey decodePublicKey(String pem) throws Exception {
byte[] der = pemToDer(pem);
return DerUtils.decodePublicKey(der);
}
/**
* Extract a private key that is a PKCS8 pem string (base64 encoded PKCS8)
*
* @param pem
* @return
* @throws Exception
*/
public static PrivateKey decodePrivateKey(String pem) throws Exception {
byte[] der = pemToDer(pem);
return DerUtils.decodePrivateKey(der);
}
public static PrivateKey decodePrivateKey(InputStream is) throws Exception {
String pem = pemFromStream(is);
return decodePrivateKey(pem);
}
/**
* Decode a PEM file to DER format
*
* @param is
* @return
* @throws java.io.IOException
*/
public static byte[] pemToDer(InputStream is) throws IOException {
String pem = pemFromStream(is);
return pemToDer(pem);
}
/**
* Decode a PEM string to DER format
*
* @param pem
* @return
* @throws java.io.IOException
*/
public static byte[] pemToDer(String pem) throws IOException {
pem = removeBeginEnd(pem);
return Base64.decode(pem);
}
public static String removeBeginEnd(String pem) {
pem = pem.replaceAll("-----BEGIN (.*)-----", "");
pem = pem.replaceAll("-----END (.*)----", "");
pem = pem.replaceAll("\r\n", "");
pem = pem.replaceAll("\n", "");
return pem.trim();
}
public static String pemFromStream(InputStream is) throws IOException {
DataInputStream dis = new DataInputStream(is);
byte[] keyBytes = new byte[dis.available()];
dis.readFully(keyBytes);
dis.close();
return new String(keyBytes, "utf-8");
}
}
@@ -1,35 +1,35 @@
package org.keycloak.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public final class StreamUtil {
private StreamUtil() {
}
public static String readString(InputStream in) throws IOException
{
char[] buffer = new char[1024];
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int wasRead;
do
{
wasRead = reader.read(buffer, 0, 1024);
if (wasRead > 0)
{
builder.append(buffer, 0, wasRead);
}
}
while (wasRead > -1);
return builder.toString();
}
}
package org.keycloak.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public final class StreamUtil {
private StreamUtil() {
}
public static String readString(InputStream in) throws IOException
{
char[] buffer = new char[1024];
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int wasRead;
do
{
wasRead = reader.read(buffer, 0, 1024);
if (wasRead > 0)
{
builder.append(buffer, 0, wasRead);
}
}
while (wasRead > -1);
return builder.toString();
}
}
@@ -1,2 +1,2 @@
version=${project.version}
version=${project.version}
build-time=${timestamp}
@@ -1,231 +1,231 @@
package org.keycloak;
import junit.framework.Assert;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.x509.X509V1CertificateGenerator;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.keycloak.jose.jws.JWSBuilder;
import org.keycloak.representations.AccessToken;
import org.keycloak.util.Time;
import javax.security.auth.x500.X500Principal;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.Security;
import java.security.SignatureException;
import java.security.cert.X509Certificate;
import java.util.Date;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class RSAVerifierTest {
private static X509Certificate[] idpCertificates;
private static KeyPair idpPair;
private static KeyPair badPair;
private static KeyPair clientPair;
private static X509Certificate[] clientCertificateChain;
private AccessToken token;
static {
if (Security.getProvider("BC") == null) Security.addProvider(new BouncyCastleProvider());
}
public static X509Certificate generateTestCertificate(String subject, String issuer, KeyPair pair) throws InvalidKeyException,
NoSuchProviderException, SignatureException {
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setIssuerDN(new X500Principal(issuer));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000));
certGen.setSubjectDN(new X500Principal(subject));
certGen.setPublicKey(pair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}
@BeforeClass
public static void setupCerts() throws NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {
badPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
idpPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
idpCertificates = new X509Certificate[]{generateTestCertificate("CN=IDP", "CN=IDP", idpPair)};
clientPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
clientCertificateChain = new X509Certificate[]{generateTestCertificate("CN=Client", "CN=IDP", idpPair)};
}
@Before
public void initTest() {
token = new AccessToken();
token.subject("CN=Client")
.issuer("http://localhost:8080/auth/realm")
.addAccess("service").addRole("admin");
}
@Test
public void testPemWriter() throws Exception {
PublicKey realmPublicKey = idpPair.getPublic();
StringWriter sw = new StringWriter();
PEMWriter writer = new PEMWriter(sw);
try {
writer.writeObject(realmPublicKey);
writer.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println(sw.toString());
}
@Test
public void testSimpleVerification() throws Exception {
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(idpPair.getPrivate());
AccessToken token = verifySkeletonKeyToken(encoded);
Assert.assertTrue(token.getResourceAccess("service").getRoles().contains("admin"));
Assert.assertEquals("CN=Client", token.getSubject());
}
private AccessToken verifySkeletonKeyToken(String encoded) throws VerificationException {
return RSATokenVerifier.verifyToken(encoded, idpPair.getPublic(), "http://localhost:8080/auth/realm");
}
/*
@Test
public void testSpeed() throws Exception
{
byte[] tokenBytes = JsonSerialization.toByteArray(token, false);
String encoded = new JWSBuilder()
.content(tokenBytes)
.rsa256(idpPair.getPrivate());
long start = System.currentTimeMillis();
int count = 10000;
for (int i = 0; i < count; i++)
{
SkeletonKeyTokenVerification v = RSATokenVerifier.verify(null, encoded, metadata);
}
long end = System.currentTimeMillis() - start;
System.out.println("rate: " + ((double)end/(double)count));
}
*/
@Test
public void testBadSignature() throws Exception {
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(badPair.getPrivate());
AccessToken v = null;
try {
v = verifySkeletonKeyToken(encoded);
Assert.fail();
} catch (VerificationException ignored) {
}
}
@Test
public void testNotBeforeGood() throws Exception {
token.notBefore(Time.currentTime() - 100);
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(idpPair.getPrivate());
AccessToken v = null;
try {
v = verifySkeletonKeyToken(encoded);
} catch (VerificationException ignored) {
throw ignored;
}
}
@Test
public void testNotBeforeBad() throws Exception {
token.notBefore(Time.currentTime() + 100);
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(idpPair.getPrivate());
AccessToken v = null;
try {
v = verifySkeletonKeyToken(encoded);
Assert.fail();
} catch (VerificationException ignored) {
System.out.println(ignored.getMessage());
}
}
@Test
public void testExpirationGood() throws Exception {
token.expiration(Time.currentTime() + 100);
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(idpPair.getPrivate());
AccessToken v = null;
try {
v = verifySkeletonKeyToken(encoded);
} catch (VerificationException ignored) {
throw ignored;
}
}
@Test
public void testExpirationBad() throws Exception {
token.expiration(Time.currentTime() - 100);
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(idpPair.getPrivate());
AccessToken v = null;
try {
v = verifySkeletonKeyToken(encoded);
Assert.fail();
} catch (VerificationException ignored) {
}
}
@Test
public void testTokenAuth() throws Exception {
token = new AccessToken();
token.subject("CN=Client")
.issuer("domain")
.addAccess("service").addRole("admin").verifyCaller(true);
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(idpPair.getPrivate());
AccessToken v = null;
try {
v = verifySkeletonKeyToken(encoded);
} catch (VerificationException ignored) {
}
}
}
package org.keycloak;
import junit.framework.Assert;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.x509.X509V1CertificateGenerator;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.keycloak.jose.jws.JWSBuilder;
import org.keycloak.representations.AccessToken;
import org.keycloak.util.Time;
import javax.security.auth.x500.X500Principal;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.Security;
import java.security.SignatureException;
import java.security.cert.X509Certificate;
import java.util.Date;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class RSAVerifierTest {
private static X509Certificate[] idpCertificates;
private static KeyPair idpPair;
private static KeyPair badPair;
private static KeyPair clientPair;
private static X509Certificate[] clientCertificateChain;
private AccessToken token;
static {
if (Security.getProvider("BC") == null) Security.addProvider(new BouncyCastleProvider());
}
public static X509Certificate generateTestCertificate(String subject, String issuer, KeyPair pair) throws InvalidKeyException,
NoSuchProviderException, SignatureException {
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setIssuerDN(new X500Principal(issuer));
certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000));
certGen.setSubjectDN(new X500Principal(subject));
certGen.setPublicKey(pair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}
@BeforeClass
public static void setupCerts() throws NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {
badPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
idpPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
idpCertificates = new X509Certificate[]{generateTestCertificate("CN=IDP", "CN=IDP", idpPair)};
clientPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
clientCertificateChain = new X509Certificate[]{generateTestCertificate("CN=Client", "CN=IDP", idpPair)};
}
@Before
public void initTest() {
token = new AccessToken();
token.subject("CN=Client")
.issuer("http://localhost:8080/auth/realm")
.addAccess("service").addRole("admin");
}
@Test
public void testPemWriter() throws Exception {
PublicKey realmPublicKey = idpPair.getPublic();
StringWriter sw = new StringWriter();
PEMWriter writer = new PEMWriter(sw);
try {
writer.writeObject(realmPublicKey);
writer.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println(sw.toString());
}
@Test
public void testSimpleVerification() throws Exception {
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(idpPair.getPrivate());
AccessToken token = verifySkeletonKeyToken(encoded);
Assert.assertTrue(token.getResourceAccess("service").getRoles().contains("admin"));
Assert.assertEquals("CN=Client", token.getSubject());
}
private AccessToken verifySkeletonKeyToken(String encoded) throws VerificationException {
return RSATokenVerifier.verifyToken(encoded, idpPair.getPublic(), "http://localhost:8080/auth/realm");
}
/*
@Test
public void testSpeed() throws Exception
{
byte[] tokenBytes = JsonSerialization.toByteArray(token, false);
String encoded = new JWSBuilder()
.content(tokenBytes)
.rsa256(idpPair.getPrivate());
long start = System.currentTimeMillis();
int count = 10000;
for (int i = 0; i < count; i++)
{
SkeletonKeyTokenVerification v = RSATokenVerifier.verify(null, encoded, metadata);
}
long end = System.currentTimeMillis() - start;
System.out.println("rate: " + ((double)end/(double)count));
}
*/
@Test
public void testBadSignature() throws Exception {
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(badPair.getPrivate());
AccessToken v = null;
try {
v = verifySkeletonKeyToken(encoded);
Assert.fail();
} catch (VerificationException ignored) {
}
}
@Test
public void testNotBeforeGood() throws Exception {
token.notBefore(Time.currentTime() - 100);
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(idpPair.getPrivate());
AccessToken v = null;
try {
v = verifySkeletonKeyToken(encoded);
} catch (VerificationException ignored) {
throw ignored;
}
}
@Test
public void testNotBeforeBad() throws Exception {
token.notBefore(Time.currentTime() + 100);
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(idpPair.getPrivate());
AccessToken v = null;
try {
v = verifySkeletonKeyToken(encoded);
Assert.fail();
} catch (VerificationException ignored) {
System.out.println(ignored.getMessage());
}
}
@Test
public void testExpirationGood() throws Exception {
token.expiration(Time.currentTime() + 100);
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(idpPair.getPrivate());
AccessToken v = null;
try {
v = verifySkeletonKeyToken(encoded);
} catch (VerificationException ignored) {
throw ignored;
}
}
@Test
public void testExpirationBad() throws Exception {
token.expiration(Time.currentTime() - 100);
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(idpPair.getPrivate());
AccessToken v = null;
try {
v = verifySkeletonKeyToken(encoded);
Assert.fail();
} catch (VerificationException ignored) {
}
}
@Test
public void testTokenAuth() throws Exception {
token = new AccessToken();
token.subject("CN=Client")
.issuer("domain")
.addAccess("service").addRole("admin").verifyCaller(true);
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(idpPair.getPrivate());
AccessToken v = null;
try {
v = verifySkeletonKeyToken(encoded);
} catch (VerificationException ignored) {
}
}
}
@@ -1,112 +1,112 @@
package org.keycloak;
import org.junit.Assert;
import org.junit.Test;
import org.keycloak.jose.jws.JWSBuilder;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.IDToken;
import org.keycloak.util.JsonSerialization;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class SkeletonKeyTokenTest {
@Test
public void testToken() throws Exception {
AccessToken token = createSimpleToken();
String json = JsonSerialization.writeValueAsString(token);
token = JsonSerialization.readValue(json, AccessToken.class);
Assert.assertEquals("111", token.getId());
AccessToken.Access foo = token.getResourceAccess("foo");
Assert.assertNotNull(foo);
Assert.assertTrue(foo.isUserInRole("admin"));
}
@Test
public void testRSA() throws Exception {
AccessToken token = createSimpleToken();
token.id("111");
token.addAccess("foo").addRole("admin");
token.addAccess("bar").addRole("user");
KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(keyPair.getPrivate());
JWSInput input = new JWSInput(encoded);
token = input.readJsonContent(AccessToken.class);
Assert.assertEquals("111", token.getId());
Assert.assertTrue(RSAProvider.verify(input, keyPair.getPublic()));
}
@Test
public void testSerialization() throws Exception {
AccessToken token = createSimpleToken();
IDToken idToken = new IDToken();
idToken.setEmail("joe@email.cz");
KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(keyPair.getPrivate());
String encodedIdToken = new JWSBuilder()
.jsonContent(idToken)
.rsa256(keyPair.getPrivate());
KeycloakSecurityContext ctx = new KeycloakSecurityContext(encoded, token, encodedIdToken, idToken);
KeycloakPrincipal principal = new KeycloakPrincipal("joe", ctx);
// Serialize
ByteArrayOutputStream bso = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bso);
oos.writeObject(principal);
oos.close();
// Deserialize
byte[] bytes = bso.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
principal = (KeycloakPrincipal)ois.readObject();
ctx = principal.getKeycloakSecurityContext();
token = ctx.getToken();
idToken = ctx.getIdToken();
System.out.println("Size of serialized principal: " + bytes.length);
Assert.assertEquals(encoded, ctx.getTokenString());
Assert.assertEquals(encodedIdToken, ctx.getIdTokenString());
Assert.assertEquals("111", token.getId());
Assert.assertEquals("111", token.getId());
Assert.assertTrue(token.getResourceAccess("foo").isUserInRole("admin"));
Assert.assertTrue(token.getResourceAccess("bar").isUserInRole("user"));
Assert.assertEquals("joe@email.cz", idToken.getEmail());
Assert.assertEquals("acme", ctx.getRealm());
ois.close();
}
private AccessToken createSimpleToken() {
AccessToken token = new AccessToken();
token.id("111");
token.issuer("http://localhost:8080/auth/acme");
token.addAccess("foo").addRole("admin");
token.addAccess("bar").addRole("user");
return token;
}
}
package org.keycloak;
import org.junit.Assert;
import org.junit.Test;
import org.keycloak.jose.jws.JWSBuilder;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.IDToken;
import org.keycloak.util.JsonSerialization;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class SkeletonKeyTokenTest {
@Test
public void testToken() throws Exception {
AccessToken token = createSimpleToken();
String json = JsonSerialization.writeValueAsString(token);
token = JsonSerialization.readValue(json, AccessToken.class);
Assert.assertEquals("111", token.getId());
AccessToken.Access foo = token.getResourceAccess("foo");
Assert.assertNotNull(foo);
Assert.assertTrue(foo.isUserInRole("admin"));
}
@Test
public void testRSA() throws Exception {
AccessToken token = createSimpleToken();
token.id("111");
token.addAccess("foo").addRole("admin");
token.addAccess("bar").addRole("user");
KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(keyPair.getPrivate());
JWSInput input = new JWSInput(encoded);
token = input.readJsonContent(AccessToken.class);
Assert.assertEquals("111", token.getId());
Assert.assertTrue(RSAProvider.verify(input, keyPair.getPublic()));
}
@Test
public void testSerialization() throws Exception {
AccessToken token = createSimpleToken();
IDToken idToken = new IDToken();
idToken.setEmail("joe@email.cz");
KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
String encoded = new JWSBuilder()
.jsonContent(token)
.rsa256(keyPair.getPrivate());
String encodedIdToken = new JWSBuilder()
.jsonContent(idToken)
.rsa256(keyPair.getPrivate());
KeycloakSecurityContext ctx = new KeycloakSecurityContext(encoded, token, encodedIdToken, idToken);
KeycloakPrincipal principal = new KeycloakPrincipal("joe", ctx);
// Serialize
ByteArrayOutputStream bso = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bso);
oos.writeObject(principal);
oos.close();
// Deserialize
byte[] bytes = bso.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
principal = (KeycloakPrincipal)ois.readObject();
ctx = principal.getKeycloakSecurityContext();
token = ctx.getToken();
idToken = ctx.getIdToken();
System.out.println("Size of serialized principal: " + bytes.length);
Assert.assertEquals(encoded, ctx.getTokenString());
Assert.assertEquals(encodedIdToken, ctx.getIdTokenString());
Assert.assertEquals("111", token.getId());
Assert.assertEquals("111", token.getId());
Assert.assertTrue(token.getResourceAccess("foo").isUserInRole("admin"));
Assert.assertTrue(token.getResourceAccess("bar").isUserInRole("user"));
Assert.assertEquals("joe@email.cz", idToken.getEmail());
Assert.assertEquals("acme", ctx.getRealm());
ois.close();
}
private AccessToken createSimpleToken() {
AccessToken token = new AccessToken();
token.id("111");
token.issuer("http://localhost:8080/auth/acme");
token.addAccess("foo").addRole("admin");
token.addAccess("bar").addRole("user");
return token;
}
}