Merge pull request #47 from dBucik/refactor_models

Refactor
pull/1580/head
Dominik František Bučík 2021-11-30 12:37:37 +01:00 committed by GitHub
commit 809e7317bb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
61 changed files with 819 additions and 3752 deletions

View File

@ -14,11 +14,6 @@ CREATE TABLE IF NOT EXISTS access_token (
UNIQUE(token_value) UNIQUE(token_value)
); );
CREATE TABLE IF NOT EXISTS access_token_permissions (
access_token_id BIGINT NOT NULL,
permission_id BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS address ( CREATE TABLE IF NOT EXISTS address (
id BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) PRIMARY KEY, id BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) PRIMARY KEY,
formatted VARCHAR(256), formatted VARCHAR(256),
@ -284,83 +279,6 @@ CREATE TABLE IF NOT EXISTS pairwise_identifier (
sector_identifier VARCHAR(2048) sector_identifier VARCHAR(2048)
); );
CREATE TABLE IF NOT EXISTS resource_set (
id BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) PRIMARY KEY,
name VARCHAR(1024) NOT NULL,
uri VARCHAR(1024),
icon_uri VARCHAR(1024),
rs_type VARCHAR(256),
owner VARCHAR(256) NOT NULL,
client_id VARCHAR(256)
);
CREATE TABLE IF NOT EXISTS resource_set_scope (
owner_id BIGINT NOT NULL,
scope VARCHAR(256) NOT NULL
);
CREATE TABLE IF NOT EXISTS permission_ticket (
id BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) PRIMARY KEY,
ticket VARCHAR(256) NOT NULL,
permission_id BIGINT NOT NULL,
expiration TIMESTAMP
);
CREATE TABLE IF NOT EXISTS permission (
id BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) PRIMARY KEY,
resource_set_id BIGINT
);
CREATE TABLE IF NOT EXISTS permission_scope (
owner_id BIGINT NOT NULL,
scope VARCHAR(256) NOT NULL
);
CREATE TABLE IF NOT EXISTS claim (
id BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) PRIMARY KEY,
name VARCHAR(256),
friendly_name VARCHAR(1024),
claim_type VARCHAR(1024),
claim_value VARCHAR(1024)
);
CREATE TABLE IF NOT EXISTS claim_to_policy (
policy_id BIGINT NOT NULL,
claim_id BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS claim_to_permission_ticket (
permission_ticket_id BIGINT NOT NULL,
claim_id BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS policy (
id BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) PRIMARY KEY,
name VARCHAR(1024),
resource_set_id BIGINT
);
CREATE TABLE IF NOT EXISTS policy_scope (
owner_id BIGINT NOT NULL,
scope VARCHAR(256) NOT NULL
);
CREATE TABLE IF NOT EXISTS claim_token_format (
owner_id BIGINT NOT NULL,
claim_token_format VARCHAR(1024)
);
CREATE TABLE IF NOT EXISTS claim_issuer (
owner_id BIGINT NOT NULL,
issuer VARCHAR(1024)
);
CREATE TABLE IF NOT EXISTS saved_registered_client (
id BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) PRIMARY KEY,
issuer VARCHAR(1024),
registered_client VARCHAR(8192)
);
CREATE TABLE IF NOT EXISTS device_code ( CREATE TABLE IF NOT EXISTS device_code (
id BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) PRIMARY KEY, id BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) PRIMARY KEY,
device_code VARCHAR(1024), device_code VARCHAR(1024),

View File

@ -13,11 +13,6 @@ CREATE TABLE IF NOT EXISTS access_token (
approved_site_id BIGINT approved_site_id BIGINT
); );
CREATE TABLE IF NOT EXISTS access_token_permissions (
access_token_id BIGINT NOT NULL,
permission_id BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS address ( CREATE TABLE IF NOT EXISTS address (
id BIGINT AUTO_INCREMENT PRIMARY KEY, id BIGINT AUTO_INCREMENT PRIMARY KEY,
formatted VARCHAR(256), formatted VARCHAR(256),
@ -87,7 +82,7 @@ CREATE TABLE IF NOT EXISTS saved_user_auth (
id BIGINT AUTO_INCREMENT PRIMARY KEY, id BIGINT AUTO_INCREMENT PRIMARY KEY,
acr VARCHAR(1024), acr VARCHAR(1024),
name VARCHAR(1024), name VARCHAR(1024),
authenticated BOOLEAN, authenticated BOOLEAN
); );
CREATE TABLE IF NOT EXISTS saved_user_auth_authority ( CREATE TABLE IF NOT EXISTS saved_user_auth_authority (
@ -283,83 +278,6 @@ CREATE TABLE IF NOT EXISTS pairwise_identifier (
sector_identifier VARCHAR(2048) sector_identifier VARCHAR(2048)
); );
CREATE TABLE IF NOT EXISTS resource_set (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(1024) NOT NULL,
uri VARCHAR(1024),
icon_uri VARCHAR(1024),
rs_type VARCHAR(256),
owner VARCHAR(256) NOT NULL,
client_id VARCHAR(256)
);
CREATE TABLE IF NOT EXISTS resource_set_scope (
owner_id BIGINT NOT NULL,
scope VARCHAR(256) NOT NULL
);
CREATE TABLE IF NOT EXISTS permission_ticket (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
ticket VARCHAR(256) NOT NULL,
permission_id BIGINT NOT NULL,
expiration TIMESTAMP NULL
);
CREATE TABLE IF NOT EXISTS permission (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
resource_set_id BIGINT
);
CREATE TABLE IF NOT EXISTS permission_scope (
owner_id BIGINT NOT NULL,
scope VARCHAR(256) NOT NULL
);
CREATE TABLE IF NOT EXISTS claim (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(256),
friendly_name VARCHAR(1024),
claim_type VARCHAR(1024),
claim_value VARCHAR(1024)
);
CREATE TABLE IF NOT EXISTS claim_to_policy (
policy_id BIGINT NOT NULL,
claim_id BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS claim_to_permission_ticket (
permission_ticket_id BIGINT NOT NULL,
claim_id BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS policy (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(1024),
resource_set_id BIGINT
);
CREATE TABLE IF NOT EXISTS policy_scope (
owner_id BIGINT NOT NULL,
scope VARCHAR(256) NOT NULL
);
CREATE TABLE IF NOT EXISTS claim_token_format (
owner_id BIGINT NOT NULL,
claim_token_format VARCHAR(1024)
);
CREATE TABLE IF NOT EXISTS claim_issuer (
owner_id BIGINT NOT NULL,
issuer VARCHAR(1024)
);
CREATE TABLE IF NOT EXISTS saved_registered_client (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
issuer VARCHAR(1024),
registered_client VARCHAR(8192)
);
CREATE TABLE IF NOT EXISTS device_code ( CREATE TABLE IF NOT EXISTS device_code (
id BIGINT AUTO_INCREMENT PRIMARY KEY, id BIGINT AUTO_INCREMENT PRIMARY KEY,
device_code VARCHAR(1024), device_code VARCHAR(1024),

View File

@ -14,11 +14,6 @@ CREATE TABLE IF NOT EXISTS access_token (
UNIQUE(token_value) UNIQUE(token_value)
); );
CREATE TABLE IF NOT EXISTS access_token_permissions (
access_token_id BIGINT NOT NULL,
permission_id BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS address ( CREATE TABLE IF NOT EXISTS address (
id BIGSERIAL PRIMARY KEY, id BIGSERIAL PRIMARY KEY,
formatted VARCHAR(256), formatted VARCHAR(256),
@ -88,7 +83,7 @@ CREATE TABLE IF NOT EXISTS saved_user_auth (
id BIGSERIAL PRIMARY KEY, id BIGSERIAL PRIMARY KEY,
acr VARCHAR(1024), acr VARCHAR(1024),
name VARCHAR(1024), name VARCHAR(1024),
authenticated BOOLEAN, authenticated BOOLEAN
); );
CREATE TABLE IF NOT EXISTS saved_user_auth_authority ( CREATE TABLE IF NOT EXISTS saved_user_auth_authority (
@ -284,83 +279,6 @@ CREATE TABLE IF NOT EXISTS pairwise_identifier (
sector_identifier VARCHAR(2048) sector_identifier VARCHAR(2048)
); );
CREATE TABLE IF NOT EXISTS resource_set (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(1024) NOT NULL,
uri VARCHAR(1024),
icon_uri VARCHAR(1024),
rs_type VARCHAR(256),
owner VARCHAR(256) NOT NULL,
client_id VARCHAR(256)
);
CREATE TABLE IF NOT EXISTS resource_set_scope (
owner_id BIGINT NOT NULL,
scope VARCHAR(256) NOT NULL
);
CREATE TABLE IF NOT EXISTS permission_ticket (
id BIGSERIAL PRIMARY KEY,
ticket VARCHAR(256) NOT NULL,
permission_id BIGINT NOT NULL,
expiration TIMESTAMP
);
CREATE TABLE IF NOT EXISTS permission (
id BIGSERIAL PRIMARY KEY,
resource_set_id BIGINT
);
CREATE TABLE IF NOT EXISTS permission_scope (
owner_id BIGINT NOT NULL,
scope VARCHAR(256) NOT NULL
);
CREATE TABLE IF NOT EXISTS claim (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(256),
friendly_name VARCHAR(1024),
claim_type VARCHAR(1024),
claim_value VARCHAR(1024)
);
CREATE TABLE IF NOT EXISTS claim_to_policy (
policy_id BIGINT NOT NULL,
claim_id BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS claim_to_permission_ticket (
permission_ticket_id BIGINT NOT NULL,
claim_id BIGINT NOT NULL
);
CREATE TABLE IF NOT EXISTS policy (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(1024),
resource_set_id BIGINT
);
CREATE TABLE IF NOT EXISTS policy_scope (
owner_id BIGINT NOT NULL,
scope VARCHAR(256) NOT NULL
);
CREATE TABLE IF NOT EXISTS claim_token_format (
owner_id BIGINT NOT NULL,
claim_token_format VARCHAR(1024)
);
CREATE TABLE IF NOT EXISTS claim_issuer (
owner_id BIGINT NOT NULL,
issuer VARCHAR(1024)
);
CREATE TABLE IF NOT EXISTS saved_registered_client (
id BIGSERIAL PRIMARY KEY,
issuer VARCHAR(1024),
registered_client VARCHAR(8192)
);
CREATE TABLE IF NOT EXISTS device_code ( CREATE TABLE IF NOT EXISTS device_code (
id BIGSERIAL PRIMARY KEY, id BIGSERIAL PRIMARY KEY,
device_code VARCHAR(1024), device_code VARCHAR(1024),
@ -381,4 +299,3 @@ CREATE TABLE IF NOT EXISTS device_code_request_parameter (
param VARCHAR(2048), param VARCHAR(2048),
val VARCHAR(2048) val VARCHAR(2048)
); );

View File

@ -20,6 +20,10 @@
*/ */
package cz.muni.ics.oauth2.model; package cz.muni.ics.oauth2.model;
import static cz.muni.ics.oauth2.model.ClientDetailsEntity.PARAM_CLIENT_ID;
import static cz.muni.ics.oauth2.model.ClientDetailsEntity.QUERY_ALL;
import static cz.muni.ics.oauth2.model.ClientDetailsEntity.QUERY_BY_CLIENT_ID;
import com.nimbusds.jose.EncryptionMethod; import com.nimbusds.jose.EncryptionMethod;
import com.nimbusds.jose.JWEAlgorithm; import com.nimbusds.jose.JWEAlgorithm;
import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSAlgorithm;
@ -32,12 +36,14 @@ import cz.muni.ics.oauth2.model.convert.JWSAlgorithmStringConverter;
import cz.muni.ics.oauth2.model.convert.JWTStringConverter; import cz.muni.ics.oauth2.model.convert.JWTStringConverter;
import cz.muni.ics.oauth2.model.convert.PKCEAlgorithmStringConverter; import cz.muni.ics.oauth2.model.convert.PKCEAlgorithmStringConverter;
import cz.muni.ics.oauth2.model.convert.SimpleGrantedAuthorityStringConverter; import cz.muni.ics.oauth2.model.convert.SimpleGrantedAuthorityStringConverter;
import cz.muni.ics.oauth2.model.enums.AppType;
import cz.muni.ics.oauth2.model.enums.AuthMethod;
import cz.muni.ics.oauth2.model.enums.SubjectType;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.CollectionTable; import javax.persistence.CollectionTable;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Convert; import javax.persistence.Convert;
@ -58,6 +64,13 @@ import javax.persistence.Table;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
import javax.persistence.Transient; import javax.persistence.Transient;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.eclipse.persistence.annotations.CascadeOnDelete;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails; import org.springframework.security.oauth2.provider.ClientDetails;
@ -65,11 +78,21 @@ import org.springframework.security.oauth2.provider.ClientDetails;
* @author jricher * @author jricher
* *
*/ */
@Getter
@Setter
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
// DB ANNOTATIONS
@Entity @Entity
@Table(name = "client_details") @Table(name = "client_details")
@NamedQueries({ @NamedQueries({
@NamedQuery(name = ClientDetailsEntity.QUERY_ALL, query = "SELECT c FROM ClientDetailsEntity c"), @NamedQuery(name = QUERY_ALL,
@NamedQuery(name = ClientDetailsEntity.QUERY_BY_CLIENT_ID, query = "select c from ClientDetailsEntity c where c.clientId = :" + ClientDetailsEntity.PARAM_CLIENT_ID) query = "SELECT c FROM ClientDetailsEntity c"),
@NamedQuery(name = QUERY_BY_CLIENT_ID,
query = "SELECT c FROM ClientDetailsEntity c " +
"WHERE c.clientId = :" + PARAM_CLIENT_ID)
}) })
public class ClientDetailsEntity implements ClientDetails { public class ClientDetailsEntity implements ClientDetails {
@ -82,142 +105,206 @@ public class ClientDetailsEntity implements ClientDetails {
private static final long serialVersionUID = -1617727085733786296L; private static final long serialVersionUID = -1617727085733786296L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id; private Long id;
private String clientId = null;
private String clientSecret = null; @Column(name = "client_name")
private Set<String> redirectUris = new HashSet<>();
private String clientName; private String clientName;
private String clientUri;
private Set<String> contacts; @Column(name = "client_description")
private String tosUri;
private AuthMethod tokenEndpointAuthMethod = AuthMethod.SECRET_BASIC;
private Set<String> scope = new HashSet<>();
private Set<String> grantTypes = new HashSet<>();
private Set<String> responseTypes = new HashSet<>();
private String policyUri;
private String jwksUri;
private JWKSet jwks;
private String softwareId;
private String softwareVersion;
private AppType applicationType;
private String sectorIdentifierUri;
private SubjectType subjectType;
private JWSAlgorithm requestObjectSigningAlg = null;
private JWSAlgorithm userInfoSignedResponseAlg = null;
private JWEAlgorithm userInfoEncryptedResponseAlg = null;
private EncryptionMethod userInfoEncryptedResponseEnc = null;
private JWSAlgorithm idTokenSignedResponseAlg = null;
private JWEAlgorithm idTokenEncryptedResponseAlg = null;
private EncryptionMethod idTokenEncryptedResponseEnc = null;
private JWSAlgorithm tokenEndpointAuthSigningAlg = null;
private Integer defaultMaxAge;
private Boolean requireAuthTime;
private Set<String> defaultACRvalues;
private String initiateLoginUri;
private Set<String> postLogoutRedirectUris;
private Set<String> requestUris;
private Set<GrantedAuthority> authorities = new HashSet<>();
private Integer accessTokenValiditySeconds = 0;
private Integer refreshTokenValiditySeconds = 0;
private Set<String> resourceIds = new HashSet<>();
private Map<String, Object> additionalInformation = new HashMap<>();
private String clientDescription = ""; private String clientDescription = "";
@Column(name = "client_id")
private String clientId = null;
@Column(name = "client_secret")
private String clientSecret = null;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "client_redirect_uri", joinColumns = @JoinColumn(name = "owner_id"))
@Column(name = "redirect_uri")
@CascadeOnDelete
private Set<String> redirectUris = new HashSet<>();
@Column(name = "client_uri")
private String clientUri;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "client_contact", joinColumns = @JoinColumn(name = "owner_id"))
@Column(name = "contact")
@CascadeOnDelete
private Set<String> contacts = new HashSet<>();
@Column(name = "tos_uri")
private String tosUri;
@Enumerated(EnumType.STRING)
@Column(name = "token_endpoint_auth_method")
private AuthMethod tokenEndpointAuthMethod = AuthMethod.SECRET_BASIC;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "client_scope", joinColumns = @JoinColumn(name = "owner_id"))
@Column(name = "scope")
@CascadeOnDelete
private Set<String> scope = new HashSet<>();
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "client_grant_type", joinColumns = @JoinColumn(name = "owner_id"))
@Column(name = "grant_type")
@CascadeOnDelete
private Set<String> grantTypes = new HashSet<>();
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "client_response_type", joinColumns = @JoinColumn(name = "owner_id"))
@Column(name = "response_type")
@CascadeOnDelete
private Set<String> responseTypes = new HashSet<>();
@Column(name = "policy_uri")
private String policyUri;
@Column(name = "jwks_uri")
private String jwksUri;
@Column(name = "jwks")
@Convert(converter = JWKSetStringConverter.class)
private JWKSet jwks;
@Column(name = "software_id")
private String softwareId;
@Column(name = "software_version")
private String softwareVersion;
@Enumerated(EnumType.STRING)
@Column(name = "application_type")
private AppType applicationType;
@Column(name = "sector_identifier_uri")
private String sectorIdentifierUri;
@Enumerated(EnumType.STRING)
@Column(name = "subject_type")
private SubjectType subjectType;
@Column(name = "request_object_signing_alg")
@Convert(converter = JWSAlgorithmStringConverter.class)
private JWSAlgorithm requestObjectSigningAlg = null;
@Column(name = "user_info_signed_response_alg")
@Convert(converter = JWSAlgorithmStringConverter.class)
private JWSAlgorithm userInfoSignedResponseAlg = null;
@Column(name = "user_info_encrypted_response_alg")
@Convert(converter = JWEAlgorithmStringConverter.class)
private JWEAlgorithm userInfoEncryptedResponseAlg = null;
@Column(name = "user_info_encrypted_response_enc")
@Convert(converter = JWEEncryptionMethodStringConverter.class)
private EncryptionMethod userInfoEncryptedResponseEnc = null;
@Column(name = "id_token_signed_response_alg")
@Convert(converter = JWSAlgorithmStringConverter.class)
private JWSAlgorithm idTokenSignedResponseAlg = null;
@Column(name = "id_token_encrypted_response_alg")
@Convert(converter = JWEAlgorithmStringConverter.class)
private JWEAlgorithm idTokenEncryptedResponseAlg = null;
@Column(name = "id_token_encrypted_response_enc")
@Convert(converter = JWEEncryptionMethodStringConverter.class)
private EncryptionMethod idTokenEncryptedResponseEnc = null;
@Column(name = "token_endpoint_auth_signing_alg")
@Convert(converter = JWSAlgorithmStringConverter.class)
private JWSAlgorithm tokenEndpointAuthSigningAlg = null;
@Column(name = "default_max_age")
private Integer defaultMaxAge;
@Column(name = "require_auth_time")
private Boolean requireAuthTime;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "client_default_acr_value", joinColumns = @JoinColumn(name = "owner_id"))
@Column(name = "default_acr_value")
@CascadeOnDelete
private Set<String> defaultACRvalues;
@Column(name = "initiate_login_uri")
private String initiateLoginUri;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "client_post_logout_redirect_uri", joinColumns = @JoinColumn(name = "owner_id"))
@Column(name = "post_logout_redirect_uri")
@CascadeOnDelete
private Set<String> postLogoutRedirectUris = new HashSet<>();
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "client_request_uri", joinColumns = @JoinColumn(name = "owner_id"))
@Column(name = "request_uri")
@CascadeOnDelete
private Set<String> requestUris = new HashSet<>();;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "client_authority", joinColumns = @JoinColumn(name = "owner_id"))
@Convert(converter = SimpleGrantedAuthorityStringConverter.class)
@Column(name = "authority")
@CascadeOnDelete
private Set<GrantedAuthority> authorities = new HashSet<>();
@Column(name = "access_token_validity_seconds")
private Integer accessTokenValiditySeconds = 0;
@Column(name = "refresh_token_validity_seconds")
private Integer refreshTokenValiditySeconds = 0;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "client_resource", joinColumns = @JoinColumn(name = "owner_id"))
@Column(name = "resource_id")
@CascadeOnDelete
private Set<String> resourceIds = new HashSet<>();
@Column(name = "reuse_refresh_tokens")
private boolean reuseRefreshToken = true; private boolean reuseRefreshToken = true;
@Column(name = "dynamically_registered")
private boolean dynamicallyRegistered = false; private boolean dynamicallyRegistered = false;
@Column(name = "allow_introspection")
private boolean allowIntrospection = false; private boolean allowIntrospection = false;
private Integer idTokenValiditySeconds;
@Column(name = "id_token_validity_seconds")
private Integer idTokenValiditySeconds = DEFAULT_ID_TOKEN_VALIDITY_SECONDS;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_at")
private Date createdAt; private Date createdAt;
@Column(name = "clear_access_tokens_on_refresh")
private boolean clearAccessTokensOnRefresh = true; private boolean clearAccessTokensOnRefresh = true;
private Integer deviceCodeValiditySeconds;
private Set<String> claimsRedirectUris; @Column(name = "device_code_validity_seconds")
private Integer deviceCodeValiditySeconds = 0;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "client_claims_redirect_uri", joinColumns = @JoinColumn(name = "owner_id"))
@Column(name = "redirect_uri")
@CascadeOnDelete
private Set<String> claimsRedirectUris = new HashSet<>();
@Column(name = "software_statement")
@Convert(converter = JWTStringConverter.class)
private JWT softwareStatement; private JWT softwareStatement;
@Column(name = "code_challenge_method")
@Convert(converter = PKCEAlgorithmStringConverter.class)
private PKCEAlgorithm codeChallengeMethod; private PKCEAlgorithm codeChallengeMethod;
public enum AuthMethod { @Transient
SECRET_POST("client_secret_post"), private Map<String, Object> additionalInformation = new HashMap<>();
SECRET_BASIC("client_secret_basic"),
SECRET_JWT("client_secret_jwt"),
PRIVATE_KEY("private_key_jwt"),
NONE("none");
private final String value;
// map to aid reverse lookup
private static final Map<String, AuthMethod> lookup = new HashMap<>();
static {
for (AuthMethod a : AuthMethod.values()) {
lookup.put(a.getValue(), a);
}
}
AuthMethod(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static AuthMethod getByValue(String value) {
return lookup.get(value);
}
}
public enum AppType {
WEB("web"), NATIVE("native");
private final String value;
// map to aid reverse lookup
private static final Map<String, AppType> lookup = new HashMap<>();
static {
for (AppType a : AppType.values()) {
lookup.put(a.getValue(), a);
}
}
AppType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static AppType getByValue(String value) {
return lookup.get(value);
}
}
public enum SubjectType {
PAIRWISE("pairwise"), PUBLIC("public");
private final String value;
// map to aid reverse lookup
private static final Map<String, SubjectType> lookup = new HashMap<>();
static {
for (SubjectType u : SubjectType.values()) {
lookup.put(u.getValue(), u);
}
}
SubjectType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static SubjectType getByValue(String value) {
return lookup.get(value);
}
}
public ClientDetailsEntity() {
}
@PrePersist @PrePersist
@PreUpdate @PreUpdate
@ -227,74 +314,44 @@ public class ClientDetailsEntity implements ClientDetails {
} }
} }
@Id @Override
@GeneratedValue(strategy = GenerationType.IDENTITY) public String getClientId() {
@Column(name = "id") return clientId;
public Long getId() {
return id;
} }
public void setId(Long id) { @Override
this.id = id; public String getClientSecret() {
return clientSecret;
} }
@Basic @Override
@Column(name="client_description") public Set<String> getScope() {
public String getClientDescription() { return scope;
return clientDescription;
} }
public void setClientDescription(String clientDescription) { @Override
this.clientDescription = clientDescription; public Set<GrantedAuthority> getAuthorities() {
return authorities;
} }
@Transient @Override
public boolean isAllowRefresh() { public Integer getAccessTokenValiditySeconds() {
if (grantTypes != null) { return accessTokenValiditySeconds;
return getAuthorizedGrantTypes().contains("refresh_token");
} else {
return false; // if there are no grants, we can't be refreshing them, can we?
}
} }
@Basic @Override
@Column(name="reuse_refresh_tokens") public Integer getRefreshTokenValiditySeconds() {
public boolean isReuseRefreshToken() { return refreshTokenValiditySeconds;
return reuseRefreshToken;
} }
public void setReuseRefreshToken(boolean reuseRefreshToken) { @Override
this.reuseRefreshToken = reuseRefreshToken; public Set<String> getResourceIds() {
return resourceIds;
} }
@Basic @Override
@Column(name="id_token_validity_seconds") public boolean isAutoApprove(String scope) {
public Integer getIdTokenValiditySeconds() { return false;
return idTokenValiditySeconds;
}
public void setIdTokenValiditySeconds(Integer idTokenValiditySeconds) {
this.idTokenValiditySeconds = idTokenValiditySeconds;
}
@Basic
@Column(name="dynamically_registered")
public boolean isDynamicallyRegistered() {
return dynamicallyRegistered;
}
public void setDynamicallyRegistered(boolean dynamicallyRegistered) {
this.dynamicallyRegistered = dynamicallyRegistered;
}
@Basic
@Column(name="allow_introspection")
public boolean isAllowIntrospection() {
return allowIntrospection;
}
public void setAllowIntrospection(boolean allowIntrospection) {
this.allowIntrospection = allowIntrospection;
} }
@Override @Override
@ -312,487 +369,31 @@ public class ClientDetailsEntity implements ClientDetails {
return getScope() != null && !getScope().isEmpty(); return getScope() != null && !getScope().isEmpty();
} }
@Basic
@Override
@Column(name="client_id")
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
@Basic
@Override
@Column(name="client_secret")
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="client_scope", joinColumns=@JoinColumn(name="owner_id"))
@Override
@Column(name="scope")
public Set<String> getScope() {
return scope;
}
public void setScope(Set<String> scope) {
this.scope = scope;
}
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="client_grant_type", joinColumns=@JoinColumn(name="owner_id"))
@Column(name="grant_type")
public Set<String> getGrantTypes() {
return grantTypes;
}
public void setGrantTypes(Set<String> grantTypes) {
this.grantTypes = grantTypes;
}
@Override @Override
@Transient @Transient
public Set<String> getAuthorizedGrantTypes() { public Set<String> getAuthorizedGrantTypes() {
return getGrantTypes(); return getGrantTypes();
} }
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="client_authority", joinColumns=@JoinColumn(name="owner_id"))
@Override
@Convert(converter = SimpleGrantedAuthorityStringConverter.class)
@Column(name="authority")
public Set<GrantedAuthority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<GrantedAuthority> authorities) {
this.authorities = authorities;
}
@Override
@Basic
@Column(name="access_token_validity_seconds")
public Integer getAccessTokenValiditySeconds() {
return accessTokenValiditySeconds;
}
public void setAccessTokenValiditySeconds(Integer accessTokenValiditySeconds) {
this.accessTokenValiditySeconds = accessTokenValiditySeconds;
}
@Override
@Basic
@Column(name="refresh_token_validity_seconds")
public Integer getRefreshTokenValiditySeconds() {
return refreshTokenValiditySeconds;
}
public void setRefreshTokenValiditySeconds(Integer refreshTokenValiditySeconds) {
this.refreshTokenValiditySeconds = refreshTokenValiditySeconds;
}
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="client_redirect_uri", joinColumns=@JoinColumn(name="owner_id"))
@Column(name="redirect_uri")
public Set<String> getRedirectUris() {
return redirectUris;
}
public void setRedirectUris(Set<String> redirectUris) {
this.redirectUris = redirectUris;
}
@Override @Override
@Transient @Transient
public Set<String> getRegisteredRedirectUri() { public Set<String> getRegisteredRedirectUri() {
return getRedirectUris(); return getRedirectUris();
} }
@Override
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="client_resource", joinColumns=@JoinColumn(name="owner_id"))
@Column(name="resource_id")
public Set<String> getResourceIds() {
return resourceIds;
}
public void setResourceIds(Set<String> resourceIds) {
this.resourceIds = resourceIds;
}
@Override @Override
@Transient @Transient
public Map<String, Object> getAdditionalInformation() { public Map<String, Object> getAdditionalInformation() {
return this.additionalInformation; return this.additionalInformation;
} }
@Enumerated(EnumType.STRING) @Transient
@Column(name="application_type") public boolean isAllowRefresh() {
public AppType getApplicationType() { if (grantTypes != null) {
return applicationType; return getAuthorizedGrantTypes().contains("refresh_token");
} else {
return false; // if there are no grants, we can't be refreshing them, can we?
} }
public void setApplicationType(AppType applicationType) {
this.applicationType = applicationType;
}
@Basic
@Column(name="client_name")
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
@Enumerated(EnumType.STRING)
@Column(name="token_endpoint_auth_method")
public AuthMethod getTokenEndpointAuthMethod() {
return tokenEndpointAuthMethod;
}
public void setTokenEndpointAuthMethod(AuthMethod tokenEndpointAuthMethod) {
this.tokenEndpointAuthMethod = tokenEndpointAuthMethod;
}
@Enumerated(EnumType.STRING)
@Column(name="subject_type")
public SubjectType getSubjectType() {
return subjectType;
}
public void setSubjectType(SubjectType subjectType) {
this.subjectType = subjectType;
}
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="client_contact", joinColumns=@JoinColumn(name="owner_id"))
@Column(name="contact")
public Set<String> getContacts() {
return contacts;
}
public void setContacts(Set<String> contacts) {
this.contacts = contacts;
}
@Basic
@Column(name="policy_uri")
public String getPolicyUri() {
return policyUri;
}
public void setPolicyUri(String policyUri) {
this.policyUri = policyUri;
}
@Basic
@Column(name="client_uri")
public String getClientUri() {
return clientUri;
}
public void setClientUri(String clientUri) {
this.clientUri = clientUri;
}
@Basic
@Column(name="tos_uri")
public String getTosUri() {
return tosUri;
}
public void setTosUri(String tosUri) {
this.tosUri = tosUri;
}
@Basic
@Column(name="jwks_uri")
public String getJwksUri() {
return jwksUri;
}
public void setJwksUri(String jwksUri) {
this.jwksUri = jwksUri;
}
@Basic
@Column(name="jwks")
@Convert(converter = JWKSetStringConverter.class)
public JWKSet getJwks() {
return jwks;
}
public void setJwks(JWKSet jwks) {
this.jwks = jwks;
}
@Basic
@Column(name="sector_identifier_uri")
public String getSectorIdentifierUri() {
return sectorIdentifierUri;
}
public void setSectorIdentifierUri(String sectorIdentifierUri) {
this.sectorIdentifierUri = sectorIdentifierUri;
}
@Basic
@Column(name = "request_object_signing_alg")
@Convert(converter = JWSAlgorithmStringConverter.class)
public JWSAlgorithm getRequestObjectSigningAlg() {
return requestObjectSigningAlg;
}
public void setRequestObjectSigningAlg(JWSAlgorithm requestObjectSigningAlg) {
this.requestObjectSigningAlg = requestObjectSigningAlg;
}
@Basic
@Column(name = "user_info_signed_response_alg")
@Convert(converter = JWSAlgorithmStringConverter.class)
public JWSAlgorithm getUserInfoSignedResponseAlg() {
return userInfoSignedResponseAlg;
}
public void setUserInfoSignedResponseAlg(JWSAlgorithm userInfoSignedResponseAlg) {
this.userInfoSignedResponseAlg = userInfoSignedResponseAlg;
}
@Basic
@Column(name = "user_info_encrypted_response_alg")
@Convert(converter = JWEAlgorithmStringConverter.class)
public JWEAlgorithm getUserInfoEncryptedResponseAlg() {
return userInfoEncryptedResponseAlg;
}
public void setUserInfoEncryptedResponseAlg(JWEAlgorithm userInfoEncryptedResponseAlg) {
this.userInfoEncryptedResponseAlg = userInfoEncryptedResponseAlg;
}
@Basic
@Column(name = "user_info_encrypted_response_enc")
@Convert(converter = JWEEncryptionMethodStringConverter.class)
public EncryptionMethod getUserInfoEncryptedResponseEnc() {
return userInfoEncryptedResponseEnc;
}
public void setUserInfoEncryptedResponseEnc(EncryptionMethod userInfoEncryptedResponseEnc) {
this.userInfoEncryptedResponseEnc = userInfoEncryptedResponseEnc;
}
@Basic
@Column(name="id_token_signed_response_alg")
@Convert(converter = JWSAlgorithmStringConverter.class)
public JWSAlgorithm getIdTokenSignedResponseAlg() {
return idTokenSignedResponseAlg;
}
public void setIdTokenSignedResponseAlg(JWSAlgorithm idTokenSignedResponseAlg) {
this.idTokenSignedResponseAlg = idTokenSignedResponseAlg;
}
@Basic
@Column(name = "id_token_encrypted_response_alg")
@Convert(converter = JWEAlgorithmStringConverter.class)
public JWEAlgorithm getIdTokenEncryptedResponseAlg() {
return idTokenEncryptedResponseAlg;
}
public void setIdTokenEncryptedResponseAlg(JWEAlgorithm idTokenEncryptedResponseAlg) {
this.idTokenEncryptedResponseAlg = idTokenEncryptedResponseAlg;
}
@Basic
@Column(name = "id_token_encrypted_response_enc")
@Convert(converter = JWEEncryptionMethodStringConverter.class)
public EncryptionMethod getIdTokenEncryptedResponseEnc() {
return idTokenEncryptedResponseEnc;
}
public void setIdTokenEncryptedResponseEnc(EncryptionMethod idTokenEncryptedResponseEnc) {
this.idTokenEncryptedResponseEnc = idTokenEncryptedResponseEnc;
}
@Basic
@Column(name="token_endpoint_auth_signing_alg")
@Convert(converter = JWSAlgorithmStringConverter.class)
public JWSAlgorithm getTokenEndpointAuthSigningAlg() {
return tokenEndpointAuthSigningAlg;
}
public void setTokenEndpointAuthSigningAlg(JWSAlgorithm tokenEndpointAuthSigningAlg) {
this.tokenEndpointAuthSigningAlg = tokenEndpointAuthSigningAlg;
}
@Basic
@Column(name="default_max_age")
public Integer getDefaultMaxAge() {
return defaultMaxAge;
}
public void setDefaultMaxAge(Integer defaultMaxAge) {
this.defaultMaxAge = defaultMaxAge;
}
@Basic
@Column(name="require_auth_time")
public Boolean getRequireAuthTime() {
return requireAuthTime;
}
public void setRequireAuthTime(Boolean requireAuthTime) {
this.requireAuthTime = requireAuthTime;
}
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="client_response_type", joinColumns=@JoinColumn(name="owner_id"))
@Column(name="response_type")
public Set<String> getResponseTypes() {
return responseTypes;
}
public void setResponseTypes(Set<String> responseTypes) {
this.responseTypes = responseTypes;
}
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="client_default_acr_value", joinColumns=@JoinColumn(name="owner_id"))
@Column(name="default_acr_value")
public Set<String> getDefaultACRvalues() {
return defaultACRvalues;
}
public void setDefaultACRvalues(Set<String> defaultACRvalues) {
this.defaultACRvalues = defaultACRvalues;
}
@Basic
@Column(name="initiate_login_uri")
public String getInitiateLoginUri() {
return initiateLoginUri;
}
public void setInitiateLoginUri(String initiateLoginUri) {
this.initiateLoginUri = initiateLoginUri;
}
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="client_post_logout_redirect_uri", joinColumns=@JoinColumn(name="owner_id"))
@Column(name="post_logout_redirect_uri")
public Set<String> getPostLogoutRedirectUris() {
return postLogoutRedirectUris;
}
public void setPostLogoutRedirectUris(Set<String> postLogoutRedirectUri) {
this.postLogoutRedirectUris = postLogoutRedirectUri;
}
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="client_request_uri", joinColumns=@JoinColumn(name="owner_id"))
@Column(name="request_uri")
public Set<String> getRequestUris() {
return requestUris;
}
public void setRequestUris(Set<String> requestUris) {
this.requestUris = requestUris;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name="created_at")
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
@Override
public boolean isAutoApprove(String scope) {
return false;
}
@Basic
@Column(name = "clear_access_tokens_on_refresh")
public boolean isClearAccessTokensOnRefresh() {
return clearAccessTokensOnRefresh;
}
public void setClearAccessTokensOnRefresh(boolean clearAccessTokensOnRefresh) {
this.clearAccessTokensOnRefresh = clearAccessTokensOnRefresh;
}
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name="client_claims_redirect_uri", joinColumns=@JoinColumn(name="owner_id"))
@Column(name="redirect_uri")
public Set<String> getClaimsRedirectUris() {
return claimsRedirectUris;
}
public void setClaimsRedirectUris(Set<String> claimsRedirectUris) {
this.claimsRedirectUris = claimsRedirectUris;
}
@Basic
@Column(name = "software_statement")
@Convert(converter = JWTStringConverter.class)
public JWT getSoftwareStatement() {
return softwareStatement;
}
public void setSoftwareStatement(JWT softwareStatement) {
this.softwareStatement = softwareStatement;
}
@Basic
@Column(name = "code_challenge_method")
@Convert(converter = PKCEAlgorithmStringConverter.class)
public PKCEAlgorithm getCodeChallengeMethod() {
return codeChallengeMethod;
}
public void setCodeChallengeMethod(PKCEAlgorithm codeChallengeMethod) {
this.codeChallengeMethod = codeChallengeMethod;
}
@Basic
@Column(name="device_code_validity_seconds")
public Integer getDeviceCodeValiditySeconds() {
return deviceCodeValiditySeconds;
}
public void setDeviceCodeValiditySeconds(Integer deviceCodeValiditySeconds) {
this.deviceCodeValiditySeconds = deviceCodeValiditySeconds;
}
@Basic
@Column(name="software_id")
public String getSoftwareId() {
return softwareId;
}
public void setSoftwareId(String softwareId) {
this.softwareId = softwareId;
}
@Basic
@Column(name="software_version")
public String getSoftwareVersion() {
return softwareVersion;
}
public void setSoftwareVersion(String softwareVersion) {
this.softwareVersion = softwareVersion;
} }
} }

View File

@ -20,20 +20,29 @@
*/ */
package cz.muni.ics.oauth2.model; package cz.muni.ics.oauth2.model;
import static cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity.*; import static cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity.PARAM_APPROVED_SITE;
import static cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity.PARAM_CLIENT;
import static cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity.PARAM_DATE;
import static cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity.PARAM_NAME;
import static cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity.PARAM_REFRESH_TOKEN;
import static cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity.PARAM_TOKEN_VALUE;
import static cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity.QUERY_ALL;
import static cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity.QUERY_BY_APPROVED_SITE;
import static cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity.QUERY_BY_CLIENT;
import static cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity.QUERY_BY_NAME;
import static cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity.QUERY_BY_REFRESH_TOKEN;
import static cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity.QUERY_BY_TOKEN_VALUE;
import static cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity.QUERY_EXPIRED_BY_DATE;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWT;
import cz.muni.ics.oauth2.model.convert.JWTStringConverter; import cz.muni.ics.oauth2.model.convert.JWTStringConverter;
import cz.muni.ics.openid.connect.model.ApprovedSite; import cz.muni.ics.openid.connect.model.ApprovedSite;
import cz.muni.ics.uma.model.Permission;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable; import javax.persistence.CollectionTable;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Convert; import javax.persistence.Convert;
@ -44,11 +53,9 @@ import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.JoinColumn; import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries; import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table; import javax.persistence.Table;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType; import javax.persistence.TemporalType;
@ -96,9 +103,6 @@ import org.springframework.security.oauth2.common.OAuth2RefreshToken;
@NamedQuery(name = QUERY_BY_APPROVED_SITE, @NamedQuery(name = QUERY_BY_APPROVED_SITE,
query = "SELECT a FROM OAuth2AccessTokenEntity a " + query = "SELECT a FROM OAuth2AccessTokenEntity a " +
"WHERE a.approvedSite = :" + PARAM_APPROVED_SITE), "WHERE a.approvedSite = :" + PARAM_APPROVED_SITE),
@NamedQuery(name = QUERY_BY_RESOURCE_SET,
query = "SELECT a FROM OAuth2AccessTokenEntity a JOIN a.permissions p " +
"WHERE p.resourceSet.id = :" + PARAM_RESOURCE_SET_ID),
@NamedQuery(name = QUERY_BY_NAME, @NamedQuery(name = QUERY_BY_NAME,
query = "SELECT r FROM OAuth2AccessTokenEntity r " + query = "SELECT r FROM OAuth2AccessTokenEntity r " +
"WHERE r.authenticationHolder.userAuth.name = :" + PARAM_NAME) "WHERE r.authenticationHolder.userAuth.name = :" + PARAM_NAME)
@ -160,12 +164,6 @@ public class OAuth2AccessTokenEntity implements OAuth2AccessToken {
@CascadeOnDelete @CascadeOnDelete
private Set<String> scope; private Set<String> scope;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "access_token_permissions", joinColumns = @JoinColumn(name = "access_token_id"),
inverseJoinColumns = @JoinColumn(name = "permission_id"))
@CascadeOnDelete
private Set<Permission> permissions;
@ManyToOne @ManyToOne
@JoinColumn(name = "approved_site_id") @JoinColumn(name = "approved_site_id")
private ApprovedSite approvedSite; private ApprovedSite approvedSite;

View File

@ -26,14 +26,27 @@ import com.nimbusds.jose.JWEAlgorithm;
import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWT;
import cz.muni.ics.oauth2.model.enums.AppType;
import cz.muni.ics.oauth2.model.enums.AuthMethod;
import cz.muni.ics.oauth2.model.enums.SubjectType;
import java.util.Date; import java.util.Date;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
/** /**
* @author jricher * @author jricher
*/ */
@Getter
@Setter
@ToString
@EqualsAndHashCode
@AllArgsConstructor
public class RegisteredClient { public class RegisteredClient {
private String registrationAccessToken; private String registrationAccessToken;
@ -57,14 +70,6 @@ public class RegisteredClient {
this.registrationClientUri = registrationClientUri; this.registrationClientUri = registrationClientUri;
} }
public ClientDetailsEntity getClient() {
return client;
}
public void setClient(ClientDetailsEntity client) {
this.client = client;
}
public String getClientDescription() { public String getClientDescription() {
return client.getClientDescription(); return client.getClientDescription();
} }
@ -201,11 +206,11 @@ public class RegisteredClient {
return client.getAdditionalInformation(); return client.getAdditionalInformation();
} }
public ClientDetailsEntity.AppType getApplicationType() { public AppType getApplicationType() {
return client.getApplicationType(); return client.getApplicationType();
} }
public void setApplicationType(ClientDetailsEntity.AppType applicationType) { public void setApplicationType(AppType applicationType) {
client.setApplicationType(applicationType); client.setApplicationType(applicationType);
} }
@ -217,19 +222,19 @@ public class RegisteredClient {
client.setClientName(clientName); client.setClientName(clientName);
} }
public ClientDetailsEntity.AuthMethod getTokenEndpointAuthMethod() { public AuthMethod getTokenEndpointAuthMethod() {
return client.getTokenEndpointAuthMethod(); return client.getTokenEndpointAuthMethod();
} }
public void setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod tokenEndpointAuthMethod) { public void setTokenEndpointAuthMethod(AuthMethod tokenEndpointAuthMethod) {
client.setTokenEndpointAuthMethod(tokenEndpointAuthMethod); client.setTokenEndpointAuthMethod(tokenEndpointAuthMethod);
} }
public ClientDetailsEntity.SubjectType getSubjectType() { public SubjectType getSubjectType() {
return client.getSubjectType(); return client.getSubjectType();
} }
public void setSubjectType(ClientDetailsEntity.SubjectType subjectType) { public void setSubjectType(SubjectType subjectType) {
client.setSubjectType(subjectType); client.setSubjectType(subjectType);
} }

View File

@ -20,6 +20,8 @@
*/ */
package cz.muni.ics.oauth2.model; package cz.muni.ics.oauth2.model;
import static cz.muni.ics.oauth2.model.SystemScope.*;
import javax.persistence.Basic; import javax.persistence.Basic;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
@ -29,15 +31,31 @@ import javax.persistence.Id;
import javax.persistence.NamedQueries; import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.Table; import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/** /**
* @author jricher * @author jricher
*/ */
@Getter
@Setter
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
// DB ANNOTATIONS
@Entity @Entity
@Table(name = "system_scope") @Table(name = "system_scope")
@NamedQueries({ @NamedQueries({
@NamedQuery(name = SystemScope.QUERY_ALL, query = "select s from SystemScope s ORDER BY s.id"), @NamedQuery(name = QUERY_ALL,
@NamedQuery(name = SystemScope.QUERY_BY_VALUE, query = "select s from SystemScope s WHERE s.value = :" + SystemScope.PARAM_VALUE) query = "SELECT s FROM SystemScope s ORDER BY s.id"),
@NamedQuery(name = QUERY_BY_VALUE,
query = "SELECT s FROM SystemScope s " +
"WHERE s.value = :" + PARAM_VALUE)
}) })
public class SystemScope { public class SystemScope {
@ -46,145 +64,28 @@ public class SystemScope {
public static final String PARAM_VALUE = "value"; public static final String PARAM_VALUE = "value";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id; private Long id;
private String value; // scope value
private String description; // human-readable description
private String icon; // class of the icon to display on the auth page
private boolean defaultScope = false; // is this a default scope for newly-registered clients?
private boolean restricted = false; // is this scope restricted to admin-only registration access?
public SystemScope() { } @Column(name = "scope")
private String value;
@Column(name = "description")
private String description; // human-readable description
@Column(name = "icon")
private String icon; // class of the icon to display on the auth page
@Column(name = "default_scope")
private boolean defaultScope = false; // is this a default scope for newly-registered clients?
@Column(name = "restricted")
private boolean restricted = false; // is this scope restricted to admin-only registration access?
public SystemScope(String value) { public SystemScope(String value) {
this.value = value; this.value = value;
} }
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Basic
@Column(name = "scope")
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Basic
@Column(name = "description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Basic
@Column(name = "icon")
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
@Basic
@Column(name = "default_scope")
public boolean isDefaultScope() {
return defaultScope;
}
public void setDefaultScope(boolean defaultScope) {
this.defaultScope = defaultScope;
}
@Basic
@Column(name = "restricted")
public boolean isRestricted() {
return restricted;
}
public void setRestricted(boolean restricted) {
this.restricted = restricted;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (defaultScope ? 1231 : 1237);
result = prime * result
+ ((description == null) ? 0 : description.hashCode());
result = prime * result + ((icon == null) ? 0 : icon.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + (restricted ? 1231 : 1237);
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
SystemScope other = (SystemScope) obj;
if (defaultScope != other.defaultScope) {
return false;
}
if (description == null) {
if (other.description != null) {
return false;
}
} else if (!description.equals(other.description)) {
return false;
}
if (icon == null) {
if (other.icon != null) {
return false;
}
} else if (!icon.equals(other.icon)) {
return false;
}
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (restricted != other.restricted) {
return false;
}
if (value == null) {
return other.value == null;
} else {
return value.equals(other.value);
}
}
@Override
public String toString() {
return "SystemScope [id=" + id + ", value=" + value + ", description="
+ description + ", icon=" + icon + ", defaultScope="
+ defaultScope + ", restricted=" + restricted + "]";
}
} }

View File

@ -0,0 +1,27 @@
package cz.muni.ics.oauth2.model.enums;
import java.util.HashMap;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum AppType {
WEB("web"), NATIVE("native");
private final String value;
// map to aid reverse lookup
private static final Map<String, AppType> lookup = new HashMap<>();
static {
for (AppType a : AppType.values()) {
lookup.put(a.getValue(), a);
}
}
public static AppType getByValue(String value) {
return lookup.get(value);
}
}

View File

@ -0,0 +1,31 @@
package cz.muni.ics.oauth2.model.enums;
import java.util.HashMap;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum AuthMethod {
SECRET_POST("client_secret_post"),
SECRET_BASIC("client_secret_basic"),
SECRET_JWT("client_secret_jwt"),
PRIVATE_KEY("private_key_jwt"),
NONE("none");
private final String value;
// map to aid reverse lookup
private static final Map<String, AuthMethod> lookup = new HashMap<>();
static {
for (AuthMethod a : AuthMethod.values()) {
lookup.put(a.getValue(), a);
}
}
public static AuthMethod getByValue(String value) {
return lookup.get(value);
}
}

View File

@ -0,0 +1,27 @@
package cz.muni.ics.oauth2.model.enums;
import java.util.HashMap;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum SubjectType {
PAIRWISE("pairwise"), PUBLIC("public");
private final String value;
// map to aid reverse lookup
private static final Map<String, SubjectType> lookup = new HashMap<>();
static {
for (SubjectType u : SubjectType.values()) {
lookup.put(u.getValue(), u);
}
}
public static SubjectType getByValue(String value) {
return lookup.get(value);
}
}

View File

@ -22,7 +22,6 @@ import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity; import cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity;
import cz.muni.ics.oauth2.model.OAuth2RefreshTokenEntity; import cz.muni.ics.oauth2.model.OAuth2RefreshTokenEntity;
import cz.muni.ics.openid.connect.model.ApprovedSite; import cz.muni.ics.openid.connect.model.ApprovedSite;
import cz.muni.ics.uma.model.ResourceSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -68,8 +67,6 @@ public interface OAuth2TokenRepository {
Set<OAuth2RefreshTokenEntity> getAllExpiredRefreshTokens(PageCriteria pageCriteria); Set<OAuth2RefreshTokenEntity> getAllExpiredRefreshTokens(PageCriteria pageCriteria);
Set<OAuth2AccessTokenEntity> getAccessTokensForResourceSet(ResourceSet rs);
/** /**
* removes duplicate access tokens. * removes duplicate access tokens.
* *

View File

@ -26,7 +26,6 @@ import cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity;
import cz.muni.ics.oauth2.model.OAuth2RefreshTokenEntity; import cz.muni.ics.oauth2.model.OAuth2RefreshTokenEntity;
import cz.muni.ics.oauth2.repository.OAuth2TokenRepository; import cz.muni.ics.oauth2.repository.OAuth2TokenRepository;
import cz.muni.ics.openid.connect.model.ApprovedSite; import cz.muni.ics.openid.connect.model.ApprovedSite;
import cz.muni.ics.uma.model.ResourceSet;
import cz.muni.ics.util.jpa.JpaUtil; import cz.muni.ics.util.jpa.JpaUtil;
import java.text.ParseException; import java.text.ParseException;
import java.util.ArrayList; import java.util.ArrayList;
@ -222,13 +221,6 @@ public class JpaOAuth2TokenRepository implements OAuth2TokenRepository {
return new LinkedHashSet<>(JpaUtil.getResultPage(query,pageCriteria)); return new LinkedHashSet<>(JpaUtil.getResultPage(query,pageCriteria));
} }
@Override
public Set<OAuth2AccessTokenEntity> getAccessTokensForResourceSet(ResourceSet rs) {
TypedQuery<OAuth2AccessTokenEntity> query = manager.createNamedQuery(OAuth2AccessTokenEntity.QUERY_BY_RESOURCE_SET, OAuth2AccessTokenEntity.class);
query.setParameter(OAuth2AccessTokenEntity.PARAM_RESOURCE_SET_ID, rs.getId());
return new LinkedHashSet<>(query.getResultList());
}
@Override @Override
@Transactional(value="defaultTransactionManager") @Transactional(value="defaultTransactionManager")
public void clearDuplicateAccessTokens() { public void clearDuplicateAccessTokens() {

View File

@ -19,6 +19,7 @@
package cz.muni.ics.oauth2.service.impl; package cz.muni.ics.oauth2.service.impl;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.enums.AppType;
import cz.muni.ics.openid.connect.config.ConfigurationPropertiesBean; import cz.muni.ics.openid.connect.config.ConfigurationPropertiesBean;
import cz.muni.ics.openid.connect.service.BlacklistedSiteService; import cz.muni.ics.openid.connect.service.BlacklistedSiteService;
import java.util.Arrays; import java.util.Arrays;
@ -158,7 +159,7 @@ public class BlacklistAwareRedirectResolver implements RedirectResolver {
* @return Whether the requested redirect URI "matches" the specified redirect URI. * @return Whether the requested redirect URI "matches" the specified redirect URI.
*/ */
protected boolean redirectMatches(String requestedRedirect, String redirectUri, protected boolean redirectMatches(String requestedRedirect, String redirectUri,
ClientDetailsEntity.AppType applicationType) AppType applicationType)
{ {
UriComponents requestedRedirectUri = UriComponentsBuilder.fromUriString(requestedRedirect).build(); UriComponents requestedRedirectUri = UriComponentsBuilder.fromUriString(requestedRedirect).build();
UriComponents registeredRedirectUri = UriComponentsBuilder.fromUriString(redirectUri).build(); UriComponents registeredRedirectUri = UriComponentsBuilder.fromUriString(redirectUri).build();
@ -167,7 +168,7 @@ public class BlacklistAwareRedirectResolver implements RedirectResolver {
boolean userInfoMatch = isEqual(registeredRedirectUri.getUserInfo(), requestedRedirectUri.getUserInfo()); boolean userInfoMatch = isEqual(registeredRedirectUri.getUserInfo(), requestedRedirectUri.getUserInfo());
boolean hostMatch = hostMatches(registeredRedirectUri.getHost(), requestedRedirectUri.getHost()); boolean hostMatch = hostMatches(registeredRedirectUri.getHost(), requestedRedirectUri.getHost());
boolean portMatch = true; boolean portMatch = true;
if (!ClientDetailsEntity.AppType.NATIVE.equals(applicationType)) { if (!AppType.NATIVE.equals(applicationType)) {
portMatch = !matchPorts || registeredRedirectUri.getPort() == requestedRedirectUri.getPort(); portMatch = !matchPorts || registeredRedirectUri.getPort() == requestedRedirectUri.getPort();
} }
boolean pathMatch = true; boolean pathMatch = true;
@ -205,7 +206,7 @@ public class BlacklistAwareRedirectResolver implements RedirectResolver {
* @throws RedirectMismatchException if no match was found * @throws RedirectMismatchException if no match was found
*/ */
private String obtainMatchingRedirect(Set<String> redirectUris, String requestedRedirect, private String obtainMatchingRedirect(Set<String> redirectUris, String requestedRedirect,
ClientDetailsEntity.AppType applicationType) AppType applicationType)
{ {
Assert.notEmpty(redirectUris, "Redirect URIs cannot be empty"); Assert.notEmpty(redirectUris, "Redirect URIs cannot be empty");
@ -222,7 +223,7 @@ public class BlacklistAwareRedirectResolver implements RedirectResolver {
if (this.matchSubdomains) { if (this.matchSubdomains) {
redirectUriBuilder.host(requestedRedirectUri.getHost()); redirectUriBuilder.host(requestedRedirectUri.getHost());
} }
if (!this.matchPorts || ClientDetailsEntity.AppType.NATIVE.equals(applicationType)) { if (!this.matchPorts || AppType.NATIVE.equals(applicationType)) {
redirectUriBuilder.port(requestedRedirectUri.getPort()); redirectUriBuilder.port(requestedRedirectUri.getPort());
} }
if (!this.strictMatch) { if (!this.strictMatch) {

View File

@ -19,11 +19,11 @@ import static com.google.common.collect.Maps.newLinkedHashMap;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.common.collect.Sets;
import cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity; import cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity;
import cz.muni.ics.oauth2.model.OAuth2RefreshTokenEntity; import cz.muni.ics.oauth2.model.OAuth2RefreshTokenEntity;
import cz.muni.ics.oauth2.service.IntrospectionResultAssembler; import cz.muni.ics.oauth2.service.IntrospectionResultAssembler;
import cz.muni.ics.openid.connect.model.UserInfo; import cz.muni.ics.openid.connect.model.UserInfo;
import cz.muni.ics.uma.model.Permission;
import java.text.ParseException; import java.text.ParseException;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -46,27 +46,10 @@ public class DefaultIntrospectionResultAssembler implements IntrospectionResultA
result.put(ACTIVE, true); result.put(ACTIVE, true);
if (accessToken.getPermissions() != null && !accessToken.getPermissions().isEmpty()) {
Set<Object> permissions = Sets.newHashSet();
for (Permission perm : accessToken.getPermissions()) {
Map<String, Object> o = newLinkedHashMap();
o.put("resource_set_id", perm.getResourceSet().getId().toString());
Set<String> scopes = Sets.newHashSet(perm.getScopes());
o.put("scopes", scopes);
permissions.add(o);
}
result.put("permissions", permissions);
} else {
Set<String> scopes = Sets.intersection(authScopes, accessToken.getScope()); Set<String> scopes = Sets.intersection(authScopes, accessToken.getScope());
result.put(SCOPE, Joiner.on(SCOPE_SEPARATOR).join(scopes)); result.put(SCOPE, Joiner.on(SCOPE_SEPARATOR).join(scopes));
}
if (accessToken.getExpiration() != null) { if (accessToken.getExpiration() != null) {
try { try {
result.put(EXPIRES_AT, dateFormat.valueToString(accessToken.getExpiration())); result.put(EXPIRES_AT, dateFormat.valueToString(accessToken.getExpiration()));

View File

@ -25,8 +25,8 @@ import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.ClientDetailsEntity.AuthMethod;
import cz.muni.ics.oauth2.model.SystemScope; import cz.muni.ics.oauth2.model.SystemScope;
import cz.muni.ics.oauth2.model.enums.AuthMethod;
import cz.muni.ics.oauth2.repository.OAuth2ClientRepository; import cz.muni.ics.oauth2.repository.OAuth2ClientRepository;
import cz.muni.ics.oauth2.repository.OAuth2TokenRepository; import cz.muni.ics.oauth2.repository.OAuth2TokenRepository;
import cz.muni.ics.oauth2.service.ClientDetailsEntityService; import cz.muni.ics.oauth2.service.ClientDetailsEntityService;
@ -36,8 +36,6 @@ import cz.muni.ics.openid.connect.model.WhitelistedSite;
import cz.muni.ics.openid.connect.service.ApprovedSiteService; import cz.muni.ics.openid.connect.service.ApprovedSiteService;
import cz.muni.ics.openid.connect.service.BlacklistedSiteService; import cz.muni.ics.openid.connect.service.BlacklistedSiteService;
import cz.muni.ics.openid.connect.service.WhitelistedSiteService; import cz.muni.ics.openid.connect.service.WhitelistedSiteService;
import cz.muni.ics.uma.model.ResourceSet;
import cz.muni.ics.uma.service.ResourceSetService;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.ArrayList; import java.util.ArrayList;
@ -83,9 +81,6 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt
@Autowired @Autowired
private SystemScopeService scopeService; private SystemScopeService scopeService;
@Autowired
private ResourceSetService resourceSetService;
@Autowired @Autowired
private ConfigurationPropertiesBean config; private ConfigurationPropertiesBean config;
@ -354,12 +349,6 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt
whitelistedSiteService.remove(whitelistedSite); whitelistedSiteService.remove(whitelistedSite);
} }
// clear out resource sets registered for this client
Collection<ResourceSet> resourceSets = resourceSetService.getAllForClient(client);
for (ResourceSet rs : resourceSets) {
resourceSetService.remove(rs);
}
// take care of the client itself // take care of the client itself
clientRepository.deleteClient(client); clientRepository.deleteClient(client);
} }

View File

@ -1,6 +1,7 @@
package cz.muni.ics.oauth2.service.impl; package cz.muni.ics.oauth2.service.impl;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.enums.AuthMethod;
import cz.muni.ics.openid.connect.config.ConfigurationPropertiesBean; import cz.muni.ics.openid.connect.config.ConfigurationPropertiesBean;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.SecureRandom; import java.security.SecureRandom;
@ -15,8 +16,8 @@ public class ServiceUtils {
public static UserDetails getUserDetails(String decodedClientId, ClientDetailsEntity client, String encodedPassword, ConfigurationPropertiesBean config, GrantedAuthority roleClient) { public static UserDetails getUserDetails(String decodedClientId, ClientDetailsEntity client, String encodedPassword, ConfigurationPropertiesBean config, GrantedAuthority roleClient) {
if (config.isHeartMode() || // if we're running HEART mode turn off all client secrets if (config.isHeartMode() || // if we're running HEART mode turn off all client secrets
(client.getTokenEndpointAuthMethod() != null && (client.getTokenEndpointAuthMethod() != null &&
(client.getTokenEndpointAuthMethod().equals(ClientDetailsEntity.AuthMethod.PRIVATE_KEY) || (client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY) ||
client.getTokenEndpointAuthMethod().equals(ClientDetailsEntity.AuthMethod.SECRET_JWT)))) { client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT)))) {
encodedPassword = new BigInteger(512, new SecureRandom()).toString(16); encodedPassword = new BigInteger(512, new SecureRandom()).toString(16);
} }

View File

@ -30,9 +30,6 @@ import cz.muni.ics.openid.connect.model.UserInfo;
import cz.muni.ics.openid.connect.service.UserInfoService; import cz.muni.ics.openid.connect.service.UserInfoService;
import cz.muni.ics.openid.connect.view.HttpCodeView; import cz.muni.ics.openid.connect.view.HttpCodeView;
import cz.muni.ics.openid.connect.view.JsonEntityView; import cz.muni.ics.openid.connect.view.JsonEntityView;
import cz.muni.ics.uma.model.ResourceSet;
import cz.muni.ics.uma.service.ResourceSetService;
import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -68,9 +65,6 @@ public class IntrospectionEndpoint {
@Autowired @Autowired
private UserInfoService userInfoService; private UserInfoService userInfoService;
@Autowired
private ResourceSetService resourceSetService;
public IntrospectionEndpoint() { public IntrospectionEndpoint() {
} }
@ -101,15 +95,6 @@ public class IntrospectionEndpoint {
String ownerId = o2a.getUserAuthentication().getName(); String ownerId = o2a.getUserAuthentication().getName();
authScopes.addAll(authClient.getScope()); authScopes.addAll(authClient.getScope());
// UMA style clients also get a subset of scopes of all the resource sets they've registered
Collection<ResourceSet> resourceSets = resourceSetService.getAllForOwnerAndClient(ownerId, authClientId);
// collect all the scopes
for (ResourceSet rs : resourceSets) {
authScopes.addAll(rs.getScopes());
}
} else { } else {
// the client authenticated directly, make sure it's got the right access // the client authenticated directly, make sure it's got the right access

View File

@ -4,8 +4,6 @@ import cz.muni.ics.oauth2.model.AuthorizationCodeEntity;
import cz.muni.ics.oauth2.model.DeviceCode; import cz.muni.ics.oauth2.model.DeviceCode;
import cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity; import cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity;
import cz.muni.ics.oauth2.model.OAuth2RefreshTokenEntity; import cz.muni.ics.oauth2.model.OAuth2RefreshTokenEntity;
import cz.muni.ics.openid.connect.models.Acr;
import cz.muni.ics.openid.connect.models.DeviceCodeAcr;
import java.time.Instant; import java.time.Instant;
import java.util.Date; import java.util.Date;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
@ -135,38 +133,4 @@ public class CustomClearTasks {
return count; return count;
} }
public int clearExpiredAcrs(long timeout) {
manager.flush();
manager.clear();
int count = 0;
Query query = manager.createNamedQuery(Acr.DELETE_EXPIRED);
query.setParameter(Acr.PARAM_EXPIRES_AT, Instant.now().toEpochMilli());
if (timeout > 0) {
query.setHint("javax.persistence.query.timeout", timeout);
}
try {
count += query.executeUpdate();
} catch (QueryTimeoutException e) {
// this is OK
}
return count;
}
public int clearExpiredDeviceCodeAcrs(long timeout) {
manager.flush();
manager.clear();
int count = 0;
Query query = manager.createNamedQuery(DeviceCodeAcr.DELETE_EXPIRED);
query.setParameter(DeviceCodeAcr.PARAM_EXPIRES_AT, Instant.now().toEpochMilli());
if (timeout > 0) {
query.setHint("javax.persistence.query.timeout", timeout);
}
try {
count += query.executeUpdate();
} catch (QueryTimeoutException e) {
// this is OK
}
return count;
}
} }

View File

@ -105,34 +105,4 @@ public class CustomTaskScheduler {
log.info("clearExpiredDeviceCodes took {}ms, deleted {} records", execution, count); log.info("clearExpiredDeviceCodes took {}ms, deleted {} records", execution, count);
} }
@Transactional(value = "defaultTransactionManager")
@Scheduled(fixedDelay = 60 * ONE_MINUTE, initialDelay = 48 * ONE_MINUTE)
@SchedulerLock(name = "clearExpiredAcrs", lockAtMostFor = "3590s", lockAtLeastFor = "3590s")
public void clearExpiredAcrs() {
try {
LockAssert.assertLocked();
} catch (IllegalArgumentException e) {
return;
}
long start = System.currentTimeMillis();
int count = this.customClearTasks.clearExpiredAcrs(TimeUnit.MINUTES.toMillis(15));
long execution = System.currentTimeMillis() - start;
log.info("clearExpiredAcrs took {}ms, deleted {} records", execution, count);
}
@Transactional(value = "defaultTransactionManager")
@Scheduled(fixedDelay = 60 * ONE_MINUTE, initialDelay = 48 * ONE_MINUTE)
@SchedulerLock(name = "clearExpiredDeviceAcrs", lockAtMostFor = "3590s", lockAtLeastFor = "3590s")
public void clearExpiredDeviceAcrs() {
try {
LockAssert.assertLocked();
} catch (IllegalArgumentException e) {
return;
}
long start = System.currentTimeMillis();
int count = this.customClearTasks.clearExpiredAcrs(TimeUnit.MINUTES.toMillis(15));
long execution = System.currentTimeMillis() - start;
log.info("clearExpiredDeviceAcrs took {}ms, deleted {} records", execution, count);
}
} }

View File

@ -1,81 +0,0 @@
package cz.muni.ics.oidc.server;
import cz.muni.ics.openid.connect.models.Acr;
import java.time.Instant;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* Repository class for ACR model.
*
* @author Dominik Frantisek Bucik <bucik@ics.muni.cz>
*/
@Repository
@Transactional(value = "defaultTransactionManager")
public class PerunAcrRepository {
@PersistenceContext(unitName = "defaultPersistenceUnit")
private EntityManager manager;
public Acr getActive(String sub, String clientId, String state) {
TypedQuery<Acr> query = manager.createNamedQuery(Acr.GET_ACTIVE, Acr.class);
query.setParameter(Acr.PARAM_SUB, sub);
query.setParameter(Acr.PARAM_CLIENT_ID, clientId);
query.setParameter(Acr.PARAM_STATE, state);
query.setParameter(Acr.PARAM_EXPIRES_AT, now());
try {
return query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
public Acr getById(Long id) {
TypedQuery<Acr> query = manager.createNamedQuery(Acr.GET_BY_ID, Acr.class);
query.setParameter(Acr.PARAM_ID, id);
query.setParameter(Acr.PARAM_EXPIRES_AT, now());
try {
return query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
@Transactional
public Acr store(Acr acr) {
Acr existing = getActive(acr.getSub(), acr.getClientId(), acr.getState());
if (existing != null) {
return existing;
} else {
Acr tmp = manager.merge(acr);
manager.flush();
return tmp;
}
}
@Transactional
public void remove(Long id) {
Acr acr = getById(id);
if (acr != null) {
manager.remove(acr);
}
}
@Transactional
public void deleteExpired() {
Query query = manager.createNamedQuery(Acr.DELETE_EXPIRED);
query.setParameter(Acr.PARAM_EXPIRES_AT, now());
query.executeUpdate();
}
private long now() {
return Instant.now().toEpochMilli();
}
}

View File

@ -1,91 +0,0 @@
package cz.muni.ics.oidc.server;
import cz.muni.ics.openid.connect.models.Acr;
import cz.muni.ics.openid.connect.models.DeviceCodeAcr;
import java.time.Instant;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* Repository class for ACR model.
*
* @author Dominik Frantisek Bucik <bucik@ics.muni.cz>
*/
@Repository
@Transactional(value = "defaultTransactionManager")
public class PerunDeviceCodeAcrRepository {
@PersistenceContext(unitName = "defaultPersistenceUnit")
private EntityManager manager;
public DeviceCodeAcr getActiveByDeviceCode(String deviceCode) {
TypedQuery<DeviceCodeAcr> query = manager.createNamedQuery(DeviceCodeAcr.GET_ACTIVE_BY_DEVICE_CODE,
DeviceCodeAcr.class);
query.setParameter(DeviceCodeAcr.PARAM_DEVICE_CODE, deviceCode);
query.setParameter(Acr.PARAM_EXPIRES_AT, now());
try {
return query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
public DeviceCodeAcr getByUserCode(String userCode) {
TypedQuery<DeviceCodeAcr> query = manager.createNamedQuery(DeviceCodeAcr.GET_BY_USER_CODE, DeviceCodeAcr.class);
query.setParameter(DeviceCodeAcr.PARAM_USER_CODE, userCode);
try {
return query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
public DeviceCodeAcr getById(Long id) {
TypedQuery<DeviceCodeAcr> query = manager.createNamedQuery(DeviceCodeAcr.GET_BY_ID, DeviceCodeAcr.class);
query.setParameter(DeviceCodeAcr.PARAM_ID, id);
query.setParameter(DeviceCodeAcr.PARAM_EXPIRES_AT, now());
try {
return query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
@Transactional
public DeviceCodeAcr store(DeviceCodeAcr acr) {
try {
return getActiveByDeviceCode(acr.getDeviceCode());
} catch (NoResultException e) {
DeviceCodeAcr tmp = manager.merge(acr);
manager.flush();
return tmp;
}
}
@Transactional
public void remove(Long id) {
DeviceCodeAcr acr = getById(id);
if (acr != null) {
manager.remove(acr);
}
}
@Transactional
public void deleteExpired() {
Query query = manager.createNamedQuery(DeviceCodeAcr.DELETE_EXPIRED);
query.setParameter(DeviceCodeAcr.PARAM_EXPIRES_AT, now());
query.executeUpdate();
}
private long now() {
return Instant.now().toEpochMilli();
}
}

View File

@ -4,17 +4,14 @@ import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.DeviceCode; import cz.muni.ics.oauth2.model.DeviceCode;
import cz.muni.ics.oauth2.service.SystemScopeService; import cz.muni.ics.oauth2.service.SystemScopeService;
import cz.muni.ics.oauth2.web.DeviceEndpoint; import cz.muni.ics.oauth2.web.DeviceEndpoint;
import cz.muni.ics.oidc.server.PerunDeviceCodeAcrRepository;
import cz.muni.ics.oidc.server.PerunScopeClaimTranslationService; import cz.muni.ics.oidc.server.PerunScopeClaimTranslationService;
import cz.muni.ics.oidc.server.configurations.PerunOidcConfig; import cz.muni.ics.oidc.server.configurations.PerunOidcConfig;
import cz.muni.ics.oidc.server.filters.PerunFilterConstants; import cz.muni.ics.oidc.server.filters.PerunFilterConstants;
import cz.muni.ics.oidc.server.userInfo.PerunUserInfo; import cz.muni.ics.oidc.server.userInfo.PerunUserInfo;
import cz.muni.ics.oidc.web.WebHtmlClasses; import cz.muni.ics.oidc.web.WebHtmlClasses;
import cz.muni.ics.oidc.web.langs.Localization; import cz.muni.ics.oidc.web.langs.Localization;
import cz.muni.ics.openid.connect.models.DeviceCodeAcr;
import cz.muni.ics.openid.connect.service.UserInfoService; import cz.muni.ics.openid.connect.service.UserInfoService;
import java.security.Principal; import java.security.Principal;
import java.time.Instant;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
@ -41,7 +38,6 @@ public class ApproveDeviceController {
public static final String DEVICE_APPROVED = "deviceApproved"; public static final String DEVICE_APPROVED = "deviceApproved";
public static final String REQUEST_USER_CODE = "requestUserCode"; public static final String REQUEST_USER_CODE = "requestUserCode";
public static final String USER_CODE = "user_code"; public static final String USER_CODE = "user_code";
public static final String DEVICE_CODE = "device_code";
public static final String USER_OAUTH_APPROVAL = "user_oauth_approval"; public static final String USER_OAUTH_APPROVAL = "user_oauth_approval";
public static final String URL = "devicecode"; public static final String URL = "devicecode";
public static final String VERIFICATION_URI = "verification_uri"; public static final String VERIFICATION_URI = "verification_uri";
@ -59,7 +55,6 @@ public class ApproveDeviceController {
private final WebHtmlClasses htmlClasses; private final WebHtmlClasses htmlClasses;
private final PerunScopeClaimTranslationService scopeClaimTranslationService; private final PerunScopeClaimTranslationService scopeClaimTranslationService;
private final UserInfoService userInfoService; private final UserInfoService userInfoService;
private final PerunDeviceCodeAcrRepository deviceCodeAcrRepository;
@Autowired @Autowired
public ApproveDeviceController(SystemScopeService scopeService, public ApproveDeviceController(SystemScopeService scopeService,
@ -68,8 +63,7 @@ public class ApproveDeviceController {
Localization localization, Localization localization,
WebHtmlClasses htmlClasses, WebHtmlClasses htmlClasses,
PerunScopeClaimTranslationService scopeClaimTranslationService, PerunScopeClaimTranslationService scopeClaimTranslationService,
UserInfoService userInfoService, UserInfoService userInfoService)
PerunDeviceCodeAcrRepository perunDeviceCodeAcrRepository)
{ {
this.scopeService = scopeService; this.scopeService = scopeService;
this.deviceEndpoint = deviceEndpoint; this.deviceEndpoint = deviceEndpoint;
@ -78,7 +72,6 @@ public class ApproveDeviceController {
this.htmlClasses = htmlClasses; this.htmlClasses = htmlClasses;
this.scopeClaimTranslationService = scopeClaimTranslationService; this.scopeClaimTranslationService = scopeClaimTranslationService;
this.userInfoService = userInfoService; this.userInfoService = userInfoService;
this.deviceCodeAcrRepository = perunDeviceCodeAcrRepository;
} }
@RequestMapping( @RequestMapping(
@ -96,7 +89,6 @@ public class ApproveDeviceController {
Map<String, Object> response = (Map<String, Object>) model.get(ENTITY); Map<String, Object> response = (Map<String, Object>) model.get(ENTITY);
response.replace(VERIFICATION_URI, response.get(VERIFICATION_URI) + "?" + ACR_VALUES + "=" + acrValues); response.replace(VERIFICATION_URI, response.get(VERIFICATION_URI) + "?" + ACR_VALUES + "=" + acrValues);
response.replace(VERIFICATION_URI_COMPLETE, response.get(VERIFICATION_URI_COMPLETE) + "&" + ACR_VALUES + "=" + acrValues); response.replace(VERIFICATION_URI_COMPLETE, response.get(VERIFICATION_URI_COMPLETE) + "&" + ACR_VALUES + "=" + acrValues);
storeAcrBase((String) response.get(DEVICE_CODE), (String)response.get(USER_CODE));
return result; return result;
} }
@ -145,10 +137,6 @@ public class ApproveDeviceController {
{ {
String result = deviceEndpoint.readUserCode(userCode, model, session); String result = deviceEndpoint.readUserCode(userCode, model, session);
if (result.equals(APPROVE_DEVICE) && !perunOidcConfig.getTheme().equalsIgnoreCase("default")) { if (result.equals(APPROVE_DEVICE) && !perunOidcConfig.getTheme().equalsIgnoreCase("default")) {
if (StringUtils.hasText(req.getParameter(ACR))) {
storeAcr(req.getParameter(ACR), userCode);
}
return themedApproveDevice(model, p, req); return themedApproveDevice(model, p, req);
} else if (result.equals(REQUEST_USER_CODE) && !perunOidcConfig.getTheme().equalsIgnoreCase("default")) { } else if (result.equals(REQUEST_USER_CODE) && !perunOidcConfig.getTheme().equalsIgnoreCase("default")) {
ControllerUtils.setPageOptions(model, req, localization, htmlClasses, perunOidcConfig); ControllerUtils.setPageOptions(model, req, localization, htmlClasses, perunOidcConfig);
@ -189,14 +177,6 @@ public class ApproveDeviceController {
return result; return result;
} }
private void storeAcr(String acrValue, String userCode) {
DeviceCodeAcr acr = deviceCodeAcrRepository.getByUserCode(userCode);
acr.setShibAuthnContextClass(acrValue);
long expiresAtEpoch = Instant.now().plusSeconds(600L).toEpochMilli();
acr.setExpiresAt(expiresAtEpoch);
deviceCodeAcrRepository.store(acr);
}
private String themedApproveDevice(ModelMap model, Principal p, HttpServletRequest req) { private String themedApproveDevice(ModelMap model, Principal p, HttpServletRequest req) {
model.remove("scopes"); model.remove("scopes");
DeviceCode dc = (DeviceCode) model.get("dc"); DeviceCode dc = (DeviceCode) model.get("dc");
@ -210,10 +190,4 @@ public class ApproveDeviceController {
return "themedApproveDevice"; return "themedApproveDevice";
} }
private void storeAcrBase(String deviceCode, String userCode) {
DeviceCodeAcr acrBase = new DeviceCodeAcr(deviceCode, userCode);
acrBase.setExpiresAt(Instant.now().plusSeconds(1800).toEpochMilli());
deviceCodeAcrRepository.store(acrBase);
}
} }

View File

@ -74,10 +74,10 @@ import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWT;
import com.nimbusds.jwt.JWTParser; import com.nimbusds.jwt.JWTParser;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.ClientDetailsEntity.AppType;
import cz.muni.ics.oauth2.model.ClientDetailsEntity.AuthMethod;
import cz.muni.ics.oauth2.model.ClientDetailsEntity.SubjectType;
import cz.muni.ics.oauth2.model.RegisteredClient; import cz.muni.ics.oauth2.model.RegisteredClient;
import cz.muni.ics.oauth2.model.enums.AppType;
import cz.muni.ics.oauth2.model.enums.AuthMethod;
import cz.muni.ics.oauth2.model.enums.SubjectType;
import cz.muni.ics.util.JsonUtils; import cz.muni.ics.util.JsonUtils;
import java.text.ParseException; import java.text.ParseException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;

View File

@ -27,7 +27,7 @@ import com.nimbusds.jwt.SignedJWT;
import cz.muni.ics.jwt.signer.service.JWTSigningAndValidationService; import cz.muni.ics.jwt.signer.service.JWTSigningAndValidationService;
import cz.muni.ics.jwt.signer.service.impl.ClientKeyCacheService; import cz.muni.ics.jwt.signer.service.impl.ClientKeyCacheService;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.ClientDetailsEntity.AuthMethod; import cz.muni.ics.oauth2.model.enums.AuthMethod;
import cz.muni.ics.oauth2.service.ClientDetailsEntityService; import cz.muni.ics.oauth2.service.ClientDetailsEntityService;
import cz.muni.ics.openid.connect.config.ConfigurationPropertiesBean; import cz.muni.ics.openid.connect.config.ConfigurationPropertiesBean;
import java.text.ParseException; import java.text.ParseException;

View File

@ -17,9 +17,15 @@
*******************************************************************************/ *******************************************************************************/
package cz.muni.ics.openid.connect.model; package cz.muni.ics.openid.connect.model;
import static cz.muni.ics.openid.connect.model.ApprovedSite.PARAM_CLIENT_ID;
import static cz.muni.ics.openid.connect.model.ApprovedSite.PARAM_USER_ID;
import static cz.muni.ics.openid.connect.model.ApprovedSite.QUERY_ALL;
import static cz.muni.ics.openid.connect.model.ApprovedSite.QUERY_BY_CLIENT_ID;
import static cz.muni.ics.openid.connect.model.ApprovedSite.QUERY_BY_CLIENT_ID_AND_USER_ID;
import static cz.muni.ics.openid.connect.model.ApprovedSite.QUERY_BY_USER_ID;
import java.util.Date; import java.util.Date;
import java.util.Set; import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.CollectionTable; import javax.persistence.CollectionTable;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.ElementCollection; import javax.persistence.ElementCollection;
@ -33,15 +39,37 @@ import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.Table; import javax.persistence.Table;
import javax.persistence.Temporal; import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient; import javax.persistence.Transient;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
// DB ANNOTATIONS
@Entity @Entity
@Table(name="approved_site") @Table(name="approved_site")
@NamedQueries({ @NamedQueries({
@NamedQuery(name = ApprovedSite.QUERY_ALL, query = "select a from ApprovedSite a"), @NamedQuery(name = QUERY_ALL,
@NamedQuery(name = ApprovedSite.QUERY_BY_USER_ID, query = "select a from ApprovedSite a where a.userId = :" + ApprovedSite.PARAM_USER_ID), query = "SELECT a FROM ApprovedSite a"),
@NamedQuery(name = ApprovedSite.QUERY_BY_CLIENT_ID, query = "select a from ApprovedSite a where a.clientId = :" + ApprovedSite.PARAM_CLIENT_ID), @NamedQuery(name = QUERY_BY_USER_ID,
@NamedQuery(name = ApprovedSite.QUERY_BY_CLIENT_ID_AND_USER_ID, query = "select a from ApprovedSite a where a.clientId = :" + ApprovedSite.PARAM_CLIENT_ID + " and a.userId = :" + ApprovedSite.PARAM_USER_ID) query = "SELECT a FROM ApprovedSite a " +
"WHERE a.userId = :" + PARAM_USER_ID),
@NamedQuery(name = QUERY_BY_CLIENT_ID,
query = "SELECT a FROM ApprovedSite a " +
"WHERE a.clientId = :" + PARAM_CLIENT_ID),
@NamedQuery(name = QUERY_BY_CLIENT_ID_AND_USER_ID,
query = "SELECT a FROM ApprovedSite a " +
"WHERE a.clientId = :" + PARAM_CLIENT_ID + ' ' +
"AND a.userId = :" + PARAM_USER_ID)
}) })
public class ApprovedSite { public class ApprovedSite {
@ -53,90 +81,33 @@ public class ApprovedSite {
public static final String PARAM_CLIENT_ID = "clientId"; public static final String PARAM_CLIENT_ID = "clientId";
public static final String PARAM_USER_ID = "userId"; public static final String PARAM_USER_ID = "userId";
private Long id;
private String userId;
private String clientId;
private Date creationDate;
private Date accessDate;
private Date timeoutDate;
private Set<String> allowedScopes;
public ApprovedSite() { }
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id") @Column(name = "id")
public Long getId() { private Long id;
return id;
}
public void setId(Long id) {
this.id = id;
}
@Basic
@Column(name = "user_id") @Column(name = "user_id")
public String getUserId() { private String userId;
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Basic
@Column(name = "client_id") @Column(name = "client_id")
public String getClientId() { private String clientId;
return clientId;
}
public void setClientId(String clientId) { @Temporal(TemporalType.TIMESTAMP)
this.clientId = clientId;
}
@Basic
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
@Column(name = "creation_date") @Column(name = "creation_date")
public Date getCreationDate() { private Date creationDate;
return creationDate;
}
public void setCreationDate(Date creationDate) { @Temporal(TemporalType.TIMESTAMP)
this.creationDate = creationDate;
}
@Basic
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
@Column(name = "access_date") @Column(name = "access_date")
public Date getAccessDate() { private Date accessDate;
return accessDate;
}
public void setAccessDate(Date accessDate) { @Temporal(TemporalType.TIMESTAMP)
this.accessDate = accessDate; @Column(name = "timeout_date")
} private Date timeoutDate;
@ElementCollection(fetch = FetchType.EAGER) @ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "approved_site_scope", joinColumns = @JoinColumn(name = "owner_id")) @CollectionTable(name = "approved_site_scope", joinColumns = @JoinColumn(name = "owner_id"))
@Column(name = "scope") @Column(name = "scope")
public Set<String> getAllowedScopes() { private Set<String> allowedScopes;
return allowedScopes;
}
public void setAllowedScopes(Set<String> allowedScopes) {
this.allowedScopes = allowedScopes;
}
@Basic
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
@Column(name="timeout_date")
public Date getTimeoutDate() {
return timeoutDate;
}
public void setTimeoutDate(Date timeoutDate) {
this.timeoutDate = timeoutDate;
}
@Transient @Transient
public boolean isExpired() { public boolean isExpired() {

View File

@ -20,7 +20,8 @@
*/ */
package cz.muni.ics.openid.connect.model; package cz.muni.ics.openid.connect.model;
import javax.persistence.Basic; import static cz.muni.ics.openid.connect.model.BlacklistedSite.QUERY_ALL;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
@ -29,43 +30,39 @@ import javax.persistence.Id;
import javax.persistence.NamedQueries; import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.Table; import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/** /**
* @author jricher * @author jricher
*/ */
@Getter
@Setter
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
// DB ANNOTATIONS
@Entity @Entity
@Table(name="blacklisted_site") @Table(name="blacklisted_site")
@NamedQueries({ @NamedQueries({
@NamedQuery(name = BlacklistedSite.QUERY_ALL, query = "select b from BlacklistedSite b") @NamedQuery(name = QUERY_ALL,
query = "SELECT b FROM BlacklistedSite b")
}) })
public class BlacklistedSite { public class BlacklistedSite {
public static final String QUERY_ALL = "BlacklistedSite.getAll"; public static final String QUERY_ALL = "BlacklistedSite.getAll";
private Long id;
private String uri;
public BlacklistedSite() { }
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id") @Column(name = "id")
public Long getId() { private Long id;
return id;
}
public void setId(Long id) {
this.id = id;
}
@Basic
@Column(name="uri") @Column(name="uri")
public String getUri() { private String uri;
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
} }

View File

@ -15,29 +15,54 @@
*******************************************************************************/ *******************************************************************************/
package cz.muni.ics.openid.connect.model; package cz.muni.ics.openid.connect.model;
import javax.persistence.Basic;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.Table; import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
// DB ANNOTATIONS
@Entity @Entity
@Table(name = "address") @Table(name = "address")
public class DefaultAddress implements Address { public class DefaultAddress implements Address {
private static final long serialVersionUID = -1304880008685206811L; private static final long serialVersionUID = -1304880008685206811L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id; private Long id;
private String formatted;
private String streetAddress;
private String locality;
private String region;
private String postalCode;
private String country;
public DefaultAddress() { } @Column(name = "formatted")
private String formatted;
@Column(name = "street_address")
private String streetAddress;
@Column(name = "locality")
private String locality;
@Column(name = "region")
private String region;
@Column(name = "postal_code")
private String postalCode;
@Column(name = "country")
private String country;
public DefaultAddress(Address address) { public DefaultAddress(Address address) {
setFormatted(address.getFormatted()); setFormatted(address.getFormatted());
@ -49,8 +74,11 @@ public class DefaultAddress implements Address {
} }
@Override @Override
@Basic public Long getId() {
@Column(name = "formatted") return id;
}
@Override
public String getFormatted() { public String getFormatted() {
return formatted; return formatted;
} }
@ -61,8 +89,6 @@ public class DefaultAddress implements Address {
} }
@Override @Override
@Basic
@Column(name="street_address")
public String getStreetAddress() { public String getStreetAddress() {
return streetAddress; return streetAddress;
} }
@ -73,8 +99,6 @@ public class DefaultAddress implements Address {
} }
@Override @Override
@Basic
@Column(name = "locality")
public String getLocality() { public String getLocality() {
return locality; return locality;
} }
@ -85,8 +109,6 @@ public class DefaultAddress implements Address {
} }
@Override @Override
@Basic
@Column(name = "region")
public String getRegion() { public String getRegion() {
return region; return region;
} }
@ -97,8 +119,6 @@ public class DefaultAddress implements Address {
} }
@Override @Override
@Basic
@Column(name="postal_code")
public String getPostalCode() { public String getPostalCode() {
return postalCode; return postalCode;
} }
@ -109,8 +129,6 @@ public class DefaultAddress implements Address {
} }
@Override @Override
@Basic
@Column(name = "country")
public String getCountry() { public String getCountry() {
return country; return country;
} }
@ -120,93 +138,4 @@ public class DefaultAddress implements Address {
this.country = country; this.country = country;
} }
@Override
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + ((formatted == null) ? 0 : formatted.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((locality == null) ? 0 : locality.hashCode());
result = prime * result + ((postalCode == null) ? 0 : postalCode.hashCode());
result = prime * result + ((region == null) ? 0 : region.hashCode());
result = prime * result + ((streetAddress == null) ? 0 : streetAddress.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof DefaultAddress)) {
return false;
}
DefaultAddress other = (DefaultAddress) obj;
if (country == null) {
if (other.country != null) {
return false;
}
} else if (!country.equals(other.country)) {
return false;
}
if (formatted == null) {
if (other.formatted != null) {
return false;
}
} else if (!formatted.equals(other.formatted)) {
return false;
}
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (locality == null) {
if (other.locality != null) {
return false;
}
} else if (!locality.equals(other.locality)) {
return false;
}
if (postalCode == null) {
if (other.postalCode != null) {
return false;
}
} else if (!postalCode.equals(other.postalCode)) {
return false;
}
if (region == null) {
if (other.region != null) {
return false;
}
} else if (!region.equals(other.region)) {
return false;
}
if (streetAddress == null) {
return other.streetAddress == null;
} else return streetAddress.equals(other.streetAddress);
}
} }

View File

@ -17,13 +17,17 @@
*******************************************************************************/ *******************************************************************************/
package cz.muni.ics.openid.connect.model; package cz.muni.ics.openid.connect.model;
import static cz.muni.ics.openid.connect.model.DefaultUserInfo.PARAM_EMAIL;
import static cz.muni.ics.openid.connect.model.DefaultUserInfo.PARAM_USERNAME;
import static cz.muni.ics.openid.connect.model.DefaultUserInfo.QUERY_BY_EMAIL;
import static cz.muni.ics.openid.connect.model.DefaultUserInfo.QUERY_BY_USERNAME;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import cz.muni.ics.openid.connect.model.convert.JsonObjectStringConverter; import cz.muni.ics.openid.connect.model.convert.JsonObjectStringConverter;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import javax.persistence.Basic;
import javax.persistence.CascadeType; import javax.persistence.CascadeType;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Convert; import javax.persistence.Convert;
@ -36,12 +40,29 @@ import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.OneToOne; import javax.persistence.OneToOne;
import javax.persistence.Table; import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
// DB ANNOTATIONS
@Entity @Entity
@Table(name="user_info") @Table(name="user_info")
@NamedQueries({ @NamedQueries({
@NamedQuery(name=DefaultUserInfo.QUERY_BY_USERNAME, query = "select u from DefaultUserInfo u WHERE u.preferredUsername = :" + DefaultUserInfo.PARAM_USERNAME), @NamedQuery(name = QUERY_BY_USERNAME,
@NamedQuery(name=DefaultUserInfo.QUERY_BY_EMAIL, query = "select u from DefaultUserInfo u WHERE u.email = :" + DefaultUserInfo.PARAM_EMAIL) query = "SELECT u FROM DefaultUserInfo u " +
"WHERE u.preferredUsername = :" + PARAM_USERNAME),
@NamedQuery(name = QUERY_BY_EMAIL,
query = "SELECT u FROM DefaultUserInfo u " +
"WHERE u.email = :" + PARAM_EMAIL)
}) })
public class DefaultUserInfo implements UserInfo { public class DefaultUserInfo implements UserInfo {
@ -53,44 +74,77 @@ public class DefaultUserInfo implements UserInfo {
private static final long serialVersionUID = 6078310513185681918L; private static final long serialVersionUID = 6078310513185681918L;
private Long id;
private String sub;
private String preferredUsername;
private String name;
private String givenName;
private String familyName;
private String middleName;
private String nickname;
private String profile;
private String picture;
private String website;
private String email;
private Boolean emailVerified;
private String gender;
private String zoneinfo;
private String locale;
private String phoneNumber;
private Boolean phoneNumberVerified;
private DefaultAddress address;
private String updatedTime;
private String birthdate;
private transient JsonObject src; // source JSON if this is loaded remotely
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id") @Column(name = "id")
public Long getId() { private Long id;
return id;
}
public void setId(Long id) { @Column(name = "sub")
this.id = id; private String sub;
}
@Column(name = "preferred_username")
private String preferredUsername;
@Column(name = "name")
private String name;
@Column(name = "given_name")
private String givenName;
@Column(name = "family_name")
private String familyName;
@Column(name = "middle_name")
private String middleName;
@Column(name = "nickname")
private String nickname;
@Column(name = "profile")
private String profile;
@Column(name = "picture")
private String picture;
@Column(name = "website")
private String website;
@Column(name = "email")
private String email;
@Column(name = "email_verified")
private Boolean emailVerified;
@Column(name = "gender")
private String gender;
@Column(name = "zone_info")
private String zoneinfo;
@Column(name = "locale")
private String locale;
@Column(name = "phone_number")
private String phoneNumber;
@Column(name = "phone_number_verified")
private Boolean phoneNumberVerified;
@OneToOne(targetEntity = DefaultAddress.class, cascade = CascadeType.ALL)
@JoinColumn(name = "address_id")
private DefaultAddress address;
@Column(name = "updated_time")
private String updatedTime;
@Column(name = "birthdate")
private String birthdate;
@Column(name = "src")
@Convert(converter = JsonObjectStringConverter.class)
private transient JsonObject source; // source JSON if this is loaded remotely
@Override @Override
@Basic
@Column(name="sub")
public String getSub() { public String getSub() {
return sub; return sub;
} }
@ -101,8 +155,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name="preferred_username")
public String getPreferredUsername() { public String getPreferredUsername() {
return this.preferredUsername; return this.preferredUsername;
} }
@ -113,8 +165,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name = "name")
public String getName() { public String getName() {
return name; return name;
} }
@ -125,8 +175,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name="given_name")
public String getGivenName() { public String getGivenName() {
return givenName; return givenName;
} }
@ -137,8 +185,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name="family_name")
public String getFamilyName() { public String getFamilyName() {
return familyName; return familyName;
} }
@ -149,8 +195,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name="middle_name")
public String getMiddleName() { public String getMiddleName() {
return middleName; return middleName;
} }
@ -161,8 +205,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name = "nickname")
public String getNickname() { public String getNickname() {
return nickname; return nickname;
} }
@ -173,8 +215,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name = "profile")
public String getProfile() { public String getProfile() {
return profile; return profile;
} }
@ -185,8 +225,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name = "picture")
public String getPicture() { public String getPicture() {
return picture; return picture;
} }
@ -197,8 +235,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name = "website")
public String getWebsite() { public String getWebsite() {
return website; return website;
} }
@ -209,8 +245,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name = "email")
public String getEmail() { public String getEmail() {
return email; return email;
} }
@ -221,8 +255,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name="email_verified")
public Boolean getEmailVerified() { public Boolean getEmailVerified() {
return emailVerified; return emailVerified;
} }
@ -233,8 +265,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name = "gender")
public String getGender() { public String getGender() {
return gender; return gender;
} }
@ -245,8 +275,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name="zone_info")
public String getZoneinfo() { public String getZoneinfo() {
return zoneinfo; return zoneinfo;
} }
@ -257,8 +285,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name = "locale")
public String getLocale() { public String getLocale() {
return locale; return locale;
} }
@ -269,8 +295,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name="phone_number")
public String getPhoneNumber() { public String getPhoneNumber() {
return phoneNumber; return phoneNumber;
} }
@ -281,8 +305,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name="phone_number_verified")
public Boolean getPhoneNumberVerified() { public Boolean getPhoneNumberVerified() {
return phoneNumberVerified; return phoneNumberVerified;
} }
@ -293,8 +315,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@OneToOne(targetEntity = DefaultAddress.class, cascade = CascadeType.ALL)
@JoinColumn(name="address_id")
public Address getAddress() { public Address getAddress() {
return address; return address;
} }
@ -309,8 +329,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name="updated_time")
public String getUpdatedTime() { public String getUpdatedTime() {
return updatedTime; return updatedTime;
} }
@ -321,8 +339,6 @@ public class DefaultUserInfo implements UserInfo {
} }
@Override @Override
@Basic
@Column(name="birthdate")
public String getBirthdate() { public String getBirthdate() {
return birthdate; return birthdate;
} }
@ -334,7 +350,7 @@ public class DefaultUserInfo implements UserInfo {
@Override @Override
public JsonObject toJson() { public JsonObject toJson() {
if (src == null) { if (source == null) {
JsonObject obj = new JsonObject(); JsonObject obj = new JsonObject();
obj.addProperty("sub", this.getSub()); obj.addProperty("sub", this.getSub());
@ -372,10 +388,14 @@ public class DefaultUserInfo implements UserInfo {
} }
return obj; return obj;
} else { } else {
return src; return source;
} }
} }
@Override
public JsonObject getSource() {
return source;
}
public static UserInfo fromJson(JsonObject obj) { public static UserInfo fromJson(JsonObject obj) {
DefaultUserInfo ui = new DefaultUserInfo(); DefaultUserInfo ui = new DefaultUserInfo();
@ -420,213 +440,16 @@ public class DefaultUserInfo implements UserInfo {
return ui; return ui;
} }
@Override
@Basic
@Column(name = "src")
@Convert(converter = JsonObjectStringConverter.class)
public JsonObject getSource() {
return src;
}
public void setSource(JsonObject src) {
this.src = src;
}
private static String nullSafeGetString(JsonObject obj, String field) { private static String nullSafeGetString(JsonObject obj, String field) {
return obj.has(field) && obj.get(field).isJsonPrimitive() ? obj.get(field).getAsString() : null; return obj.has(field) && obj.get(field).isJsonPrimitive() ? obj.get(field).getAsString() : null;
} }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((birthdate == null) ? 0 : birthdate.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((emailVerified == null) ? 0 : emailVerified.hashCode());
result = prime * result + ((familyName == null) ? 0 : familyName.hashCode());
result = prime * result + ((gender == null) ? 0 : gender.hashCode());
result = prime * result + ((givenName == null) ? 0 : givenName.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((locale == null) ? 0 : locale.hashCode());
result = prime * result + ((middleName == null) ? 0 : middleName.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((nickname == null) ? 0 : nickname.hashCode());
result = prime * result + ((phoneNumber == null) ? 0 : phoneNumber.hashCode());
result = prime * result + ((phoneNumberVerified == null) ? 0 : phoneNumberVerified.hashCode());
result = prime * result + ((picture == null) ? 0 : picture.hashCode());
result = prime * result + ((preferredUsername == null) ? 0 : preferredUsername.hashCode());
result = prime * result + ((profile == null) ? 0 : profile.hashCode());
result = prime * result + ((sub == null) ? 0 : sub.hashCode());
result = prime * result + ((updatedTime == null) ? 0 : updatedTime.hashCode());
result = prime * result + ((website == null) ? 0 : website.hashCode());
result = prime * result + ((zoneinfo == null) ? 0 : zoneinfo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof DefaultUserInfo)) {
return false;
}
DefaultUserInfo other = (DefaultUserInfo) obj;
if (address == null) {
if (other.address != null) {
return false;
}
} else if (!address.equals(other.address)) {
return false;
}
if (birthdate == null) {
if (other.birthdate != null) {
return false;
}
} else if (!birthdate.equals(other.birthdate)) {
return false;
}
if (email == null) {
if (other.email != null) {
return false;
}
} else if (!email.equals(other.email)) {
return false;
}
if (emailVerified == null) {
if (other.emailVerified != null) {
return false;
}
} else if (!emailVerified.equals(other.emailVerified)) {
return false;
}
if (familyName == null) {
if (other.familyName != null) {
return false;
}
} else if (!familyName.equals(other.familyName)) {
return false;
}
if (gender == null) {
if (other.gender != null) {
return false;
}
} else if (!gender.equals(other.gender)) {
return false;
}
if (givenName == null) {
if (other.givenName != null) {
return false;
}
} else if (!givenName.equals(other.givenName)) {
return false;
}
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (locale == null) {
if (other.locale != null) {
return false;
}
} else if (!locale.equals(other.locale)) {
return false;
}
if (middleName == null) {
if (other.middleName != null) {
return false;
}
} else if (!middleName.equals(other.middleName)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (nickname == null) {
if (other.nickname != null) {
return false;
}
} else if (!nickname.equals(other.nickname)) {
return false;
}
if (phoneNumber == null) {
if (other.phoneNumber != null) {
return false;
}
} else if (!phoneNumber.equals(other.phoneNumber)) {
return false;
}
if (phoneNumberVerified == null) {
if (other.phoneNumberVerified != null) {
return false;
}
} else if (!phoneNumberVerified.equals(other.phoneNumberVerified)) {
return false;
}
if (picture == null) {
if (other.picture != null) {
return false;
}
} else if (!picture.equals(other.picture)) {
return false;
}
if (preferredUsername == null) {
if (other.preferredUsername != null) {
return false;
}
} else if (!preferredUsername.equals(other.preferredUsername)) {
return false;
}
if (profile == null) {
if (other.profile != null) {
return false;
}
} else if (!profile.equals(other.profile)) {
return false;
}
if (sub == null) {
if (other.sub != null) {
return false;
}
} else if (!sub.equals(other.sub)) {
return false;
}
if (updatedTime == null) {
if (other.updatedTime != null) {
return false;
}
} else if (!updatedTime.equals(other.updatedTime)) {
return false;
}
if (website == null) {
if (other.website != null) {
return false;
}
} else if (!website.equals(other.website)) {
return false;
}
if (zoneinfo == null) {
return other.zoneinfo == null;
} else return zoneinfo.equals(other.zoneinfo);
}
private void writeObject(ObjectOutputStream out) throws IOException { private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject(); out.defaultWriteObject();
if (src == null) { if (source == null) {
out.writeObject(null); out.writeObject(null);
} else { } else {
out.writeObject(src.toString()); out.writeObject(source.toString());
} }
} }
@ -635,7 +458,7 @@ public class DefaultUserInfo implements UserInfo {
Object o = in.readObject(); Object o = in.readObject();
if (o != null) { if (o != null) {
JsonParser parser = new JsonParser(); JsonParser parser = new JsonParser();
src = parser.parse((String)o).getAsJsonObject(); source = parser.parse((String)o).getAsJsonObject();
} }
} }

View File

@ -20,7 +20,11 @@
*/ */
package cz.muni.ics.openid.connect.model; package cz.muni.ics.openid.connect.model;
import javax.persistence.Basic; import static cz.muni.ics.openid.connect.model.PairwiseIdentifier.PARAM_SECTOR_IDENTIFIER;
import static cz.muni.ics.openid.connect.model.PairwiseIdentifier.PARAM_SUB;
import static cz.muni.ics.openid.connect.model.PairwiseIdentifier.QUERY_ALL;
import static cz.muni.ics.openid.connect.model.PairwiseIdentifier.QUERY_BY_SECTOR_IDENTIFIER;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
@ -29,6 +33,12 @@ import javax.persistence.Id;
import javax.persistence.NamedQueries; import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.Table; import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/** /**
* *
@ -37,11 +47,22 @@ import javax.persistence.Table;
* @author jricher * @author jricher
* *
*/ */
@Getter
@Setter
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
// DB ANNOTATIONS
@Entity @Entity
@Table(name = "pairwise_identifier") @Table(name = "pairwise_identifier")
@NamedQueries({ @NamedQueries({
@NamedQuery(name=PairwiseIdentifier.QUERY_ALL, query = "select p from PairwiseIdentifier p"), @NamedQuery(name = QUERY_ALL,
@NamedQuery(name=PairwiseIdentifier.QUERY_BY_SECTOR_IDENTIFIER, query = "select p from PairwiseIdentifier p WHERE p.userSub = :" + PairwiseIdentifier.PARAM_SUB + " AND p.sectorIdentifier = :" + PairwiseIdentifier.PARAM_SECTOR_IDENTIFIER) query = "SELECT p FROM PairwiseIdentifier p"),
@NamedQuery(name = QUERY_BY_SECTOR_IDENTIFIER,
query = "SELECT p FROM PairwiseIdentifier p " +
"WHERE p.userSub = :" + PARAM_SUB + ' ' +
"AND p.sectorIdentifier = :" + PARAM_SECTOR_IDENTIFIER)
}) })
public class PairwiseIdentifier { public class PairwiseIdentifier {
@ -51,50 +72,18 @@ public class PairwiseIdentifier {
public static final String PARAM_SECTOR_IDENTIFIER = "sectorIdentifier"; public static final String PARAM_SECTOR_IDENTIFIER = "sectorIdentifier";
public static final String PARAM_SUB = "sub"; public static final String PARAM_SUB = "sub";
private Long id;
private String identifier;
private String userSub;
private String sectorIdentifier;
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id") @Column(name = "id")
public Long getId() { private Long id;
return id;
}
public void setId(Long id) {
this.id = id;
}
@Basic
@Column(name = "identifier") @Column(name = "identifier")
public String getIdentifier() { private String identifier;
return identifier;
}
public void setIdentifier(String identifier) { @Column(name = PARAM_SUB)
this.identifier = identifier; private String userSub;
}
@Basic
@Column(name = PairwiseIdentifier.PARAM_SUB)
public String getUserSub() {
return userSub;
}
public void setUserSub(String userSub) {
this.userSub = userSub;
}
@Basic
@Column(name = "sector_identifier") @Column(name = "sector_identifier")
public String getSectorIdentifier() { private String sectorIdentifier;
return sectorIdentifier;
}
public void setSectorIdentifier(String sectorIdentifier) {
this.sectorIdentifier = sectorIdentifier;
}
} }

View File

@ -17,8 +17,13 @@
*******************************************************************************/ *******************************************************************************/
package cz.muni.ics.openid.connect.model; package cz.muni.ics.openid.connect.model;
import static cz.muni.ics.openid.connect.model.WhitelistedSite.PARAM_CLIENT_ID;
import static cz.muni.ics.openid.connect.model.WhitelistedSite.PARAM_USER_ID;
import static cz.muni.ics.openid.connect.model.WhitelistedSite.QUERY_ALL;
import static cz.muni.ics.openid.connect.model.WhitelistedSite.QUERY_BY_CLIENT_ID;
import static cz.muni.ics.openid.connect.model.WhitelistedSite.QUERY_BY_CREATOR;
import java.util.Set; import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.CollectionTable; import javax.persistence.CollectionTable;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.ElementCollection; import javax.persistence.ElementCollection;
@ -31,6 +36,13 @@ import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries; import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery; import javax.persistence.NamedQuery;
import javax.persistence.Table; import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.eclipse.persistence.annotations.CascadeOnDelete;
/** /**
* Indicator that login to a site should be automatically granted * Indicator that login to a site should be automatically granted
@ -38,12 +50,24 @@ import javax.persistence.Table;
* @author jricher, aanganes * @author jricher, aanganes
* *
*/ */
@Getter
@Setter
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
// DB ANNOTATIONS
@Entity @Entity
@Table(name="whitelisted_site") @Table(name="whitelisted_site")
@NamedQueries({ @NamedQueries({
@NamedQuery(name = WhitelistedSite.QUERY_ALL, query = "select w from WhitelistedSite w"), @NamedQuery(name = QUERY_ALL,
@NamedQuery(name = WhitelistedSite.QUERY_BY_CLIENT_ID, query = "select w from WhitelistedSite w where w.clientId = :" + WhitelistedSite.PARAM_CLIENT_ID), query = "SELECT w FROM WhitelistedSite w"),
@NamedQuery(name = WhitelistedSite.QUERY_BY_CREATOR, query = "select w from WhitelistedSite w where w.creatorUserId = :" + WhitelistedSite.PARAM_USER_ID) @NamedQuery(name = QUERY_BY_CLIENT_ID,
query = "SELECT w FROM WhitelistedSite w " +
"WHERE w.clientId = :" + PARAM_CLIENT_ID),
@NamedQuery(name = QUERY_BY_CREATOR,
query = "SELECT w FROM WhitelistedSite w " +
"WHERE w.creatorUserId = :" + PARAM_USER_ID)
}) })
public class WhitelistedSite { public class WhitelistedSite {
@ -54,53 +78,21 @@ public class WhitelistedSite {
public static final String PARAM_USER_ID = "userId"; public static final String PARAM_USER_ID = "userId";
public static final String PARAM_CLIENT_ID = "clientId"; public static final String PARAM_CLIENT_ID = "clientId";
private Long id;
private String creatorUserId;
private String clientId;
private Set<String> allowedScopes;
public WhitelistedSite() { }
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id") @Column(name = "id")
public Long getId() { private Long id;
return id;
}
public void setId(Long id) { @Column(name = "creator_user_id")
this.id = id; private String creatorUserId;
}
@Basic
@Column(name = "client_id") @Column(name = "client_id")
public String getClientId() { private String clientId;
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
@ElementCollection(fetch = FetchType.EAGER) @ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "whitelisted_site_scope", joinColumns = @JoinColumn(name = "owner_id")) @CollectionTable(name = "whitelisted_site_scope", joinColumns = @JoinColumn(name = "owner_id"))
@Column(name = "scope") @Column(name = "scope")
public Set<String> getAllowedScopes() { @CascadeOnDelete
return allowedScopes; private Set<String> allowedScopes;
}
public void setAllowedScopes(Set<String> allowedScopes) {
this.allowedScopes = allowedScopes;
}
@Basic
@Column(name="creator_user_id")
public String getCreatorUserId() {
return creatorUserId;
}
public void setCreatorUserId(String creatorUserId) {
this.creatorUserId = creatorUserId;
}
} }

View File

@ -1,137 +0,0 @@
package cz.muni.ics.openid.connect.models;
import static cz.muni.ics.openid.connect.models.Acr.PARAM_EXPIRES_AT;
import static cz.muni.ics.openid.connect.models.Acr.PARAM_SUB;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* Model of ACR.
*
* @author Dominik Frantisek Bucik <bucik@ics.muni.cz>
*/
@Entity
@Table(name = "acrs")
@NamedQueries({
@NamedQuery(name = Acr.GET_ACTIVE, query = "SELECT acr FROM Acr acr WHERE " +
"acr.sub = :" + PARAM_SUB +
" AND acr.clientId = :" + Acr.PARAM_CLIENT_ID +
" AND acr.state = :" + Acr.PARAM_STATE +
" AND acr.expiresAt > :" + PARAM_EXPIRES_AT),
@NamedQuery(name = Acr.GET_BY_ID,
query = "SELECT acr FROM Acr acr " +
"WHERE acr.id = :" + Acr.PARAM_ID +
" AND acr.expiresAt > :" + PARAM_EXPIRES_AT),
@NamedQuery(name = Acr.DELETE_EXPIRED,
query = "DELETE FROM Acr acr WHERE acr.expiresAt <= :" + Acr.PARAM_EXPIRES_AT)
})
public class Acr {
public static final String GET_ACTIVE = "Acr.getActive";
public static final String GET_BY_ID = "Acr.getById";
public static final String DELETE_EXPIRED = "Acr.deleteExpired";
public static final String PARAM_ID = "id";
public static final String PARAM_SUB = "sub";
public static final String PARAM_CLIENT_ID = "client_id";
public static final String PARAM_STATE = "state";
public static final String PARAM_EXPIRES_AT = "expiration";
private Long id;
private String sub;
private String clientId;
private String state;
private String shibAuthnContextClass;
private long expiresAt;
public Acr() { }
public Acr(String sub, String clientId, String state, String shibAuthnContextClass, long expiresAt) {
this.sub = sub;
this.clientId = clientId;
this.state = state;
this.shibAuthnContextClass = shibAuthnContextClass;
this.expiresAt = expiresAt;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Basic
@Column(name = "sub")
public String getSub() {
return sub;
}
public void setSub(String sub) {
this.sub = sub;
}
@Basic
@Column(name = "client_id")
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
@Basic
@Column(name = "state")
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Basic
@Column(name = "shib_authn_context_class")
public String getShibAuthnContextClass() {
return shibAuthnContextClass;
}
public void setShibAuthnContextClass(String shibAuthnContextClass) {
this.shibAuthnContextClass = shibAuthnContextClass;
}
@Basic
@Column(name = "expiration")
public long getExpiresAt() {
return expiresAt;
}
public void setExpiresAt(long expiresAt) {
this.expiresAt = expiresAt;
}
@Override
public String toString() {
return "Acr{" +
"id=" + id +
", sub='" + sub + '\'' +
", clientId='" + clientId + '\'' +
", state='" + state + '\'' +
", shibAuthnContextClass='" + shibAuthnContextClass + '\'' +
", expiration=" + expiresAt +
'}';
}
}

View File

@ -1,122 +0,0 @@
package cz.muni.ics.openid.connect.models;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* Model of ACR for device_code flow.
*
* @author Dominik Frantisek Bucik <bucik@ics.muni.cz>
*/
@Entity
@Table(name = "device_code_acrs")
@NamedQueries({
@NamedQuery(name = DeviceCodeAcr.GET_ACTIVE_BY_DEVICE_CODE,
query = "SELECT acr FROM DeviceCodeAcr acr WHERE " +
"acr.deviceCode = :" + DeviceCodeAcr.PARAM_DEVICE_CODE +
" AND acr.expiresAt > :" + DeviceCodeAcr.PARAM_EXPIRES_AT),
@NamedQuery(name = DeviceCodeAcr.GET_BY_ID,
query = "SELECT acr FROM DeviceCodeAcr acr " +
"WHERE acr.id = :" + DeviceCodeAcr.PARAM_ID +
" AND acr.expiresAt > :" + DeviceCodeAcr.PARAM_EXPIRES_AT),
@NamedQuery(name = DeviceCodeAcr.GET_BY_USER_CODE,
query = "SELECT acr FROM DeviceCodeAcr acr " +
"WHERE acr.userCode = :" + DeviceCodeAcr.PARAM_USER_CODE),
@NamedQuery(name = DeviceCodeAcr.DELETE_EXPIRED,
query = "DELETE FROM DeviceCodeAcr acr WHERE acr.expiresAt <= :" + DeviceCodeAcr.PARAM_EXPIRES_AT)
})
public class DeviceCodeAcr {
public static final String GET_ACTIVE_BY_DEVICE_CODE = "DeviceCodeAcr.getActive";
public static final String GET_BY_ID = "DeviceCodeAcr.getById";
public static final String DELETE_EXPIRED = "DeviceCodeAcr.deleteExpired";
public static final String GET_BY_USER_CODE = "DeviceCodeAcr.getByUserCode";
public static final String PARAM_ID = "id";
public static final String PARAM_USER_CODE = "user_code";
public static final String PARAM_DEVICE_CODE = "device_code";
public static final String PARAM_EXPIRES_AT = "expiration";
private Long id;
private String userCode;
private String deviceCode;
private String shibAuthnContextClass;
private long expiresAt;
public DeviceCodeAcr() { }
public DeviceCodeAcr(String deviceCode, String userCode) {
this.deviceCode = deviceCode;
this.userCode = userCode;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Basic
@Column(name = "device_code")
public String getDeviceCode() {
return deviceCode;
}
public void setDeviceCode(String deviceCode) {
this.deviceCode = deviceCode;
}
@Basic
@Column(name = "user_code")
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
@Basic
@Column(name = "shib_authn_context_class")
public String getShibAuthnContextClass() {
return shibAuthnContextClass;
}
public void setShibAuthnContextClass(String shibAuthnContextClass) {
this.shibAuthnContextClass = shibAuthnContextClass;
}
@Basic
@Column(name = "expiration")
public long getExpiresAt() {
return expiresAt;
}
public void setExpiresAt(long expiresAt) {
this.expiresAt = expiresAt;
}
@Override
public String toString() {
return "Acr{" +
"id=" + id +
", deviceCode='" + deviceCode + '\'' +
", userCode='" + userCode + '\'' +
", shibAuthnContextClass='" + shibAuthnContextClass + '\'' +
", expiration=" + expiresAt +
'}';
}
}

View File

@ -18,7 +18,7 @@
package cz.muni.ics.openid.connect.service.impl; package cz.muni.ics.openid.connect.service.impl;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.ClientDetailsEntity.SubjectType; import cz.muni.ics.oauth2.model.enums.SubjectType;
import cz.muni.ics.oauth2.service.ClientDetailsEntityService; import cz.muni.ics.oauth2.service.ClientDetailsEntityService;
import cz.muni.ics.openid.connect.model.UserInfo; import cz.muni.ics.openid.connect.model.UserInfo;
import cz.muni.ics.openid.connect.repository.UserInfoRepository; import cz.muni.ics.openid.connect.repository.UserInfoRepository;

View File

@ -1,71 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.openid.connect.service.impl;
import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.uma.model.ResourceSet;
import cz.muni.ics.uma.service.ResourceSetService;
import java.util.Collection;
import java.util.Collections;
import org.springframework.stereotype.Service;
/**
* Dummy resource set service that doesn't do anything; acts as a stub for the
* introspection service when the UMA functionality is disabled.
*
* @author jricher
*
*/
@Service
public class DummyResourceSetService implements ResourceSetService {
@Override
public ResourceSet saveNew(ResourceSet rs) {
throw new UnsupportedOperationException();
}
@Override
public ResourceSet getById(Long id) {
throw new UnsupportedOperationException();
}
@Override
public ResourceSet update(ResourceSet oldRs, ResourceSet newRs) {
throw new UnsupportedOperationException();
}
@Override
public void remove(ResourceSet rs) {
throw new UnsupportedOperationException();
}
@Override
public Collection<ResourceSet> getAllForOwner(String owner) {
throw new UnsupportedOperationException();
}
@Override
public Collection<ResourceSet> getAllForOwnerAndClient(String owner, String authClientId) {
return Collections.emptySet();
}
@Override
public Collection<ResourceSet> getAllForClient(ClientDetailsEntity client) {
return Collections.emptySet();
}
}

View File

@ -76,10 +76,10 @@ import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.JWTParser; import com.nimbusds.jwt.JWTParser;
import cz.muni.ics.jwt.assertion.AssertionValidator; import cz.muni.ics.jwt.assertion.AssertionValidator;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.ClientDetailsEntity.AppType;
import cz.muni.ics.oauth2.model.ClientDetailsEntity.AuthMethod;
import cz.muni.ics.oauth2.model.ClientDetailsEntity.SubjectType;
import cz.muni.ics.oauth2.model.PKCEAlgorithm; import cz.muni.ics.oauth2.model.PKCEAlgorithm;
import cz.muni.ics.oauth2.model.enums.AppType;
import cz.muni.ics.oauth2.model.enums.AuthMethod;
import cz.muni.ics.oauth2.model.enums.SubjectType;
import cz.muni.ics.oauth2.service.ClientDetailsEntityService; import cz.muni.ics.oauth2.service.ClientDetailsEntityService;
import cz.muni.ics.oauth2.web.AuthenticationUtilities; import cz.muni.ics.oauth2.web.AuthenticationUtilities;
import cz.muni.ics.openid.connect.exception.ValidationException; import cz.muni.ics.openid.connect.exception.ValidationException;

View File

@ -66,12 +66,12 @@ import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.JWTClaimsSet;
import cz.muni.ics.jwt.assertion.AssertionValidator; import cz.muni.ics.jwt.assertion.AssertionValidator;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.ClientDetailsEntity.AppType;
import cz.muni.ics.oauth2.model.ClientDetailsEntity.AuthMethod;
import cz.muni.ics.oauth2.model.ClientDetailsEntity.SubjectType;
import cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity; import cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity;
import cz.muni.ics.oauth2.model.RegisteredClient; import cz.muni.ics.oauth2.model.RegisteredClient;
import cz.muni.ics.oauth2.model.SystemScope; import cz.muni.ics.oauth2.model.SystemScope;
import cz.muni.ics.oauth2.model.enums.AppType;
import cz.muni.ics.oauth2.model.enums.AuthMethod;
import cz.muni.ics.oauth2.model.enums.SubjectType;
import cz.muni.ics.oauth2.service.ClientDetailsEntityService; import cz.muni.ics.oauth2.service.ClientDetailsEntityService;
import cz.muni.ics.oauth2.service.OAuth2TokenEntityService; import cz.muni.ics.oauth2.service.OAuth2TokenEntityService;
import cz.muni.ics.oauth2.service.SystemScopeService; import cz.muni.ics.oauth2.service.SystemScopeService;

View File

@ -18,10 +18,10 @@ package cz.muni.ics.openid.connect.web;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import com.google.gson.JsonSyntaxException; import com.google.gson.JsonSyntaxException;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.ClientDetailsEntity.AuthMethod;
import cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity; import cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity;
import cz.muni.ics.oauth2.model.RegisteredClient; import cz.muni.ics.oauth2.model.RegisteredClient;
import cz.muni.ics.oauth2.model.SystemScope; import cz.muni.ics.oauth2.model.SystemScope;
import cz.muni.ics.oauth2.model.enums.AuthMethod;
import cz.muni.ics.oauth2.service.ClientDetailsEntityService; import cz.muni.ics.oauth2.service.ClientDetailsEntityService;
import cz.muni.ics.oauth2.service.OAuth2TokenEntityService; import cz.muni.ics.oauth2.service.OAuth2TokenEntityService;
import cz.muni.ics.oauth2.service.SystemScopeService; import cz.muni.ics.oauth2.service.SystemScopeService;

View File

@ -1,203 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.model;
import com.google.gson.JsonElement;
import cz.muni.ics.oauth2.model.convert.JsonElementStringConverter;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
/**
* @author jricher
*/
@Entity
@Table(name = "claim")
public class Claim {
private Long id;
private String name;
private String friendlyName;
private String claimType;
private JsonElement value;
private Set<String> claimTokenFormat;
private Set<String> issuer;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Basic
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "friendly_name")
public String getFriendlyName() {
return friendlyName;
}
public void setFriendlyName(String friendlyName) {
this.friendlyName = friendlyName;
}
@Basic
@Column(name = "claim_type")
public String getClaimType() {
return claimType;
}
public void setClaimType(String claimType) {
this.claimType = claimType;
}
@ElementCollection(fetch = FetchType.EAGER)
@Column(name = "claim_token_format")
@CollectionTable(name = "claim_token_format", joinColumns = @JoinColumn(name = "owner_id"))
public Set<String> getClaimTokenFormat() {
return claimTokenFormat;
}
public void setClaimTokenFormat(Set<String> claimTokenFormat) {
this.claimTokenFormat = claimTokenFormat;
}
@ElementCollection(fetch = FetchType.EAGER)
@Column(name = "issuer")
@CollectionTable(name = "claim_issuer", joinColumns = @JoinColumn(name = "owner_id"))
public Set<String> getIssuer() {
return issuer;
}
public void setIssuer(Set<String> issuer) {
this.issuer = issuer;
}
@Basic
@Column(name = "claim_value")
@Convert(converter = JsonElementStringConverter.class)
public JsonElement getValue() {
return value;
}
public void setValue(JsonElement value) {
this.value = value;
}
@Override
public String toString() {
return "Claim [id=" + id + ", name=" + name + ", friendlyName=" + friendlyName + ", claimType=" + claimType + ", value=" + value + ", claimTokenFormat=" + claimTokenFormat + ", issuer=" + issuer + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((claimTokenFormat == null) ? 0 : claimTokenFormat.hashCode());
result = prime * result + ((claimType == null) ? 0 : claimType.hashCode());
result = prime * result + ((friendlyName == null) ? 0 : friendlyName.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((issuer == null) ? 0 : issuer.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Claim other = (Claim) obj;
if (claimTokenFormat == null) {
if (other.claimTokenFormat != null) {
return false;
}
} else if (!claimTokenFormat.equals(other.claimTokenFormat)) {
return false;
}
if (claimType == null) {
if (other.claimType != null) {
return false;
}
} else if (!claimType.equals(other.claimType)) {
return false;
}
if (friendlyName == null) {
if (other.friendlyName != null) {
return false;
}
} else if (!friendlyName.equals(other.friendlyName)) {
return false;
}
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (issuer == null) {
if (other.issuer != null) {
return false;
}
} else if (!issuer.equals(other.issuer)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (value == null) {
return other.value == null;
} else return value.equals(other.value);
}
}

View File

@ -1,68 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.model;
import java.util.Collection;
/**
* Data shuttle to return results of the claims processing service.
*
* @author jricher
*/
public class ClaimProcessingResult {
private boolean satisfied;
private Collection<Claim> unmatched;
private Policy matched;
public ClaimProcessingResult(Collection<Claim> unmatched) {
this.satisfied = false;
this.unmatched = unmatched;
this.matched = null;
}
public ClaimProcessingResult(Policy matched) {
this.satisfied = true;
this.matched = matched;
this.unmatched = null;
}
public boolean isSatisfied() {
return satisfied;
}
public void setSatisfied(boolean satisfied) {
this.satisfied = satisfied;
}
public Collection<Claim> getUnmatched() {
return unmatched;
}
public void setUnmatched(Collection<Claim> unmatched) {
this.unmatched = unmatched;
}
public Policy getMatched() {
return matched;
}
public void setMatched(Policy matched) {
this.matched = matched;
}
}

View File

@ -1,75 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.model;
import java.util.Set;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* @author jricher
*/
@Entity
@Table(name = "permission")
public class Permission {
private Long id;
private ResourceSet resourceSet;
private Set<String> scopes;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "resource_set_id")
public ResourceSet getResourceSet() {
return resourceSet;
}
public void setResourceSet(ResourceSet resourceSet) {
this.resourceSet = resourceSet;
}
@ElementCollection(fetch = FetchType.EAGER)
@Column(name = "scope")
@CollectionTable(name = "permission_scope", joinColumns = @JoinColumn(name = "owner_id"))
public Set<String> getScopes() {
return scopes;
}
public void setScopes(Set<String> scopes) {
this.scopes = scopes;
}
}

View File

@ -1,121 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.model;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* An UMA permission, used in the protection API.
*
* @author jricher
*
*/
@Entity
@Table(name = "permission_ticket")
@NamedQueries({
@NamedQuery(name = PermissionTicket.QUERY_TICKET, query = "select p from PermissionTicket p where p.ticket = :" + PermissionTicket.PARAM_TICKET),
@NamedQuery(name = PermissionTicket.QUERY_ALL, query = "select p from PermissionTicket p"),
@NamedQuery(name = PermissionTicket.QUERY_BY_RESOURCE_SET, query = "select p from PermissionTicket p where p.permission.resourceSet.id = :" + PermissionTicket.PARAM_RESOURCE_SET_ID)
})
public class PermissionTicket {
public static final String QUERY_TICKET = "PermissionTicket.queryByTicket";
public static final String QUERY_ALL = "PermissionTicket.queryAll";
public static final String QUERY_BY_RESOURCE_SET = "PermissionTicket.queryByResourceSet";
public static final String PARAM_TICKET = "ticket";
public static final String PARAM_RESOURCE_SET_ID = "rsid";
private Long id;
private Permission permission;
private String ticket;
private Date expiration;
private Collection<Claim> claimsSupplied;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "permission_id")
public Permission getPermission() {
return permission;
}
public void setPermission(Permission permission) {
this.permission = permission;
}
@Basic
@Column(name = "ticket")
public String getTicket() {
return ticket;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
@Basic
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "expiration")
public Date getExpiration() {
return expiration;
}
public void setExpiration(Date expiration) {
this.expiration = expiration;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "claim_to_permission_ticket", joinColumns = @JoinColumn(name = "permission_ticket_id"),
inverseJoinColumns = @JoinColumn(name = "claim_id"))
public Collection<Claim> getClaimsSupplied() {
return claimsSupplied;
}
public void setClaimsSupplied(Collection<Claim> claimsSupplied) {
this.claimsSupplied = claimsSupplied;
}
}

View File

@ -1,147 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.model;
import java.util.Collection;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* A set of claims required to fulfill a given permission.
*
* @author jricher
*/
@Entity
@Table(name = "policy")
public class Policy {
private Long id;
private String name;
private Collection<Claim> claimsRequired;
private Set<String> scopes;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Basic
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "claim_to_policy", joinColumns = @JoinColumn(name = "policy_id"),
inverseJoinColumns = @JoinColumn(name = "claim_id"))
public Collection<Claim> getClaimsRequired() {
return claimsRequired;
}
public void setClaimsRequired(Collection<Claim> claimsRequired) {
this.claimsRequired = claimsRequired;
}
@ElementCollection(fetch = FetchType.EAGER)
@Column(name = "scope")
@CollectionTable(name = "policy_scope", joinColumns = @JoinColumn(name = "owner_id"))
public Set<String> getScopes() {
return scopes;
}
public void setScopes(Set<String> scopes) {
this.scopes = scopes;
}
@Override
public String toString() {
return "Policy [id=" + id + ", name=" + name + ", claimsRequired=" + claimsRequired + ", scopes=" + scopes + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((claimsRequired == null) ? 0 : claimsRequired.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((scopes == null) ? 0 : scopes.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Policy other = (Policy) obj;
if (claimsRequired == null) {
if (other.claimsRequired != null) {
return false;
}
} else if (!claimsRequired.equals(other.claimsRequired)) {
return false;
}
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (scopes == null) {
return other.scopes == null;
} else return scopes.equals(other.scopes);
}
}

View File

@ -1,255 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.model;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "resource_set")
@NamedQueries ({
@NamedQuery(name = ResourceSet.QUERY_BY_OWNER, query = "select r from ResourceSet r where r.owner = :" + ResourceSet.PARAM_OWNER),
@NamedQuery(name = ResourceSet.QUERY_BY_OWNER_AND_CLIENT, query = "select r from ResourceSet r where r.owner = :" + ResourceSet.PARAM_OWNER + " and r.clientId = :" + ResourceSet.PARAM_CLIENTID),
@NamedQuery(name = ResourceSet.QUERY_BY_CLIENT, query = "select r from ResourceSet r where r.clientId = :" + ResourceSet.PARAM_CLIENTID),
@NamedQuery(name = ResourceSet.QUERY_ALL, query = "select r from ResourceSet r")
})
public class ResourceSet {
public static final String QUERY_BY_OWNER = "ResourceSet.queryByOwner";
public static final String QUERY_BY_OWNER_AND_CLIENT = "ResourceSet.queryByOwnerAndClient";
public static final String QUERY_BY_CLIENT = "ResourceSet.queryByClient";
public static final String QUERY_ALL = "ResourceSet.queryAll";
public static final String PARAM_OWNER = "owner";
public static final String PARAM_CLIENTID = "clientId";
private Long id;
private String name;
private String uri;
private String type;
private Set<String> scopes = new HashSet<>();
private String iconUri;
private String owner; // username of the person responsible for the registration (either directly or via OAuth token)
private String clientId; // client id of the protected resource that registered this resource set via OAuth token
private Collection<Policy> policies = new HashSet<>();
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Basic
@Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "uri")
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
@Basic
@Column(name = "rs_type")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@ElementCollection(fetch = FetchType.EAGER)
@Column(name = "scope")
@CollectionTable(name = "resource_set_scope", joinColumns = @JoinColumn(name = "owner_id"))
public Set<String> getScopes() {
return scopes;
}
public void setScopes(Set<String> scopes) {
this.scopes = scopes;
}
@Basic
@Column(name = "icon_uri")
public String getIconUri() {
return iconUri;
}
public void setIconUri(String iconUri) {
this.iconUri = iconUri;
}
@Basic
@Column(name = "owner")
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
@Basic
@Column(name = "client_id")
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "resource_set_id")
public Collection<Policy> getPolicies() {
return policies;
}
public void setPolicies(Collection<Policy> policies) {
this.policies = policies;
}
@Override
public String toString() {
return "ResourceSet [id=" + id + ", name=" + name + ", uri=" + uri + ", type=" + type + ", scopes=" + scopes + ", iconUri=" + iconUri + ", owner=" + owner + ", clientId=" + clientId + ", policies=" + policies + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((clientId == null) ? 0 : clientId.hashCode());
result = prime * result + ((iconUri == null) ? 0 : iconUri.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((owner == null) ? 0 : owner.hashCode());
result = prime * result + ((policies == null) ? 0 : policies.hashCode());
result = prime * result + ((scopes == null) ? 0 : scopes.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((uri == null) ? 0 : uri.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ResourceSet other = (ResourceSet) obj;
if (clientId == null) {
if (other.clientId != null) {
return false;
}
} else if (!clientId.equals(other.clientId)) {
return false;
}
if (iconUri == null) {
if (other.iconUri != null) {
return false;
}
} else if (!iconUri.equals(other.iconUri)) {
return false;
}
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (owner == null) {
if (other.owner != null) {
return false;
}
} else if (!owner.equals(other.owner)) {
return false;
}
if (policies == null) {
if (other.policies != null) {
return false;
}
} else if (!policies.equals(other.policies)) {
return false;
}
if (scopes == null) {
if (other.scopes != null) {
return false;
}
} else if (!scopes.equals(other.scopes)) {
return false;
}
if (type == null) {
if (other.type != null) {
return false;
}
} else if (!type.equals(other.type)) {
return false;
}
if (uri == null) {
return other.uri == null;
} else return uri.equals(other.uri);
}
}

View File

@ -1,73 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.model;
import cz.muni.ics.oauth2.model.RegisteredClient;
import cz.muni.ics.uma.model.convert.RegisteredClientStringConverter;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author jricher
*/
@Entity
@Table(name = "saved_registered_client")
public class SavedRegisteredClient {
private Long id;
private String issuer;
private RegisteredClient registeredClient;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Basic
@Column(name = "issuer")
public String getIssuer() {
return issuer;
}
public void setIssuer(String issuer) {
this.issuer = issuer;
}
@Basic
@Column(name = "registered_client")
@Convert(converter = RegisteredClientStringConverter.class)
public RegisteredClient getRegisteredClient() {
return registeredClient;
}
public void setRegisteredClient(RegisteredClient registeredClient) {
this.registeredClient = registeredClient;
}
}

View File

@ -1,41 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.model.convert;
import cz.muni.ics.oauth2.model.RegisteredClient;
import cz.muni.ics.openid.connect.ClientDetailsEntityJsonProcessor;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import org.springframework.util.StringUtils;
/**
* @author jricher
*/
@Converter
public class RegisteredClientStringConverter implements AttributeConverter<RegisteredClient, String>{
@Override
public String convertToDatabaseColumn(RegisteredClient attribute) {
return attribute == null || attribute.getSource() == null ? null : attribute.getSource().toString();
}
@Override
public RegisteredClient convertToEntityAttribute(String dbData) {
return StringUtils.isEmpty(dbData) ? null : ClientDetailsEntityJsonProcessor.parseRegistered(dbData);
}
}

View File

@ -1,43 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.repository;
import cz.muni.ics.uma.model.Permission;
import cz.muni.ics.uma.model.PermissionTicket;
import cz.muni.ics.uma.model.ResourceSet;
import java.util.Collection;
/**
* @author jricher
*/
public interface PermissionRepository {
PermissionTicket save(PermissionTicket p);
PermissionTicket getByTicket(String ticket);
Collection<PermissionTicket> getAll();
Permission saveRawPermission(Permission p);
Permission getById(Long permissionId);
Collection<PermissionTicket> getPermissionTicketsForResourceSet(ResourceSet rs);
void remove(PermissionTicket ticket);
}

View File

@ -1,41 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.repository;
import cz.muni.ics.uma.model.ResourceSet;
import java.util.Collection;
/**
* @author jricher
*/
public interface ResourceSetRepository {
ResourceSet save(ResourceSet rs);
ResourceSet getById(Long id);
void remove(ResourceSet rs);
Collection<ResourceSet> getAllForOwner(String owner);
Collection<ResourceSet> getAllForOwnerAndClient(String owner, String clientId);
Collection<ResourceSet> getAll();
Collection<ResourceSet> getAllForClient(String clientId);
}

View File

@ -1,42 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.service;
import cz.muni.ics.uma.model.ClaimProcessingResult;
import cz.muni.ics.uma.model.PermissionTicket;
import cz.muni.ics.uma.model.ResourceSet;
/**
* Processes claims presented during an UMA transaction.
*
* @author jricher
*/
public interface ClaimsProcessingService {
/**
*
* Determine whether or not the claims that have been supplied are
* sufficient to fulfill the requirements given by the claims that
* are required.
*
* @param rs the required claims to check against
* @param ticket the supplied claims to test
* @return the result of the claims processing action
*/
ClaimProcessingResult claimsAreSatisfied(ResourceSet rs, PermissionTicket ticket);
}

View File

@ -1,54 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.service;
import cz.muni.ics.uma.model.PermissionTicket;
import cz.muni.ics.uma.model.ResourceSet;
import java.util.Set;
import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException;
/**
* @author jricher
*/
public interface PermissionService {
/**
* @param resourceSet the resource set to create the permission on
* @param scopes the set of scopes that this permission is for
* @return the created (and stored) permission object, with ticket
* @throws InsufficientScopeException if the scopes in scopes don't match those in resourceSet.getScopes
*/
PermissionTicket createTicket(ResourceSet resourceSet, Set<String> scopes);
/**
* Read the permission associated with the given ticket.
*
* @param the ticket value to search on
* @return the permission object, or null if none is found
*/
PermissionTicket getByTicket(String ticket);
/**
* Save the updated permission ticket to the database. Does not create a new ticket.
*
* @param ticket
* @return
*/
PermissionTicket updateTicket(PermissionTicket ticket);
}

View File

@ -1,43 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.service;
import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.uma.model.ResourceSet;
import java.util.Collection;
/**
* Manage registered resource sets at this authorization server.
*
* @author jricher
*/
public interface ResourceSetService {
ResourceSet saveNew(ResourceSet rs);
ResourceSet getById(Long id);
ResourceSet update(ResourceSet oldRs, ResourceSet newRs);
void remove(ResourceSet rs);
Collection<ResourceSet> getAllForOwner(String owner);
Collection<ResourceSet> getAllForOwnerAndClient(String owner, String authClientId);
Collection<ResourceSet> getAllForClient(ClientDetailsEntity client);
}

View File

@ -1,42 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.service;
import cz.muni.ics.oauth2.model.RegisteredClient;
import cz.muni.ics.uma.model.SavedRegisteredClient;
import java.util.Collection;
/**
* @author jricher
*/
public interface SavedRegisteredClientService {
/**
* Get a list of all the registered clients that we know about.
*
* @return
*/
Collection<SavedRegisteredClient> getAll();
/**
* @param issuer
* @param client
*/
void save(String issuer, RegisteredClient client);
}

View File

@ -1,37 +0,0 @@
/*******************************************************************************
* Copyright 2018 The MIT Internet Trust Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package cz.muni.ics.uma.service;
import cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity;
import cz.muni.ics.uma.model.PermissionTicket;
import cz.muni.ics.uma.model.Policy;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
/**
* Service to create special tokens for UMA.
*
* @author jricher
*
*/
public interface UmaTokenService {
/**
* Create the RPT from the given authentication and ticket.
*/
OAuth2AccessTokenEntity createRequestingPartyToken(OAuth2Authentication o2auth, PermissionTicket ticket, Policy policy);
}

View File

@ -25,6 +25,9 @@ import static org.junit.Assert.assertEquals;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.nimbusds.jose.EncryptionMethod; import com.nimbusds.jose.EncryptionMethod;
import com.nimbusds.jose.JWEAlgorithm; import com.nimbusds.jose.JWEAlgorithm;
import cz.muni.ics.oauth2.model.enums.AppType;
import cz.muni.ics.oauth2.model.enums.AuthMethod;
import cz.muni.ics.oauth2.model.enums.SubjectType;
import java.util.Date; import java.util.Date;
import org.junit.Test; import org.junit.Test;
@ -45,12 +48,12 @@ public class ClientDetailsEntityTest {
c.setClientId("s6BhdRkqt3"); c.setClientId("s6BhdRkqt3");
c.setClientSecret("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk"); c.setClientSecret("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk");
c.setApplicationType(ClientDetailsEntity.AppType.WEB); c.setApplicationType(AppType.WEB);
c.setRedirectUris(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2")); c.setRedirectUris(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"));
c.setClientName("My Example"); c.setClientName("My Example");
c.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); c.setSubjectType(SubjectType.PAIRWISE);
c.setSectorIdentifierUri("https://other.example.net/file_of_redirect_uris.json"); c.setSectorIdentifierUri("https://other.example.net/file_of_redirect_uris.json");
c.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.SECRET_BASIC); c.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC);
c.setJwksUri("https://client.example.org/my_public_keys.jwks"); c.setJwksUri("https://client.example.org/my_public_keys.jwks");
c.setUserInfoEncryptedResponseAlg(JWEAlgorithm.RSA1_5); c.setUserInfoEncryptedResponseAlg(JWEAlgorithm.RSA1_5);
c.setUserInfoEncryptedResponseEnc(EncryptionMethod.A128CBC_HS256); c.setUserInfoEncryptedResponseEnc(EncryptionMethod.A128CBC_HS256);
@ -61,12 +64,12 @@ public class ClientDetailsEntityTest {
assertEquals("s6BhdRkqt3", c.getClientId()); assertEquals("s6BhdRkqt3", c.getClientId());
assertEquals("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk", c.getClientSecret()); assertEquals("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk", c.getClientSecret());
assertEquals(ClientDetailsEntity.AppType.WEB, c.getApplicationType()); assertEquals(AppType.WEB, c.getApplicationType());
assertEquals(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"), c.getRedirectUris()); assertEquals(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"), c.getRedirectUris());
assertEquals("My Example", c.getClientName()); assertEquals("My Example", c.getClientName());
assertEquals(ClientDetailsEntity.SubjectType.PAIRWISE, c.getSubjectType()); assertEquals(SubjectType.PAIRWISE, c.getSubjectType());
assertEquals("https://other.example.net/file_of_redirect_uris.json", c.getSectorIdentifierUri()); assertEquals("https://other.example.net/file_of_redirect_uris.json", c.getSectorIdentifierUri());
assertEquals(ClientDetailsEntity.AuthMethod.SECRET_BASIC, c.getTokenEndpointAuthMethod()); assertEquals(AuthMethod.SECRET_BASIC, c.getTokenEndpointAuthMethod());
assertEquals("https://client.example.org/my_public_keys.jwks", c.getJwksUri()); assertEquals("https://client.example.org/my_public_keys.jwks", c.getJwksUri());
assertEquals(JWEAlgorithm.RSA1_5, c.getUserInfoEncryptedResponseAlg()); assertEquals(JWEAlgorithm.RSA1_5, c.getUserInfoEncryptedResponseAlg());
assertEquals(EncryptionMethod.A128CBC_HS256, c.getUserInfoEncryptedResponseEnc()); assertEquals(EncryptionMethod.A128CBC_HS256, c.getUserInfoEncryptedResponseEnc());

View File

@ -25,6 +25,9 @@ import static org.junit.Assert.assertEquals;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.nimbusds.jose.EncryptionMethod; import com.nimbusds.jose.EncryptionMethod;
import com.nimbusds.jose.JWEAlgorithm; import com.nimbusds.jose.JWEAlgorithm;
import cz.muni.ics.oauth2.model.enums.AppType;
import cz.muni.ics.oauth2.model.enums.AuthMethod;
import cz.muni.ics.oauth2.model.enums.SubjectType;
import java.sql.Date; import java.sql.Date;
import org.junit.Test; import org.junit.Test;
@ -49,12 +52,12 @@ public class RegisteredClientTest {
c.setClientSecretExpiresAt(new Date(1577858400L * 1000L)); c.setClientSecretExpiresAt(new Date(1577858400L * 1000L));
c.setRegistrationAccessToken("this.is.an.access.token.value.ffx83"); c.setRegistrationAccessToken("this.is.an.access.token.value.ffx83");
c.setRegistrationClientUri("https://server.example.com/connect/register?client_id=s6BhdRkqt3"); c.setRegistrationClientUri("https://server.example.com/connect/register?client_id=s6BhdRkqt3");
c.setApplicationType(ClientDetailsEntity.AppType.WEB); c.setApplicationType(AppType.WEB);
c.setRedirectUris(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2")); c.setRedirectUris(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"));
c.setClientName("My Example"); c.setClientName("My Example");
c.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); c.setSubjectType(SubjectType.PAIRWISE);
c.setSectorIdentifierUri("https://other.example.net/file_of_redirect_uris.json"); c.setSectorIdentifierUri("https://other.example.net/file_of_redirect_uris.json");
c.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.SECRET_BASIC); c.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC);
c.setJwksUri("https://client.example.org/my_public_keys.jwks"); c.setJwksUri("https://client.example.org/my_public_keys.jwks");
c.setUserInfoEncryptedResponseAlg(JWEAlgorithm.RSA1_5); c.setUserInfoEncryptedResponseAlg(JWEAlgorithm.RSA1_5);
c.setUserInfoEncryptedResponseEnc(EncryptionMethod.A128CBC_HS256); c.setUserInfoEncryptedResponseEnc(EncryptionMethod.A128CBC_HS256);
@ -66,12 +69,12 @@ public class RegisteredClientTest {
assertEquals(new Date(1577858400L * 1000L), c.getClientSecretExpiresAt()); assertEquals(new Date(1577858400L * 1000L), c.getClientSecretExpiresAt());
assertEquals("this.is.an.access.token.value.ffx83", c.getRegistrationAccessToken()); assertEquals("this.is.an.access.token.value.ffx83", c.getRegistrationAccessToken());
assertEquals("https://server.example.com/connect/register?client_id=s6BhdRkqt3", c.getRegistrationClientUri()); assertEquals("https://server.example.com/connect/register?client_id=s6BhdRkqt3", c.getRegistrationClientUri());
assertEquals(ClientDetailsEntity.AppType.WEB, c.getApplicationType()); assertEquals(AppType.WEB, c.getApplicationType());
assertEquals(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"), c.getRedirectUris()); assertEquals(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"), c.getRedirectUris());
assertEquals("My Example", c.getClientName()); assertEquals("My Example", c.getClientName());
assertEquals(ClientDetailsEntity.SubjectType.PAIRWISE, c.getSubjectType()); assertEquals(SubjectType.PAIRWISE, c.getSubjectType());
assertEquals("https://other.example.net/file_of_redirect_uris.json", c.getSectorIdentifierUri()); assertEquals("https://other.example.net/file_of_redirect_uris.json", c.getSectorIdentifierUri());
assertEquals(ClientDetailsEntity.AuthMethod.SECRET_BASIC, c.getTokenEndpointAuthMethod()); assertEquals(AuthMethod.SECRET_BASIC, c.getTokenEndpointAuthMethod());
assertEquals("https://client.example.org/my_public_keys.jwks", c.getJwksUri()); assertEquals("https://client.example.org/my_public_keys.jwks", c.getJwksUri());
assertEquals(JWEAlgorithm.RSA1_5, c.getUserInfoEncryptedResponseAlg()); assertEquals(JWEAlgorithm.RSA1_5, c.getUserInfoEncryptedResponseAlg());
assertEquals(EncryptionMethod.A128CBC_HS256, c.getUserInfoEncryptedResponseEnc()); assertEquals(EncryptionMethod.A128CBC_HS256, c.getUserInfoEncryptedResponseEnc());
@ -88,13 +91,13 @@ public class RegisteredClientTest {
c.setClientId("s6BhdRkqt3"); c.setClientId("s6BhdRkqt3");
c.setClientSecret("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk"); c.setClientSecret("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk");
c.setApplicationType(ClientDetailsEntity.AppType.WEB); c.setApplicationType(AppType.WEB);
c.setRedirectUris(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2")); c.setRedirectUris(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"));
c.setClientName("My Example"); c.setClientName("My Example");
c.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); c.setSubjectType(SubjectType.PAIRWISE);
c.setSectorIdentifierUri("https://other.example.net/file_of_redirect_uris.json"); c.setSectorIdentifierUri("https://other.example.net/file_of_redirect_uris.json");
c.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.SECRET_BASIC); c.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC);
c.setJwksUri("https://client.example.org/my_public_keys.jwks"); c.setJwksUri("https://client.example.org/my_public_keys.jwks");
c.setUserInfoEncryptedResponseAlg(JWEAlgorithm.RSA1_5); c.setUserInfoEncryptedResponseAlg(JWEAlgorithm.RSA1_5);
c.setUserInfoEncryptedResponseEnc(EncryptionMethod.A128CBC_HS256); c.setUserInfoEncryptedResponseEnc(EncryptionMethod.A128CBC_HS256);
@ -113,12 +116,12 @@ public class RegisteredClientTest {
assertEquals(new Date(1577858400L * 1000L), rc.getClientSecretExpiresAt()); assertEquals(new Date(1577858400L * 1000L), rc.getClientSecretExpiresAt());
assertEquals("this.is.an.access.token.value.ffx83", rc.getRegistrationAccessToken()); assertEquals("this.is.an.access.token.value.ffx83", rc.getRegistrationAccessToken());
assertEquals("https://server.example.com/connect/register?client_id=s6BhdRkqt3", rc.getRegistrationClientUri()); assertEquals("https://server.example.com/connect/register?client_id=s6BhdRkqt3", rc.getRegistrationClientUri());
assertEquals(ClientDetailsEntity.AppType.WEB, rc.getApplicationType()); assertEquals(AppType.WEB, rc.getApplicationType());
assertEquals(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"), rc.getRedirectUris()); assertEquals(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"), rc.getRedirectUris());
assertEquals("My Example", rc.getClientName()); assertEquals("My Example", rc.getClientName());
assertEquals(ClientDetailsEntity.SubjectType.PAIRWISE, rc.getSubjectType()); assertEquals(SubjectType.PAIRWISE, rc.getSubjectType());
assertEquals("https://other.example.net/file_of_redirect_uris.json", rc.getSectorIdentifierUri()); assertEquals("https://other.example.net/file_of_redirect_uris.json", rc.getSectorIdentifierUri());
assertEquals(ClientDetailsEntity.AuthMethod.SECRET_BASIC, rc.getTokenEndpointAuthMethod()); assertEquals(AuthMethod.SECRET_BASIC, rc.getTokenEndpointAuthMethod());
assertEquals("https://client.example.org/my_public_keys.jwks", rc.getJwksUri()); assertEquals("https://client.example.org/my_public_keys.jwks", rc.getJwksUri());
assertEquals(JWEAlgorithm.RSA1_5, rc.getUserInfoEncryptedResponseAlg()); assertEquals(JWEAlgorithm.RSA1_5, rc.getUserInfoEncryptedResponseAlg());
assertEquals(EncryptionMethod.A128CBC_HS256, rc.getUserInfoEncryptedResponseEnc()); assertEquals(EncryptionMethod.A128CBC_HS256, rc.getUserInfoEncryptedResponseEnc());
@ -135,13 +138,13 @@ public class RegisteredClientTest {
c.setClientId("s6BhdRkqt3"); c.setClientId("s6BhdRkqt3");
c.setClientSecret("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk"); c.setClientSecret("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk");
c.setApplicationType(ClientDetailsEntity.AppType.WEB); c.setApplicationType(AppType.WEB);
c.setRedirectUris(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2")); c.setRedirectUris(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"));
c.setClientName("My Example"); c.setClientName("My Example");
c.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); c.setSubjectType(SubjectType.PAIRWISE);
c.setSectorIdentifierUri("https://other.example.net/file_of_redirect_uris.json"); c.setSectorIdentifierUri("https://other.example.net/file_of_redirect_uris.json");
c.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.SECRET_BASIC); c.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC);
c.setJwksUri("https://client.example.org/my_public_keys.jwks"); c.setJwksUri("https://client.example.org/my_public_keys.jwks");
c.setUserInfoEncryptedResponseAlg(JWEAlgorithm.RSA1_5); c.setUserInfoEncryptedResponseAlg(JWEAlgorithm.RSA1_5);
c.setUserInfoEncryptedResponseEnc(EncryptionMethod.A128CBC_HS256); c.setUserInfoEncryptedResponseEnc(EncryptionMethod.A128CBC_HS256);
@ -156,12 +159,12 @@ public class RegisteredClientTest {
assertEquals("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk", rc.getClientSecret()); assertEquals("ZJYCqe3GGRvdrudKyZS0XhGv_Z45DuKhCUk0gBR1vZk", rc.getClientSecret());
assertEquals("this.is.an.access.token.value.ffx83", rc.getRegistrationAccessToken()); assertEquals("this.is.an.access.token.value.ffx83", rc.getRegistrationAccessToken());
assertEquals("https://server.example.com/connect/register?client_id=s6BhdRkqt3", rc.getRegistrationClientUri()); assertEquals("https://server.example.com/connect/register?client_id=s6BhdRkqt3", rc.getRegistrationClientUri());
assertEquals(ClientDetailsEntity.AppType.WEB, rc.getApplicationType()); assertEquals(AppType.WEB, rc.getApplicationType());
assertEquals(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"), rc.getRedirectUris()); assertEquals(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"), rc.getRedirectUris());
assertEquals("My Example", rc.getClientName()); assertEquals("My Example", rc.getClientName());
assertEquals(ClientDetailsEntity.SubjectType.PAIRWISE, rc.getSubjectType()); assertEquals(SubjectType.PAIRWISE, rc.getSubjectType());
assertEquals("https://other.example.net/file_of_redirect_uris.json", rc.getSectorIdentifierUri()); assertEquals("https://other.example.net/file_of_redirect_uris.json", rc.getSectorIdentifierUri());
assertEquals(ClientDetailsEntity.AuthMethod.SECRET_BASIC, rc.getTokenEndpointAuthMethod()); assertEquals(AuthMethod.SECRET_BASIC, rc.getTokenEndpointAuthMethod());
assertEquals("https://client.example.org/my_public_keys.jwks", rc.getJwksUri()); assertEquals("https://client.example.org/my_public_keys.jwks", rc.getJwksUri());
assertEquals(JWEAlgorithm.RSA1_5, rc.getUserInfoEncryptedResponseAlg()); assertEquals(JWEAlgorithm.RSA1_5, rc.getUserInfoEncryptedResponseAlg());
assertEquals(EncryptionMethod.A128CBC_HS256, rc.getUserInfoEncryptedResponseEnc()); assertEquals(EncryptionMethod.A128CBC_HS256, rc.getUserInfoEncryptedResponseEnc());

View File

@ -24,6 +24,7 @@ import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.enums.AppType;
import cz.muni.ics.openid.connect.config.ConfigurationPropertiesBean; import cz.muni.ics.openid.connect.config.ConfigurationPropertiesBean;
import cz.muni.ics.openid.connect.service.BlacklistedSiteService; import cz.muni.ics.openid.connect.service.BlacklistedSiteService;
import org.junit.Before; import org.junit.Before;
@ -104,12 +105,12 @@ public class TestBlacklistAwareRedirectResolver {
public void testRedirectMatches_default() { public void testRedirectMatches_default() {
// this is not an exact match // this is not an exact match
boolean res1 = resolver.redirectMatches(pathUri, goodUri, ClientDetailsEntity.AppType.WEB); boolean res1 = resolver.redirectMatches(pathUri, goodUri, AppType.WEB);
assertThat(res1, is(false)); assertThat(res1, is(false));
// this is an exact match // this is an exact match
boolean res2 = resolver.redirectMatches(goodUri, goodUri, ClientDetailsEntity.AppType.WEB); boolean res2 = resolver.redirectMatches(goodUri, goodUri, AppType.WEB);
assertThat(res2, is(true)); assertThat(res2, is(true));
@ -122,12 +123,12 @@ public class TestBlacklistAwareRedirectResolver {
resolver.setStrictMatch(false); resolver.setStrictMatch(false);
// this is not an exact match (but that's OK) // this is not an exact match (but that's OK)
boolean res1 = resolver.redirectMatches(pathUri, goodUri, ClientDetailsEntity.AppType.WEB); boolean res1 = resolver.redirectMatches(pathUri, goodUri, AppType.WEB);
assertThat(res1, is(true)); assertThat(res1, is(true));
// this is an exact match // this is an exact match
boolean res2 = resolver.redirectMatches(goodUri, goodUri, ClientDetailsEntity.AppType.WEB); boolean res2 = resolver.redirectMatches(goodUri, goodUri, AppType.WEB);
assertThat(res2, is(true)); assertThat(res2, is(true));
@ -136,12 +137,12 @@ public class TestBlacklistAwareRedirectResolver {
@Test @Test
public void testHeartMode() { public void testHeartMode() {
// this is not an exact match // this is not an exact match
boolean res1 = resolver.redirectMatches(pathUri, goodUri, ClientDetailsEntity.AppType.WEB); boolean res1 = resolver.redirectMatches(pathUri, goodUri, AppType.WEB);
assertThat(res1, is(false)); assertThat(res1, is(false));
// this is an exact match // this is an exact match
boolean res2 = resolver.redirectMatches(goodUri, goodUri, ClientDetailsEntity.AppType.WEB); boolean res2 = resolver.redirectMatches(goodUri, goodUri, AppType.WEB);
assertThat(res2, is(true)); assertThat(res2, is(true));
} }

View File

@ -29,7 +29,6 @@ import cz.muni.ics.oauth2.model.OAuth2AccessTokenEntity;
import cz.muni.ics.oauth2.model.OAuth2RefreshTokenEntity; import cz.muni.ics.oauth2.model.OAuth2RefreshTokenEntity;
import cz.muni.ics.oauth2.service.IntrospectionResultAssembler; import cz.muni.ics.oauth2.service.IntrospectionResultAssembler;
import cz.muni.ics.openid.connect.model.UserInfo; import cz.muni.ics.openid.connect.model.UserInfo;
import cz.muni.ics.uma.model.Permission;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
@ -52,7 +51,7 @@ public class TestDefaultIntrospectionResultAssembler {
public void shouldAssembleExpectedResultForAccessToken() throws ParseException { public void shouldAssembleExpectedResultForAccessToken() throws ParseException {
// given // given
OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), null, "Bearer", OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), "Bearer",
oauth2AuthenticationWithUser(oauth2Request("clientId"), "name")); oauth2AuthenticationWithUser(oauth2Request("clientId"), "name"));
UserInfo userInfo = userInfo("sub"); UserInfo userInfo = userInfo("sub");
@ -77,50 +76,11 @@ public class TestDefaultIntrospectionResultAssembler {
assertThat(result, is(equalTo(expected))); assertThat(result, is(equalTo(expected)));
} }
@Test
public void shouldAssembleExpectedResultForAccessToken_withPermissions() throws ParseException {
// given
OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"),
permissions(permission(1L, "foo", "bar")),
"Bearer", oauth2AuthenticationWithUser(oauth2Request("clientId"), "name"));
UserInfo userInfo = userInfo("sub");
Set<String> authScopes = scopes("foo", "bar", "baz");
// when
Map<String, Object> result = assembler.assembleFrom(accessToken, userInfo, authScopes);
// then
Map<String, Object> expected = new ImmutableMap.Builder<String, Object>()
.put("sub", "sub")
.put("exp", 123L)
.put("expires_at", dateFormat.valueToString(new Date(123 * 1000L)))
.put("permissions", new ImmutableSet.Builder<>()
.add(new ImmutableMap.Builder<String, Object>()
.put("resource_set_id", "1") // note that the resource ID comes out as a string
.put("scopes", new ImmutableSet.Builder<>()
.add("bar")
.add("foo")
.build())
.build())
.build())
// note that scopes are not included if permissions are included
.put("active", Boolean.TRUE)
.put("user_id", "name")
.put("client_id", "clientId")
.put("token_type", "Bearer")
.build();
assertThat(result, is(equalTo(expected)));
}
@Test @Test
public void shouldAssembleExpectedResultForAccessTokenWithoutUserInfo() throws ParseException { public void shouldAssembleExpectedResultForAccessTokenWithoutUserInfo() throws ParseException {
// given // given
OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), null, "Bearer", OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), "Bearer",
oauth2AuthenticationWithUser(oauth2Request("clientId"), "name")); oauth2AuthenticationWithUser(oauth2Request("clientId"), "name"));
Set<String> authScopes = scopes("foo", "bar", "baz"); Set<String> authScopes = scopes("foo", "bar", "baz");
@ -147,7 +107,7 @@ public class TestDefaultIntrospectionResultAssembler {
public void shouldAssembleExpectedResultForAccessTokenWithoutExpiry() { public void shouldAssembleExpectedResultForAccessTokenWithoutExpiry() {
// given // given
OAuth2AccessTokenEntity accessToken = accessToken(null, scopes("foo", "bar"), null, "Bearer", OAuth2AccessTokenEntity accessToken = accessToken(null, scopes("foo", "bar"), "Bearer",
oauth2AuthenticationWithUser(oauth2Request("clientId"), "name")); oauth2AuthenticationWithUser(oauth2Request("clientId"), "name"));
UserInfo userInfo = userInfo("sub"); UserInfo userInfo = userInfo("sub");
@ -173,7 +133,7 @@ public class TestDefaultIntrospectionResultAssembler {
@Test @Test
public void shouldAssembleExpectedResultForAccessTokenWithoutUserAuthentication() throws ParseException { public void shouldAssembleExpectedResultForAccessTokenWithoutUserAuthentication() throws ParseException {
// given // given
OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), null, "Bearer", OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), "Bearer",
oauth2Authentication(oauth2Request("clientId"), null)); oauth2Authentication(oauth2Request("clientId"), null));
Set<String> authScopes = scopes("foo", "bar", "baz"); Set<String> authScopes = scopes("foo", "bar", "baz");
@ -305,11 +265,10 @@ public class TestDefaultIntrospectionResultAssembler {
return userInfo; return userInfo;
} }
private OAuth2AccessTokenEntity accessToken(Date exp, Set<String> scopes, Set<Permission> permissions, String tokenType, OAuth2Authentication authentication) { private OAuth2AccessTokenEntity accessToken(Date exp, Set<String> scopes, String tokenType, OAuth2Authentication authentication) {
OAuth2AccessTokenEntity accessToken = mock(OAuth2AccessTokenEntity.class, RETURNS_DEEP_STUBS); OAuth2AccessTokenEntity accessToken = mock(OAuth2AccessTokenEntity.class, RETURNS_DEEP_STUBS);
given(accessToken.getExpiration()).willReturn(exp); given(accessToken.getExpiration()).willReturn(exp);
given(accessToken.getScope()).willReturn(scopes); given(accessToken.getScope()).willReturn(scopes);
given(accessToken.getPermissions()).willReturn(permissions);
given(accessToken.getTokenType()).willReturn(tokenType); given(accessToken.getTokenType()).willReturn(tokenType);
given(accessToken.getAuthenticationHolder().getAuthentication()).willReturn(authentication); given(accessToken.getAuthenticationHolder().getAuthentication()).willReturn(authentication);
return accessToken; return accessToken;
@ -342,15 +301,4 @@ public class TestDefaultIntrospectionResultAssembler {
private Set<String> scopes(String... scopes) { private Set<String> scopes(String... scopes) {
return newHashSet(scopes); return newHashSet(scopes);
} }
private Set<Permission> permissions(Permission... permissions) {
return newHashSet(permissions);
}
private Permission permission(Long resourceSetId, String... scopes) {
Permission permission = mock(Permission.class, RETURNS_DEEP_STUBS);
given(permission.getResourceSet().getId()).willReturn(resourceSetId);
given(permission.getScopes()).willReturn(scopes(scopes));
return permission;
}
} }

View File

@ -27,6 +27,7 @@ import static org.junit.Assert.fail;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.SystemScope; import cz.muni.ics.oauth2.model.SystemScope;
import cz.muni.ics.oauth2.model.enums.AuthMethod;
import cz.muni.ics.oauth2.repository.OAuth2ClientRepository; import cz.muni.ics.oauth2.repository.OAuth2ClientRepository;
import cz.muni.ics.oauth2.repository.OAuth2TokenRepository; import cz.muni.ics.oauth2.repository.OAuth2TokenRepository;
import cz.muni.ics.oauth2.service.SystemScopeService; import cz.muni.ics.oauth2.service.SystemScopeService;
@ -35,8 +36,6 @@ import cz.muni.ics.openid.connect.model.WhitelistedSite;
import cz.muni.ics.openid.connect.service.ApprovedSiteService; import cz.muni.ics.openid.connect.service.ApprovedSiteService;
import cz.muni.ics.openid.connect.service.BlacklistedSiteService; import cz.muni.ics.openid.connect.service.BlacklistedSiteService;
import cz.muni.ics.openid.connect.service.WhitelistedSiteService; import cz.muni.ics.openid.connect.service.WhitelistedSiteService;
import cz.muni.ics.uma.model.ResourceSet;
import cz.muni.ics.uma.service.ResourceSetService;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
@ -78,9 +77,6 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
@Mock @Mock
private SystemScopeService scopeService; private SystemScopeService scopeService;
@Mock
private ResourceSetService resourceSetService;
@Mock @Mock
private ConfigurationPropertiesBean config; private ConfigurationPropertiesBean config;
@ -266,8 +262,6 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
WhitelistedSite site = Mockito.mock(WhitelistedSite.class); WhitelistedSite site = Mockito.mock(WhitelistedSite.class);
Mockito.when(whitelistedSiteService.getByClientId(clientId)).thenReturn(site); Mockito.when(whitelistedSiteService.getByClientId(clientId)).thenReturn(site);
Mockito.when(resourceSetService.getAllForClient(client)).thenReturn(new HashSet<ResourceSet>());
service.deleteClient(client); service.deleteClient(client);
Mockito.verify(tokenRepository).clearTokensForClient(client); Mockito.verify(tokenRepository).clearTokensForClient(client);
@ -362,7 +356,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
grantTypes.add("client_credentials"); grantTypes.add("client_credentials");
client.setGrantTypes(grantTypes); client.setGrantTypes(grantTypes);
client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY);
client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); client.setRedirectUris(Sets.newHashSet("https://foo.bar/"));
@ -383,7 +377,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
grantTypes.add("client_credentials"); grantTypes.add("client_credentials");
client.setGrantTypes(grantTypes); client.setGrantTypes(grantTypes);
client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.NONE); client.setTokenEndpointAuthMethod(AuthMethod.NONE);
client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); client.setRedirectUris(Sets.newHashSet("https://foo.bar/"));
@ -404,7 +398,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
grantTypes.add("implicit"); grantTypes.add("implicit");
client.setGrantTypes(grantTypes); client.setGrantTypes(grantTypes);
client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY);
client.setJwksUri("https://foo.bar/jwks"); client.setJwksUri("https://foo.bar/jwks");
@ -421,7 +415,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
grantTypes.add("authorization_code"); grantTypes.add("authorization_code");
client.setGrantTypes(grantTypes); client.setGrantTypes(grantTypes);
client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.SECRET_POST); client.setTokenEndpointAuthMethod(AuthMethod.SECRET_POST);
client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); client.setRedirectUris(Sets.newHashSet("https://foo.bar/"));
@ -440,7 +434,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
grantTypes.add("implicit"); grantTypes.add("implicit");
client.setGrantTypes(grantTypes); client.setGrantTypes(grantTypes);
client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY);
client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); client.setRedirectUris(Sets.newHashSet("https://foo.bar/"));
@ -459,7 +453,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
grantTypes.add("client_credentials"); grantTypes.add("client_credentials");
client.setGrantTypes(grantTypes); client.setGrantTypes(grantTypes);
client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.SECRET_BASIC); client.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC);
client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); client.setRedirectUris(Sets.newHashSet("https://foo.bar/"));
@ -478,7 +472,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
grantTypes.add("authorization_code"); grantTypes.add("authorization_code");
client.setGrantTypes(grantTypes); client.setGrantTypes(grantTypes);
client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY);
service.saveNewClient(client); service.saveNewClient(client);
@ -493,7 +487,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
grantTypes.add("implicit"); grantTypes.add("implicit");
client.setGrantTypes(grantTypes); client.setGrantTypes(grantTypes);
client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.NONE); client.setTokenEndpointAuthMethod(AuthMethod.NONE);
service.saveNewClient(client); service.saveNewClient(client);
@ -508,7 +502,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
grantTypes.add("client_credentials"); grantTypes.add("client_credentials");
client.setGrantTypes(grantTypes); client.setGrantTypes(grantTypes);
client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY);
client.setRedirectUris(Sets.newHashSet("http://foo.bar/")); client.setRedirectUris(Sets.newHashSet("http://foo.bar/"));
@ -525,7 +519,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
grantTypes.add("authorization_code"); grantTypes.add("authorization_code");
client.setGrantTypes(grantTypes); client.setGrantTypes(grantTypes);
client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY);
client.setRedirectUris(Sets.newHashSet("http://foo.bar/")); client.setRedirectUris(Sets.newHashSet("http://foo.bar/"));
@ -544,7 +538,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
grantTypes.add("authorization_code"); grantTypes.add("authorization_code");
client.setGrantTypes(grantTypes); client.setGrantTypes(grantTypes);
client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY);
client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); client.setRedirectUris(Sets.newHashSet("https://foo.bar/"));
@ -565,7 +559,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
grantTypes.add("refresh_token"); grantTypes.add("refresh_token");
client.setGrantTypes(grantTypes); client.setGrantTypes(grantTypes);
client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY);
client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); client.setRedirectUris(Sets.newHashSet("https://foo.bar/"));
@ -587,7 +581,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
grantTypes.add("refresh_token"); grantTypes.add("refresh_token");
client.setGrantTypes(grantTypes); client.setGrantTypes(grantTypes);
client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY);
client.setRedirectUris(Sets.newHashSet("http://foo.bar/")); client.setRedirectUris(Sets.newHashSet("http://foo.bar/"));
@ -607,7 +601,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
grantTypes.add("refresh_token"); grantTypes.add("refresh_token");
client.setGrantTypes(grantTypes); client.setGrantTypes(grantTypes);
client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY);
client.setRedirectUris(Sets.newHashSet("http://localhost/", "https://foo.bar", "foo://bar")); client.setRedirectUris(Sets.newHashSet("http://localhost/", "https://foo.bar", "foo://bar"));

View File

@ -30,6 +30,9 @@ import com.nimbusds.jose.EncryptionMethod;
import com.nimbusds.jose.JWEAlgorithm; import com.nimbusds.jose.JWEAlgorithm;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.RegisteredClient; import cz.muni.ics.oauth2.model.RegisteredClient;
import cz.muni.ics.oauth2.model.enums.AppType;
import cz.muni.ics.oauth2.model.enums.AuthMethod;
import cz.muni.ics.oauth2.model.enums.SubjectType;
import java.sql.Date; import java.sql.Date;
import org.junit.Test; import org.junit.Test;
@ -68,14 +71,14 @@ public class ClientDetailsEntityJsonProcessorTest {
" }"; " }";
ClientDetailsEntity c = ClientDetailsEntityJsonProcessor.parse(json); ClientDetailsEntity c = ClientDetailsEntityJsonProcessor.parse(json);
assertEquals(ClientDetailsEntity.AppType.WEB, c.getApplicationType()); assertEquals(AppType.WEB, c.getApplicationType());
assertEquals(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"), c.getRedirectUris()); assertEquals(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"), c.getRedirectUris());
assertEquals("My Example", c.getClientName()); assertEquals("My Example", c.getClientName());
assertEquals(ImmutableSet.of("code", "token"), c.getResponseTypes()); assertEquals(ImmutableSet.of("code", "token"), c.getResponseTypes());
assertEquals(ImmutableSet.of("authorization_code", "implicit"), c.getGrantTypes()); assertEquals(ImmutableSet.of("authorization_code", "implicit"), c.getGrantTypes());
assertEquals(ClientDetailsEntity.SubjectType.PAIRWISE, c.getSubjectType()); assertEquals(SubjectType.PAIRWISE, c.getSubjectType());
assertEquals("https://other.example.net/file_of_redirect_uris.json", c.getSectorIdentifierUri()); assertEquals("https://other.example.net/file_of_redirect_uris.json", c.getSectorIdentifierUri());
assertEquals(ClientDetailsEntity.AuthMethod.SECRET_BASIC, c.getTokenEndpointAuthMethod()); assertEquals(AuthMethod.SECRET_BASIC, c.getTokenEndpointAuthMethod());
assertEquals("https://client.example.org/my_public_keys.jwks", c.getJwksUri()); assertEquals("https://client.example.org/my_public_keys.jwks", c.getJwksUri());
assertEquals(JWEAlgorithm.RSA1_5, c.getUserInfoEncryptedResponseAlg()); assertEquals(JWEAlgorithm.RSA1_5, c.getUserInfoEncryptedResponseAlg());
assertEquals(EncryptionMethod.A128CBC_HS256, c.getUserInfoEncryptedResponseEnc()); assertEquals(EncryptionMethod.A128CBC_HS256, c.getUserInfoEncryptedResponseEnc());
@ -129,14 +132,14 @@ public class ClientDetailsEntityJsonProcessorTest {
assertEquals(new Date(1577858400L * 1000L), c.getClientSecretExpiresAt()); assertEquals(new Date(1577858400L * 1000L), c.getClientSecretExpiresAt());
assertEquals("this.is.an.access.token.value.ffx83", c.getRegistrationAccessToken()); assertEquals("this.is.an.access.token.value.ffx83", c.getRegistrationAccessToken());
assertEquals("https://server.example.com/connect/register?client_id=s6BhdRkqt3", c.getRegistrationClientUri()); assertEquals("https://server.example.com/connect/register?client_id=s6BhdRkqt3", c.getRegistrationClientUri());
assertEquals(ClientDetailsEntity.AppType.WEB, c.getApplicationType()); assertEquals(AppType.WEB, c.getApplicationType());
assertEquals(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"), c.getRedirectUris()); assertEquals(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"), c.getRedirectUris());
assertEquals("My Example", c.getClientName()); assertEquals("My Example", c.getClientName());
assertEquals(ImmutableSet.of("code", "token"), c.getResponseTypes()); assertEquals(ImmutableSet.of("code", "token"), c.getResponseTypes());
assertEquals(ImmutableSet.of("authorization_code", "implicit"), c.getGrantTypes()); assertEquals(ImmutableSet.of("authorization_code", "implicit"), c.getGrantTypes());
assertEquals(ClientDetailsEntity.SubjectType.PAIRWISE, c.getSubjectType()); assertEquals(SubjectType.PAIRWISE, c.getSubjectType());
assertEquals("https://other.example.net/file_of_redirect_uris.json", c.getSectorIdentifierUri()); assertEquals("https://other.example.net/file_of_redirect_uris.json", c.getSectorIdentifierUri());
assertEquals(ClientDetailsEntity.AuthMethod.SECRET_BASIC, c.getTokenEndpointAuthMethod()); assertEquals(AuthMethod.SECRET_BASIC, c.getTokenEndpointAuthMethod());
assertEquals("https://client.example.org/my_public_keys.jwks", c.getJwksUri()); assertEquals("https://client.example.org/my_public_keys.jwks", c.getJwksUri());
assertEquals(JWEAlgorithm.RSA1_5, c.getUserInfoEncryptedResponseAlg()); assertEquals(JWEAlgorithm.RSA1_5, c.getUserInfoEncryptedResponseAlg());
assertEquals(EncryptionMethod.A128CBC_HS256, c.getUserInfoEncryptedResponseEnc()); assertEquals(EncryptionMethod.A128CBC_HS256, c.getUserInfoEncryptedResponseEnc());
@ -157,14 +160,14 @@ public class ClientDetailsEntityJsonProcessorTest {
c.setClientSecretExpiresAt(new Date(1577858400L * 1000L)); c.setClientSecretExpiresAt(new Date(1577858400L * 1000L));
c.setRegistrationAccessToken("this.is.an.access.token.value.ffx83"); c.setRegistrationAccessToken("this.is.an.access.token.value.ffx83");
c.setRegistrationClientUri("https://server.example.com/connect/register?client_id=s6BhdRkqt3"); c.setRegistrationClientUri("https://server.example.com/connect/register?client_id=s6BhdRkqt3");
c.setApplicationType(ClientDetailsEntity.AppType.WEB); c.setApplicationType(AppType.WEB);
c.setRedirectUris(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2")); c.setRedirectUris(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2"));
c.setClientName("My Example"); c.setClientName("My Example");
c.setResponseTypes(ImmutableSet.of("code", "token")); c.setResponseTypes(ImmutableSet.of("code", "token"));
c.setGrantTypes(ImmutableSet.of("authorization_code", "implicit")); c.setGrantTypes(ImmutableSet.of("authorization_code", "implicit"));
c.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); c.setSubjectType(SubjectType.PAIRWISE);
c.setSectorIdentifierUri("https://other.example.net/file_of_redirect_uris.json"); c.setSectorIdentifierUri("https://other.example.net/file_of_redirect_uris.json");
c.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.SECRET_BASIC); c.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC);
c.setJwksUri("https://client.example.org/my_public_keys.jwks"); c.setJwksUri("https://client.example.org/my_public_keys.jwks");
c.setUserInfoEncryptedResponseAlg(JWEAlgorithm.RSA1_5); c.setUserInfoEncryptedResponseAlg(JWEAlgorithm.RSA1_5);
c.setUserInfoEncryptedResponseEnc(EncryptionMethod.A128CBC_HS256); c.setUserInfoEncryptedResponseEnc(EncryptionMethod.A128CBC_HS256);
@ -178,7 +181,7 @@ public class ClientDetailsEntityJsonProcessorTest {
assertEquals(1577858400L, j.get("client_secret_expires_at").getAsNumber()); assertEquals(1577858400L, j.get("client_secret_expires_at").getAsNumber());
assertEquals("this.is.an.access.token.value.ffx83", j.get("registration_access_token").getAsString()); assertEquals("this.is.an.access.token.value.ffx83", j.get("registration_access_token").getAsString());
assertEquals("https://server.example.com/connect/register?client_id=s6BhdRkqt3", j.get("registration_client_uri").getAsString()); assertEquals("https://server.example.com/connect/register?client_id=s6BhdRkqt3", j.get("registration_client_uri").getAsString());
assertEquals(ClientDetailsEntity.AppType.WEB.getValue(), j.get("application_type").getAsString()); assertEquals(AppType.WEB.getValue(), j.get("application_type").getAsString());
for (JsonElement e : j.get("redirect_uris").getAsJsonArray()) { for (JsonElement e : j.get("redirect_uris").getAsJsonArray()) {
assertTrue(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2").contains(e.getAsString())); assertTrue(ImmutableSet.of("https://client.example.org/callback", "https://client.example.org/callback2").contains(e.getAsString()));
} }
@ -189,9 +192,9 @@ public class ClientDetailsEntityJsonProcessorTest {
for (JsonElement e : j.get("grant_types").getAsJsonArray()) { for (JsonElement e : j.get("grant_types").getAsJsonArray()) {
assertTrue(ImmutableSet.of("authorization_code", "implicit").contains(e.getAsString())); assertTrue(ImmutableSet.of("authorization_code", "implicit").contains(e.getAsString()));
} }
assertEquals(ClientDetailsEntity.SubjectType.PAIRWISE.getValue(), j.get("subject_type").getAsString()); assertEquals(SubjectType.PAIRWISE.getValue(), j.get("subject_type").getAsString());
assertEquals("https://other.example.net/file_of_redirect_uris.json", j.get("sector_identifier_uri").getAsString()); assertEquals("https://other.example.net/file_of_redirect_uris.json", j.get("sector_identifier_uri").getAsString());
assertEquals(ClientDetailsEntity.AuthMethod.SECRET_BASIC.getValue(), j.get("token_endpoint_auth_method").getAsString()); assertEquals(AuthMethod.SECRET_BASIC.getValue(), j.get("token_endpoint_auth_method").getAsString());
assertEquals("https://client.example.org/my_public_keys.jwks", j.get("jwks_uri").getAsString()); assertEquals("https://client.example.org/my_public_keys.jwks", j.get("jwks_uri").getAsString());
assertEquals(JWEAlgorithm.RSA1_5.getName(), j.get("userinfo_encrypted_response_alg").getAsString()); assertEquals(JWEAlgorithm.RSA1_5.getName(), j.get("userinfo_encrypted_response_alg").getAsString());
assertEquals(EncryptionMethod.A128CBC_HS256.getName(), j.get("userinfo_encrypted_response_enc").getAsString()); assertEquals(EncryptionMethod.A128CBC_HS256.getName(), j.get("userinfo_encrypted_response_enc").getAsString());

View File

@ -23,7 +23,7 @@ import com.nimbusds.jwt.SignedJWT;
import cz.muni.ics.jwt.signer.service.JWTSigningAndValidationService; import cz.muni.ics.jwt.signer.service.JWTSigningAndValidationService;
import cz.muni.ics.jwt.signer.service.impl.ClientKeyCacheService; import cz.muni.ics.jwt.signer.service.impl.ClientKeyCacheService;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.ClientDetailsEntity.AuthMethod; import cz.muni.ics.oauth2.model.enums.AuthMethod;
import cz.muni.ics.oauth2.service.ClientDetailsEntityService; import cz.muni.ics.oauth2.service.ClientDetailsEntityService;
import cz.muni.ics.openid.connect.config.ConfigurationPropertiesBean; import cz.muni.ics.openid.connect.config.ConfigurationPropertiesBean;
import java.util.Arrays; import java.util.Arrays;

View File

@ -24,6 +24,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.enums.SubjectType;
import cz.muni.ics.oauth2.service.ClientDetailsEntityService; import cz.muni.ics.oauth2.service.ClientDetailsEntityService;
import cz.muni.ics.openid.connect.model.DefaultUserInfo; import cz.muni.ics.openid.connect.model.DefaultUserInfo;
import cz.muni.ics.openid.connect.model.UserInfo; import cz.muni.ics.openid.connect.model.UserInfo;
@ -112,29 +113,29 @@ public class TestDefaultUserInfoService {
publicClient2 = new ClientDetailsEntity(); publicClient2 = new ClientDetailsEntity();
publicClient2.setClientId(publicClientId2); publicClient2.setClientId(publicClientId2);
publicClient2.setSubjectType(ClientDetailsEntity.SubjectType.PUBLIC); publicClient2.setSubjectType(SubjectType.PUBLIC);
// pairwise set 1 // pairwise set 1
pairwiseClient1 = new ClientDetailsEntity(); pairwiseClient1 = new ClientDetailsEntity();
pairwiseClient1.setClientId(pairwiseClientId1); pairwiseClient1.setClientId(pairwiseClientId1);
pairwiseClient1.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); pairwiseClient1.setSubjectType(SubjectType.PAIRWISE);
pairwiseClient1.setSectorIdentifierUri(sectorIdentifier1); pairwiseClient1.setSectorIdentifierUri(sectorIdentifier1);
pairwiseClient2 = new ClientDetailsEntity(); pairwiseClient2 = new ClientDetailsEntity();
pairwiseClient2.setClientId(pairwiseClientId2); pairwiseClient2.setClientId(pairwiseClientId2);
pairwiseClient2.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); pairwiseClient2.setSubjectType(SubjectType.PAIRWISE);
pairwiseClient2.setSectorIdentifierUri(sectorIdentifier2); pairwiseClient2.setSectorIdentifierUri(sectorIdentifier2);
// pairwise set 2 // pairwise set 2
pairwiseClient3 = new ClientDetailsEntity(); pairwiseClient3 = new ClientDetailsEntity();
pairwiseClient3.setClientId(pairwiseClientId3); pairwiseClient3.setClientId(pairwiseClientId3);
pairwiseClient3.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); pairwiseClient3.setSubjectType(SubjectType.PAIRWISE);
pairwiseClient3.setSectorIdentifierUri(sectorIdentifier3); pairwiseClient3.setSectorIdentifierUri(sectorIdentifier3);
// pairwise with null sector // pairwise with null sector
pairwiseClient4 = new ClientDetailsEntity(); pairwiseClient4 = new ClientDetailsEntity();
pairwiseClient4.setClientId(pairwiseClientId4); pairwiseClient4.setClientId(pairwiseClientId4);
pairwiseClient4.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); pairwiseClient4.setSubjectType(SubjectType.PAIRWISE);

View File

@ -25,6 +25,7 @@ import static org.junit.Assert.assertNotSame;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import cz.muni.ics.oauth2.model.ClientDetailsEntity; import cz.muni.ics.oauth2.model.ClientDetailsEntity;
import cz.muni.ics.oauth2.model.enums.SubjectType;
import cz.muni.ics.openid.connect.model.DefaultUserInfo; import cz.muni.ics.openid.connect.model.DefaultUserInfo;
import cz.muni.ics.openid.connect.model.PairwiseIdentifier; import cz.muni.ics.openid.connect.model.PairwiseIdentifier;
import cz.muni.ics.openid.connect.model.UserInfo; import cz.muni.ics.openid.connect.model.UserInfo;
@ -95,31 +96,31 @@ public class TestUUIDPairwiseIdentiferService {
// pairwise set 1 // pairwise set 1
pairwiseClient1 = new ClientDetailsEntity(); pairwiseClient1 = new ClientDetailsEntity();
pairwiseClient1.setClientId(pairwiseClientId1); pairwiseClient1.setClientId(pairwiseClientId1);
pairwiseClient1.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); pairwiseClient1.setSubjectType(SubjectType.PAIRWISE);
pairwiseClient1.setSectorIdentifierUri(sectorIdentifier1); pairwiseClient1.setSectorIdentifierUri(sectorIdentifier1);
pairwiseClient2 = new ClientDetailsEntity(); pairwiseClient2 = new ClientDetailsEntity();
pairwiseClient2.setClientId(pairwiseClientId2); pairwiseClient2.setClientId(pairwiseClientId2);
pairwiseClient2.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); pairwiseClient2.setSubjectType(SubjectType.PAIRWISE);
pairwiseClient2.setSectorIdentifierUri(sectorIdentifier2); pairwiseClient2.setSectorIdentifierUri(sectorIdentifier2);
// pairwise set 2 // pairwise set 2
pairwiseClient3 = new ClientDetailsEntity(); pairwiseClient3 = new ClientDetailsEntity();
pairwiseClient3.setClientId(pairwiseClientId3); pairwiseClient3.setClientId(pairwiseClientId3);
pairwiseClient3.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); pairwiseClient3.setSubjectType(SubjectType.PAIRWISE);
pairwiseClient3.setSectorIdentifierUri(sectorIdentifier3); pairwiseClient3.setSectorIdentifierUri(sectorIdentifier3);
pairwiseClient3.setRedirectUris(pairwiseClient3RedirectUris); pairwiseClient3.setRedirectUris(pairwiseClient3RedirectUris);
// pairwise with null sector // pairwise with null sector
pairwiseClient4 = new ClientDetailsEntity(); pairwiseClient4 = new ClientDetailsEntity();
pairwiseClient4.setClientId(pairwiseClientId4); pairwiseClient4.setClientId(pairwiseClientId4);
pairwiseClient4.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); pairwiseClient4.setSubjectType(SubjectType.PAIRWISE);
pairwiseClient4.setRedirectUris(pairwiseClient4RedirectUris); pairwiseClient4.setRedirectUris(pairwiseClient4RedirectUris);
// pairwise with multiple redirects and no sector (error) // pairwise with multiple redirects and no sector (error)
pairwiseClient5 = new ClientDetailsEntity(); pairwiseClient5 = new ClientDetailsEntity();
pairwiseClient5.setClientId(pairwiseClientId5); pairwiseClient5.setClientId(pairwiseClientId5);
pairwiseClient5.setSubjectType(ClientDetailsEntity.SubjectType.PAIRWISE); pairwiseClient5.setSubjectType(SubjectType.PAIRWISE);
pairwiseClient5.setRedirectUris(pairwiseClient5RedirectUris); pairwiseClient5.setRedirectUris(pairwiseClient5RedirectUris);
// saved pairwise identifier from repository // saved pairwise identifier from repository