automated code format cleanup

pull/888/head
Justin Richer 2015-08-05 10:21:21 -04:00
parent edda0218e1
commit 489450b1c2
117 changed files with 1023 additions and 1020 deletions

View File

@ -68,11 +68,11 @@ public class IntrospectingTokenService implements ResourceServerTokenServices {
private IntrospectionConfigurationService introspectionConfigurationService;
private IntrospectionAuthorityGranter introspectionAuthorityGranter = new SimpleIntrospectionAuthorityGranter();
private int defaultExpireTime = 300000; // 5 minutes in milliseconds
private int defaultExpireTime = 300000; // 5 minutes in milliseconds
private boolean forceCacheExpireTime = false; // force removal of cached tokens based on default expire time
private boolean cacheNonExpiringTokens = false;
private boolean cacheTokens = true;
private HttpClient httpClient = HttpClientBuilder.create()
.useSystemProperties()
.build();
@ -83,15 +83,15 @@ public class IntrospectingTokenService implements ResourceServerTokenServices {
OAuth2AccessToken token;
OAuth2Authentication auth;
Date cacheExpire;
private TokenCacheObject(OAuth2AccessToken token, OAuth2Authentication auth) {
this.token = token;
this.auth = auth;
// we don't need to check the cacheTokens values, because this won't actually be added to the cache if cacheTokens is false
// if the token isn't null we use the token expire time
// if forceCacheExpireTime is also true, we also make sure that the token expire time is shorter than the default expire time
if ((this.token.getExpiration() != null) && (!forceCacheExpireTime || (forceCacheExpireTime && (this.token.getExpiration().getTime() - System.currentTimeMillis() <= defaultExpireTime)))) {
if ((this.token.getExpiration() != null) && (!forceCacheExpireTime || (forceCacheExpireTime && (this.token.getExpiration().getTime() - System.currentTimeMillis() <= defaultExpireTime)))) {
this.cacheExpire = this.token.getExpiration();
} else { // if the token doesn't have an expire time, or if the using forceCacheExpireTime the token expire time is longer than the default, then use the default expire time
Calendar cal = Calendar.getInstance();
@ -150,7 +150,7 @@ public class IntrospectingTokenService implements ResourceServerTokenServices {
public void setDefaultExpireTime(int defaultExpireTime) {
this.defaultExpireTime = defaultExpireTime;
}
/**
* check if forcing a cache expire time maximum value
* @return the forceCacheExpireTime setting
@ -198,10 +198,10 @@ public class IntrospectingTokenService implements ResourceServerTokenServices {
public void setCacheTokens(boolean cacheTokens) {
this.cacheTokens = cacheTokens;
}
/**
* Check to see if the introspection end point response for a token has been cached locally
* This call will return the token if it has been cached and is still valid according to
* This call will return the token if it has been cached and is still valid according to
* the cache expire time on the TokenCacheObject. If a cached value has been found but is
* expired, either by default expire times or the token's own expire time, then the token is
* removed from the cache and null is returned.
@ -211,7 +211,7 @@ public class IntrospectingTokenService implements ResourceServerTokenServices {
private TokenCacheObject checkCache(String key) {
if (cacheTokens && authCache.containsKey(key)) {
TokenCacheObject tco = authCache.get(key);
if (tco != null && tco.cacheExpire != null && tco.cacheExpire.after(new Date())) {
return tco;
} else {
@ -246,7 +246,7 @@ public class IntrospectingTokenService implements ResourceServerTokenServices {
/**
* Validate a token string against the introspection endpoint,
* then parse it and store it in the local cache if caching is enabled.
* then parse it and store it in the local cache if caching is enabled.
*
* @param accessToken Token to pass to the introspection endpoint
* @return TokenCacheObject containing authentication and token if the token was valid, otherwise null

View File

@ -45,7 +45,7 @@ import com.nimbusds.jwt.ReadOnlyJWTClaimsSet;
public class NamedAdminAuthoritiesMapper implements OIDCAuthoritiesMapper {
private static Logger logger = LoggerFactory.getLogger(NamedAdminAuthoritiesMapper.class);
private static final SimpleGrantedAuthority ROLE_ADMIN = new SimpleGrantedAuthority("ROLE_ADMIN");
private static final SimpleGrantedAuthority ROLE_USER = new SimpleGrantedAuthority("ROLE_USER");
@ -57,17 +57,17 @@ public class NamedAdminAuthoritiesMapper implements OIDCAuthoritiesMapper {
Set<GrantedAuthority> out = new HashSet<>();
try {
ReadOnlyJWTClaimsSet claims = idToken.getJWTClaimsSet();
SubjectIssuerGrantedAuthority authority = new SubjectIssuerGrantedAuthority(claims.getSubject(), claims.getIssuer());
out.add(authority);
if (admins.contains(authority)) {
out.add(ROLE_ADMIN);
}
// everybody's a user by default
out.add(ROLE_USER);
} catch (ParseException e) {
logger.error("Unable to parse ID Token inside of authorities mapper (huh?)");
}

View File

@ -333,8 +333,8 @@ public class OIDCAuthenticationFilter extends AbstractAuthenticationProcessingFi
protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
ClientHttpRequest httpRequest = super.createRequest(url, method);
httpRequest.getHeaders().add("Authorization",
String.format("Basic %s", Base64.encode(String.format("%s:%s",
UriUtils.encodePathSegment(clientConfig.getClientId(), "UTF-8"),
String.format("Basic %s", Base64.encode(String.format("%s:%s",
UriUtils.encodePathSegment(clientConfig.getClientId(), "UTF-8"),
UriUtils.encodePathSegment(clientConfig.getClientSecret(), "UTF-8")))));
return httpRequest;
@ -581,10 +581,10 @@ public class OIDCAuthenticationFilter extends AbstractAuthenticationProcessingFi
// construct an PendingOIDCAuthenticationToken and return a Authentication object w/the userId and the idToken
PendingOIDCAuthenticationToken token = new PendingOIDCAuthenticationToken(idClaims.getSubject(), idClaims.getIssuer(),
serverConfig,
PendingOIDCAuthenticationToken token = new PendingOIDCAuthenticationToken(idClaims.getSubject(), idClaims.getIssuer(),
serverConfig,
idToken, accessTokenValue, refreshTokenValue);
Authentication authentication = this.getAuthenticationManager().authenticate(token);
return authentication;

View File

@ -39,7 +39,7 @@ import com.nimbusds.jwt.JWT;
public class OIDCAuthenticationProvider implements AuthenticationProvider {
private static Logger logger = LoggerFactory.getLogger(OIDCAuthenticationProvider.class);
private UserInfoFetcher userInfoFetcher = new UserInfoFetcher();
private OIDCAuthoritiesMapper authoritiesMapper = new NamedAdminAuthoritiesMapper();
@ -60,7 +60,7 @@ public class OIDCAuthenticationProvider implements AuthenticationProvider {
if (authentication instanceof PendingOIDCAuthenticationToken) {
PendingOIDCAuthenticationToken token = (PendingOIDCAuthenticationToken) authentication;
// get the ID Token value out
JWT idToken = token.getIdToken();
@ -68,7 +68,7 @@ public class OIDCAuthenticationProvider implements AuthenticationProvider {
UserInfo userInfo = userInfoFetcher.loadUserInfo(token);
if (userInfo == null) {
// user info not found -- could be an error, could be fine
// user info not found -- could be an error, could be fine
} else {
// if we found userinfo, double check it
if (!Strings.isNullOrEmpty(userInfo.getSub()) && !userInfo.getSub().equals(token.getSub())) {

View File

@ -32,7 +32,7 @@ public interface OIDCAuthoritiesMapper {
/**
* @param idToken the ID Token (parsed as a JWT, cannot be @null)
* @param userInfo userInfo of the current user (could be @null)
* @param userInfo userInfo of the current user (could be @null)
* @return the set of authorities to map to this user
*/
Collection<? extends GrantedAuthority> mapAuthorities(JWT idToken, UserInfo userInfo);

View File

@ -46,7 +46,7 @@ public interface AuthRequestOptionsService {
* @return
*/
public Map<String, String> getOptions(ServerConfiguration server, RegisteredClient client, HttpServletRequest request);
/**
* The set of options needed at the token endpoint.
*

View File

@ -25,7 +25,7 @@ import org.mitre.oauth2.model.RegisteredClient;
import org.mitre.openid.connect.config.ServerConfiguration;
/**
* Builds a URL string to the IdP's authorization endpoint.
* Builds a URL string to the IdP's authorization endpoint.
*
* @author jricher
*
@ -38,7 +38,7 @@ public interface AuthRequestUrlBuilder {
* @param redirectUri
* @param nonce
* @param state
* @param loginHint
* @param loginHint
* @return
*/
public String buildAuthRequestUrl(ServerConfiguration serverConfig, RegisteredClient clientConfig, String redirectUri, String nonce, String state, Map<String, String> options, String loginHint);

View File

@ -78,7 +78,7 @@ public class EncryptedAuthRequestUrlBuilder implements AuthRequestUrlBuilder {
for (Entry<String, String> option : options.entrySet()) {
claims.setClaim(option.getKey(), option.getValue());
}
// if there's a login hint, send it
if (!Strings.isNullOrEmpty(loginHint)) {
claims.setClaim("login_hint", loginHint);

View File

@ -63,7 +63,7 @@ public class PlainAuthRequestUrlBuilder implements AuthRequestUrlBuilder {
for (Entry<String, String> option : options.entrySet()) {
uriBuilder.addParameter(option.getKey(), option.getValue());
}
// if there's a login hint, send it
if (!Strings.isNullOrEmpty(loginHint)) {
uriBuilder.addParameter("login_hint", loginHint);

View File

@ -72,7 +72,7 @@ public class SignedAuthRequestUrlBuilder implements AuthRequestUrlBuilder {
for (Entry<String, String> option : options.entrySet()) {
claims.setClaim(option.getKey(), option.getValue());
}
// if there's a login hint, send it
if (!Strings.isNullOrEmpty(loginHint)) {
claims.setClaim("login_hint", loginHint);

View File

@ -77,7 +77,7 @@ public class WebfingerIssuerService implements IssuerService {
* URL of the page to forward to if no identifier is given.
*/
private String loginPageUrl;
/**
* Strict enfocement of "https"
*/
@ -207,7 +207,7 @@ public class WebfingerIssuerService implements IssuerService {
// preserving http scheme is strictly for demo system use only.
String scheme = key.getScheme();
if (!Strings.isNullOrEmpty(scheme) &&scheme.equals("http")) {
if (forceHttps) {
throw new IllegalArgumentException("Scheme must start with htps");
@ -231,13 +231,13 @@ public class WebfingerIssuerService implements IssuerService {
builder.addParameter("rel", "http://openid.net/specs/connect/1.0/issuer");
try {
// do the fetch
logger.info("Loading: " + builder.toString());
String webfingerResponse = restTemplate.getForObject(builder.build(), String.class);
JsonElement json = parser.parse(webfingerResponse);
if (json != null && json.isJsonObject()) {
// find the issuer
JsonArray links = json.getAsJsonObject().get("links").getAsJsonArray();
@ -247,7 +247,7 @@ public class WebfingerIssuerService implements IssuerService {
if (linkObj.has("href")
&& linkObj.has("rel")
&& linkObj.get("rel").getAsString().equals("http://openid.net/specs/connect/1.0/issuer")) {
// we found the issuer, return it
return linkObj.get("href").getAsString();
}

View File

@ -50,16 +50,16 @@ import com.nimbusds.jose.jwk.JWKSet;
public class ClientKeyCacheService {
private static Logger logger = LoggerFactory.getLogger(ClientKeyCacheService.class);
@Autowired
private JWKSetCacheService jwksUriCache = new JWKSetCacheService();
@Autowired
private SymmetricKeyJWTValidatorCacheService symmetricCache = new SymmetricKeyJWTValidatorCacheService();
// cache of validators for by-value JWKs
private LoadingCache<JWKSet, JWTSigningAndValidationService> jwksValidators;
// cache of encryptors for by-value JWKs
private LoadingCache<JWKSet, JWTEncryptionAndDecryptionService> jwksEncrypters;
@ -74,7 +74,7 @@ public class ClientKeyCacheService {
.build(new JWKSetEncryptorBuilder());
}
public JWTSigningAndValidationService getValidator(ClientDetailsEntity client, JWSAlgorithm alg) {
try {
@ -87,7 +87,7 @@ public class ClientKeyCacheService {
|| alg.equals(JWSAlgorithm.PS256)
|| alg.equals(JWSAlgorithm.PS384)
|| alg.equals(JWSAlgorithm.PS512)) {
// asymmetric key
if (client.getJwks() != null) {
return jwksValidators.get(client.getJwks());
@ -96,28 +96,28 @@ public class ClientKeyCacheService {
} else {
return null;
}
} else if (alg.equals(JWSAlgorithm.HS256)
|| alg.equals(JWSAlgorithm.HS384)
|| alg.equals(JWSAlgorithm.HS512)) {
// symmetric key
return symmetricCache.getSymmetricValidtor(client);
} else {
return null;
}
} catch (UncheckedExecutionException | ExecutionException e) {
} catch (UncheckedExecutionException | ExecutionException e) {
logger.error("Problem loading client validator", e);
return null;
}
}
public JWTEncryptionAndDecryptionService getEncrypter(ClientDetailsEntity client) {
try {
if (client.getJwks() != null) {
return jwksEncrypters.get(client.getJwks());
@ -130,17 +130,17 @@ public class ClientKeyCacheService {
logger.error("Problem loading client encrypter", e);
return null;
}
}
private class JWKSetEncryptorBuilder extends CacheLoader<JWKSet, JWTEncryptionAndDecryptionService> {
@Override
public JWTEncryptionAndDecryptionService load(JWKSet key) throws Exception {
return new DefaultJWTEncryptionAndDecryptionService(new JWKSetKeyStore(key));
}
}
private class JWKSetVerifierBuilder extends CacheLoader<JWKSet, JWTSigningAndValidationService> {
@ -152,5 +152,5 @@ public class ClientKeyCacheService {
}
}

View File

@ -178,10 +178,10 @@ public class DefaultJWTSigningAndValidationService implements JWTSigningAndValid
ECDSASigner signer = new ECDSASigner(((ECKey) jwk).getD().decodeToBigInteger());
signers.put(id, signer);
}
ECDSAVerifier verifier = new ECDSAVerifier(((ECKey) jwk).getX().decodeToBigInteger(), ((ECKey) jwk).getY().decodeToBigInteger());
verifiers.put(id, verifier);
} else if (jwk instanceof OctetSequenceKey) {
// build HMAC signers & verifiers

View File

@ -65,25 +65,25 @@ public class AuthenticationHolderEntity {
private Long id;
private SavedUserAuthentication userAuth;
private Collection<? extends GrantedAuthority> authorities;
private Set<String> resourceIds;
private boolean approved;
private String redirectUri;
private Set<String> responseTypes;
private Map<String, Serializable> extensions;
private String clientId;
private Set<String> scope;
private Map<String, String> requestParameters;
public AuthenticationHolderEntity() {
}
@ -125,7 +125,7 @@ public class AuthenticationHolderEntity {
setResponseTypes(o2Request.getResponseTypes());
setScope(o2Request.getScope());
setApproved(o2Request.isApproved());
if (authentication.getUserAuthentication() != null) {
this.userAuth = new SavedUserAuthentication(authentication.getUserAuthentication());
} else {

View File

@ -47,7 +47,7 @@ public class AuthorizationCodeEntity {
public static final String QUERY_BY_VALUE = "AuthorizationCodeEntity.getByValue";
public static final String QUERY_EXPIRATION_BY_DATE = "AuthorizationCodeEntity.expirationByDate";
public static final String PARAM_DATE = "date";
private Long id;
@ -55,7 +55,7 @@ public class AuthorizationCodeEntity {
private String code;
private AuthenticationHolderEntity authenticationHolder;
private Date expiration;
/**

View File

@ -76,7 +76,7 @@ public class ClientDetailsEntity implements ClientDetails {
public static final String QUERY_ALL = "ClientDetailsEntity.findAll";
public static final String PARAM_CLIENT_ID = "clientId";
private static final int DEFAULT_ID_TOKEN_VALIDITY_SECONDS = 600;
private static final long serialVersionUID = -1617727085733786296L;
@ -141,7 +141,7 @@ public class ClientDetailsEntity implements ClientDetails {
private Integer idTokenValiditySeconds; //timeout for id tokens
private Date createdAt; // time the client was created
private boolean clearAccessTokensOnRefresh = true; // do we clear access tokens on refresh?
/** fields for UMA */
private Set<String> claimsRedirectUris;

View File

@ -92,7 +92,7 @@ public class OAuth2AccessTokenEntity implements OAuth2AccessToken {
public static final String PARAM_REFERSH_TOKEN = "refreshToken";
public static final String PARAM_DATE = "date";
public static final String PARAM_RESOURCE_SET_ID = "rsid";
public static String ID_TOKEN_FIELD_NAME = "id_token";
private Long id;
@ -112,7 +112,7 @@ public class OAuth2AccessTokenEntity implements OAuth2AccessToken {
private OAuth2RefreshTokenEntity refreshToken;
private Set<String> scope;
private Set<Permission> permissions;
/**

View File

@ -64,7 +64,7 @@ public class OAuth2RefreshTokenEntity implements OAuth2RefreshToken {
public static final String PARAM_TOKEN_VALUE = "tokenValue";
public static final String PARAM_CLIENT = "client";
public static final String PARAM_DATE = "date";
private Long id;
private AuthenticationHolderEntity authenticationHolder;

View File

@ -591,7 +591,7 @@ public class RegisteredClient {
public void setRequestUris(Set<String> requestUris) {
client.setRequestUris(requestUris);
}
/**
* @return
* @see org.mitre.oauth2.model.ClientDetailsEntity#getRequestObjectSigningAlg()

View File

@ -49,17 +49,17 @@ import org.springframework.security.core.GrantedAuthority;
public class SavedUserAuthentication implements Authentication {
private static final long serialVersionUID = -1804249963940323488L;
private Long id;
private String name;
private Collection<? extends GrantedAuthority> authorities;
private boolean authenticated;
private String sourceClass;
/**
* Create a Saved Auth from an existing Auth token
*/
@ -80,7 +80,7 @@ public class SavedUserAuthentication implements Authentication {
* Create an empty saved auth
*/
public SavedUserAuthentication() {
}
/**
@ -104,7 +104,7 @@ public class SavedUserAuthentication implements Authentication {
@Basic
@Column(name="name")
public String getName() {
return name;
return name;
}
@Override
@ -116,7 +116,7 @@ public class SavedUserAuthentication implements Authentication {
@Convert(converter = SimpleGrantedAuthorityStringConverter.class)
@Column(name="authority")
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
return authorities;
}
@Override
@ -183,5 +183,5 @@ public class SavedUserAuthentication implements Authentication {
}
}
}

View File

@ -44,9 +44,9 @@ public class SystemScope {
public static final String QUERY_BY_VALUE = "SystemScope.getByValue";
public static final String QUERY_ALL = "SystemScope.findAll";
public static final String PARAM_VALUE = "value";
private Long id;
private String value; // scope value
private String description; // human-readable description

View File

@ -61,7 +61,7 @@ public class JWKSetStringConverter implements AttributeConverter<JWKSet, String>
} else {
return null;
}
}
}

View File

@ -36,7 +36,7 @@ import com.nimbusds.jwt.JWTParser;
public class JWTStringConverter implements AttributeConverter<JWT, String> {
public static Logger logger = LoggerFactory.getLogger(JWTStringConverter.class);
@Override
public String convertToDatabaseColumn(JWT attribute) {
if (attribute != null) {

View File

@ -32,7 +32,7 @@ import com.google.gson.JsonParser;
public class JsonElementStringConverter implements AttributeConverter<JsonElement, String> {
private JsonParser parser = new JsonParser();
@Override
public String convertToDatabaseColumn(JsonElement attribute) {
if (attribute != null) {

View File

@ -27,7 +27,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Translates a Serializable object of certain primitive types
* Translates a Serializable object of certain primitive types
* into a String for storage in the database, for use with the
* OAuth2Request extensions map.
*
@ -40,7 +40,7 @@ import org.slf4j.LoggerFactory;
public class SerializableStringConverter implements AttributeConverter<Serializable, String> {
private static Logger logger = LoggerFactory.getLogger(SerializableStringConverter.class);
@Override
public String convertToDatabaseColumn(Serializable attribute) {
if (attribute == null) {

View File

@ -35,7 +35,7 @@ public class SimpleGrantedAuthorityStringConverter implements AttributeConverter
return attribute.getAuthority();
} else {
return null;
}
}
}
@Override

View File

@ -55,5 +55,5 @@ public interface AuthorizationCodeRepository {
* @return A collection of all expired codes.
*/
public Collection<AuthorizationCodeEntity> getExpiredCodes();
}

View File

@ -53,7 +53,7 @@ public interface SystemScopeService {
* @return
*/
public Set<SystemScope> getDefaults();
/**
* Get all the reserved system scopes. These can't be used
* by clients directly, but are instead tied to special system
@ -62,7 +62,7 @@ public interface SystemScopeService {
* @return
*/
public Set<SystemScope> getReserved();
/**
* Get all the registered scopes that are restricted.
* @return
@ -74,7 +74,7 @@ public interface SystemScopeService {
* @return
*/
public Set<SystemScope> getUnrestricted();
public SystemScope getById(Long id);
public SystemScope getByValue(String value);
@ -108,13 +108,13 @@ public interface SystemScopeService {
public boolean scopesMatch(Set<String> expected, Set<String> actual);
/**
* Remove any system-reserved or registered restricted scopes from the
* Remove any system-reserved or registered restricted scopes from the
* set and return the result.
* @param scopes
* @return
*/
public Set<SystemScope> removeRestrictedAndReservedScopes(Set<SystemScope> scopes);
/**
* Remove any system-reserved scopes from the set and return the result.
* @param scopes

View File

@ -55,28 +55,28 @@ public class DefaultClientUserDetailsService implements UserDetailsService {
try {
ClientDetailsEntity client = clientDetailsService.loadClientByClientId(clientId);
if (client != null) {
String password = Strings.nullToEmpty(client.getClientSecret());
if (client.getTokenEndpointAuthMethod() != null &&
(client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY) ||
client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT))) {
// Issue a random password each time to prevent password auth from being used (or skipped)
// for private key or shared key clients, see #715
password = new BigInteger(512, new SecureRandom()).toString(16);
}
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
Collection<GrantedAuthority> authorities = new HashSet<>(client.getAuthorities());
authorities.add(ROLE_CLIENT);
return new User(clientId, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
} else {
throw new UsernameNotFoundException("Client not found: " + clientId);

View File

@ -42,7 +42,7 @@ import com.google.common.base.Strings;
* Loads client details based on URI encoding as passed in from basic auth.
*
* Should only get called if non-encoded provider fails.
*
*
* @author AANGANES
*
*/
@ -59,30 +59,30 @@ public class UriEncodedClientUserDetailsService implements UserDetailsService {
try {
String decodedClientId = UriUtils.decode(clientId, "UTF-8");
ClientDetailsEntity client = clientDetailsService.loadClientByClientId(decodedClientId);
if (client != null) {
String encodedPassword = UriUtils.encodeQueryParam(Strings.nullToEmpty(client.getClientSecret()), "UTF-8");
if (client.getTokenEndpointAuthMethod() != null &&
(client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY) ||
client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT))) {
// Issue a random password each time to prevent password auth from being used (or skipped)
// for private key or shared key clients, see #715
encodedPassword = new BigInteger(512, new SecureRandom()).toString(16);
}
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
Collection<GrantedAuthority> authorities = new HashSet<>(client.getAuthorities());
authorities.add(ROLE_CLIENT);
return new User(decodedClientId, encodedPassword, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
} else {
throw new UsernameNotFoundException("Client not found: " + clientId);

View File

@ -92,7 +92,7 @@ import static org.mitre.util.JsonUtils.getAsStringSet;
public class ClientDetailsEntityJsonProcessor {
private static Logger logger = LoggerFactory.getLogger(ClientDetailsEntityJsonProcessor.class);
private static JsonParser parser = new JsonParser();
/**
@ -140,7 +140,7 @@ public class ClientDetailsEntityJsonProcessor {
c.setResponseTypes(getAsStringSet(o, RESPONSE_TYPES));
c.setPolicyUri(getAsString(o, POLICY_URI));
c.setJwksUri(getAsString(o, JWKS_URI));
JsonElement jwksEl = o.get(JWKS);
if (jwksEl != null && jwksEl.isJsonObject()) {
try {
@ -223,7 +223,7 @@ public class ClientDetailsEntityJsonProcessor {
rc.setClientSecretExpiresAt(getAsDate(o, CLIENT_SECRET_EXPIRES_AT));
rc.setSource(o);
return rc;
} else {
return null;
@ -237,25 +237,25 @@ public class ClientDetailsEntityJsonProcessor {
* @return
*/
public static JsonObject serialize(RegisteredClient c) {
if (c.getSource() != null) {
// if we have the original object, just use that
return c.getSource();
} else {
JsonObject o = new JsonObject();
o.addProperty(CLIENT_ID, c.getClientId());
if (c.getClientSecret() != null) {
o.addProperty(CLIENT_SECRET, c.getClientSecret());
if (c.getClientSecretExpiresAt() == null) {
o.addProperty(CLIENT_SECRET_EXPIRES_AT, 0); // TODO: do we want to let secrets expire?
} else {
o.addProperty(CLIENT_SECRET_EXPIRES_AT, c.getClientSecretExpiresAt().getTime() / 1000L);
}
}
if (c.getClientIdIssuedAt() != null) {
o.addProperty(CLIENT_ID_ISSUED_AT, c.getClientIdIssuedAt().getTime() / 1000L);
} else if (c.getCreatedAt() != null) {
@ -264,14 +264,14 @@ public class ClientDetailsEntityJsonProcessor {
if (c.getRegistrationAccessToken() != null) {
o.addProperty(REGISTRATION_ACCESS_TOKEN, c.getRegistrationAccessToken());
}
if (c.getRegistrationClientUri() != null) {
o.addProperty(REGISTRATION_CLIENT_URI, c.getRegistrationClientUri());
}
// add in all other client properties
// OAuth DynReg
o.add(REDIRECT_URIS, getAsArray(c.getRedirectUris()));
o.addProperty(CLIENT_NAME, c.getClientName());
@ -285,7 +285,7 @@ public class ClientDetailsEntityJsonProcessor {
o.add(RESPONSE_TYPES, getAsArray(c.getResponseTypes()));
o.addProperty(POLICY_URI, c.getPolicyUri());
o.addProperty(JWKS_URI, c.getJwksUri());
// get the JWKS sub-object
if (c.getJwks() != null) {
// We have to re-parse it into GSON because Nimbus uses a different parser
@ -294,7 +294,7 @@ public class ClientDetailsEntityJsonProcessor {
} else {
o.add(JWKS, null);
}
// OIDC Registration
o.addProperty(APPLICATION_TYPE, c.getApplicationType() != null ? c.getApplicationType().getValue() : null);
o.addProperty(SECTOR_IDENTIFIER_URI, c.getSectorIdentifierUri());

View File

@ -49,7 +49,7 @@ public class ConfigurationPropertiesBean {
private String logoImageUrl;
private Long regTokenLifeTime;
private Long rqpTokenLifeTime;
private boolean forceHttps = false; // by default we just log a warning for HTTPS deployment

View File

@ -55,7 +55,7 @@ public class ApprovedSite {
public static final String QUERY_BY_CLIENT_ID = "ApprovedSite.getByClientId";
public static final String QUERY_BY_USER_ID = "ApprovedSite.getByUserId";
public static final String QUERY_ALL = "ApprovedSite.getAll";
public static final String PARAM_CLIENT_ID = "clientId";
public static final String PARAM_USER_ID = "userId";

View File

@ -417,13 +417,13 @@ public class DefaultUserInfo implements UserInfo {
@Override
public JsonObject toJson() {
if (src == null) {
JsonObject obj = new JsonObject();
obj.addProperty("sub", this.getSub());
obj.addProperty("name", this.getName());
obj.addProperty("preferred_username", this.getPreferredUsername());
obj.addProperty("given_name", this.getGivenName());
@ -438,15 +438,15 @@ public class DefaultUserInfo implements UserInfo {
obj.addProperty("locale", this.getLocale());
obj.addProperty("updated_time", this.getUpdatedTime());
obj.addProperty("birthdate", this.getBirthdate());
obj.addProperty("email", this.getEmail());
obj.addProperty("email_verified", this.getEmailVerified());
obj.addProperty("phone_number", this.getPhoneNumber());
obj.addProperty("phone_number_verified", this.getPhoneNumberVerified());
if (this.getAddress() != null) {
JsonObject addr = new JsonObject();
addr.addProperty("formatted", this.getAddress().getFormatted());
addr.addProperty("street_address", this.getAddress().getStreetAddress());
@ -454,10 +454,10 @@ public class DefaultUserInfo implements UserInfo {
addr.addProperty("region", this.getAddress().getRegion());
addr.addProperty("postal_code", this.getAddress().getPostalCode());
addr.addProperty("country", this.getAddress().getCountry());
obj.add("address", addr);
}
return obj;
} else {
return src;
@ -531,8 +531,8 @@ public class DefaultUserInfo implements UserInfo {
public void setSource(JsonObject src) {
this.src = src;
}
private static String nullSafeGetString(JsonObject obj, String field) {
return obj.has(field) && obj.get(field).isJsonPrimitive() ? obj.get(field).getAsString() : null;
}
@ -732,26 +732,26 @@ public class DefaultUserInfo implements UserInfo {
}
return true;
}
/*
* Custom serialization to handle the JSON object
*/
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
if (src == null) {
out.writeObject(null);
} else {
out.writeObject(src.toString());
}
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
Object o = in.readObject();
if (o != null) {
JsonParser parser = new JsonParser();
src = parser.parse((String)o).getAsJsonObject();
}
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
if (src == null) {
out.writeObject(null);
} else {
out.writeObject(src.toString());
}
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
Object o = in.readObject();
if (o != null) {
JsonParser parser = new JsonParser();
src = parser.parse((String)o).getAsJsonObject();
}
}
}

View File

@ -136,20 +136,20 @@ public class OIDCAuthenticationToken extends AbstractAuthenticationToken {
/*
* Custom serialization to handle the JSON object
*/
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
if (idToken == null) {
out.writeObject(null);
} else {
out.writeObject(idToken.serialize());
}
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException, ParseException {
in.defaultReadObject();
Object o = in.readObject();
if (o != null) {
idToken = JWTParser.parse((String)o);
}
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
if (idToken == null) {
out.writeObject(null);
} else {
out.writeObject(idToken.serialize());
}
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException, ParseException {
in.defaultReadObject();
Object o = in.readObject();
if (o != null) {
idToken = JWTParser.parse((String)o);
}
}
}

View File

@ -49,7 +49,7 @@ public class PairwiseIdentifier {
public static final String PARAM_SECTOR_IDENTIFIER = "sectorIdentifier";
public static final String PARAM_SUB = "sub";
private Long id;
private String identifier;
private String userSub;

View File

@ -138,20 +138,20 @@ public class PendingOIDCAuthenticationToken extends AbstractAuthenticationToken
/*
* Custom serialization to handle the JSON object
*/
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
if (idToken == null) {
out.writeObject(null);
} else {
out.writeObject(idToken.serialize());
}
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException, ParseException {
in.defaultReadObject();
Object o = in.readObject();
if (o != null) {
idToken = JWTParser.parse((String)o);
}
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
if (idToken == null) {
out.writeObject(null);
} else {
out.writeObject(idToken.serialize());
}
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException, ParseException {
in.defaultReadObject();
Object o = in.readObject();
if (o != null) {
idToken = JWTParser.parse((String)o);
}
}
}

View File

@ -233,7 +233,7 @@ public interface UserInfo extends Serializable {
* @return
*/
public JsonObject toJson();
/**
* The JSON source of this UserInfo (if it was fetched), or null if it's local.
* @return

View File

@ -50,7 +50,7 @@ public class WhitelistedSite {
public static final String QUERY_BY_CREATOR = "WhitelistedSite.getByCreatoruserId";
public static final String QUERY_BY_CLIENT_ID = "WhitelistedSite.getByClientId";
public static final String QUERY_ALL = "WhitelistedSite.getAll";
public static final String PARAM_USER_ID = "userId";
public static final String PARAM_CLIENT_ID = "clientId";

View File

@ -32,7 +32,7 @@ import com.google.gson.JsonParser;
public class JsonObjectStringConverter implements AttributeConverter<JsonObject, String> {
private JsonParser parser = new JsonParser();
@Override
public String convertToDatabaseColumn(JsonObject attribute) {
if (attribute != null) {

View File

@ -45,7 +45,7 @@ public interface UserInfoService {
public UserInfo getByUsernameAndClientId(String username, String clientId);
/**
* Get the user registered at this server with the given email address.
* Get the user registered at this server with the given email address.
*
* @param email
* @return

View File

@ -52,7 +52,7 @@ public interface WhitelistedSiteService {
*/
public WhitelistedSite getByClientId(String clientId);
/**
* Removes the given WhitelistedSite from the repository

View File

@ -93,7 +93,7 @@ public class UserInfoInterceptor extends HandlerInterceptorAdapter {
}
}
}
return true;
}

View File

@ -51,7 +51,7 @@ public class Claim {
private JsonElement value;
private Set<String> claimTokenFormat;
private Set<String> issuer;
/**
* @return the id
*/
@ -81,7 +81,7 @@ public class Claim {
public void setName(String name) {
this.name = name;
}
/**
* @return the friendlyName
*/
@ -96,7 +96,7 @@ public class Claim {
public void setFriendlyName(String friendlyName) {
this.friendlyName = friendlyName;
}
/**
* @return the claimType
*/
@ -111,7 +111,7 @@ public class Claim {
public void setClaimType(String claimType) {
this.claimType = claimType;
}
/**
* @return the claimTokenFormat
*/

View File

@ -40,7 +40,7 @@ public class ClaimProcessingResult {
this.unmatched = unmatched;
this.matched = null;
}
/**
* Create a matched result. isSatisfied is true.
* @param matched
@ -92,5 +92,5 @@ public class ClaimProcessingResult {
public void setMatched(Policy matched) {
this.matched = matched;
}
}

View File

@ -67,14 +67,14 @@ public class Permission {
public ResourceSet getResourceSet() {
return resourceSet;
}
/**
* @param resourceSet the resourceSet to set
*/
public void setResourceSet(ResourceSet resourceSet) {
this.resourceSet = resourceSet;
}
/**
* @return the scopes
*/
@ -87,7 +87,7 @@ public class Permission {
public Set<String> getScopes() {
return scopes;
}
/**
* @param scopes the scopes to set
*/

View File

@ -57,16 +57,16 @@ 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;
/**
* @return the id
*/
@ -76,14 +76,14 @@ public class PermissionTicket {
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the permission
*/
@ -108,7 +108,7 @@ public class PermissionTicket {
public String getTicket() {
return ticket;
}
/**
* @param ticket the ticket to set
*/
@ -152,6 +152,6 @@ public class PermissionTicket {
public void setClaimsSupplied(Collection<Claim> claimsSupplied) {
this.claimsSupplied = claimsSupplied;
}
}

View File

@ -49,7 +49,7 @@ public class Policy {
private String name;
private Collection<Claim> claimsRequired;
private Set<String> scopes;
/**
* @return the id
*/
@ -59,14 +59,14 @@ public class Policy {
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the name
*/
@ -91,7 +91,7 @@ public class Policy {
name = "claim_to_policy",
joinColumns = @JoinColumn(name = "policy_id"),
inverseJoinColumns = @JoinColumn(name = "claim_id")
)
)
public Collection<Claim> getClaimsRequired() {
return claimsRequired;
}
@ -102,7 +102,7 @@ public class Policy {
public void setClaimsRequired(Collection<Claim> claimsRequired) {
this.claimsRequired = claimsRequired;
}
/**
* @return the scopes
*/
@ -115,7 +115,7 @@ public class Policy {
public Set<String> getScopes() {
return scopes;
}
/**
* @param scopes the scopes to set
*/
@ -190,5 +190,5 @@ public class Policy {
}
return true;
}
}

View File

@ -39,10 +39,10 @@ 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")
@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 {
@ -60,12 +60,12 @@ public class ResourceSet {
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<>();
/**
* @return the id
*/
@ -75,7 +75,7 @@ public class ResourceSet {
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
@ -91,14 +91,14 @@ public class ResourceSet {
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the uri
*/
@ -107,14 +107,14 @@ public class ResourceSet {
public String getUri() {
return uri;
}
/**
* @param uri the uri to set
*/
public void setUri(String uri) {
this.uri = uri;
}
/**
* @return the type
*/
@ -123,14 +123,14 @@ public class ResourceSet {
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the scopes
*/
@ -143,14 +143,14 @@ public class ResourceSet {
public Set<String> getScopes() {
return scopes;
}
/**
* @param scopes the scopes to set
*/
public void setScopes(Set<String> scopes) {
this.scopes = scopes;
}
/**
* @return the iconUri
*/
@ -159,14 +159,14 @@ public class ResourceSet {
public String getIconUri() {
return iconUri;
}
/**
* @param iconUri the iconUri to set
*/
public void setIconUri(String iconUri) {
this.iconUri = iconUri;
}
/**
* @return the owner
*/
@ -175,7 +175,7 @@ public class ResourceSet {
public String getOwner() {
return owner;
}
/**
* @param owner the owner to set
*/
@ -322,9 +322,9 @@ public class ResourceSet {
}
return true;
}
}

View File

@ -40,7 +40,7 @@ public class SavedRegisteredClient {
private Long id;
private String issuer;
private RegisteredClient registeredClient;
/**
* @return the id
*/
@ -93,5 +93,5 @@ public class SavedRegisteredClient {
}
}

View File

@ -42,7 +42,7 @@ public class RegisteredClientStringConverter implements AttributeConverter<Regis
} else {
return attribute.getSource().toString();
}
}
/* (non-Javadoc)

View File

@ -57,7 +57,7 @@ public interface PermissionRepository {
* Save a permission object with no associated ticket (used by the import/export API)
*
* @param p
* @return
* @return
*/
public Permission saveRawPermission(Permission p);

View File

@ -48,10 +48,10 @@ public interface PermissionService {
public PermissionTicket getByTicket(String ticket);
/**
* Save the updated permission ticket to the database. Does not create a new ticket.
* Save the updated permission ticket to the database. Does not create a new ticket.
*
* @param ticket
* @return
* @return
*/
public PermissionTicket updateTicket(PermissionTicket ticket);

View File

@ -31,7 +31,7 @@ import org.springframework.security.oauth2.provider.OAuth2Authentication;
public interface UmaTokenService {
/**
* Create the RPT from the given authentication and ticket.
* Create the RPT from the given authentication and ticket.
*
*/
public OAuth2AccessTokenEntity createRequestingPartyToken(OAuth2Authentication o2auth, PermissionTicket ticket, Policy policy);

View File

@ -152,7 +152,7 @@ public class JsonUtils {
return null;
}
}
/**
* Gets the value of the given member as a Long, null if it doesn't exist
*/
@ -163,7 +163,7 @@ public class JsonUtils {
return e.getAsLong();
} else {
return null;
}
}
} else {
return null;
}

View File

@ -116,12 +116,12 @@ public class DiscoveryEndpoint {
// check on email addresses first
UserInfo user = userService.getByEmailAddress(resourceUri.getUserInfo() + "@" + resourceUri.getHost());
if (user == null) {
// user wasn't found, see if the local part of the username matches, plus our issuer host
user = userService.getByUsername(resourceUri.getUserInfo()); // first part is the username
if (user != null) {
// username matched, check the host component
UriComponents issuerComponents = UriComponentsBuilder.fromHttpUrl(config.getIssuer()).build();
@ -131,16 +131,16 @@ public class DiscoveryEndpoint {
model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
return HttpCodeView.VIEWNAME;
}
} else {
// if the user's still null, punt and say we didn't find them
logger.info("User not found: " + resource);
model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
return HttpCodeView.VIEWNAME;
}
}
} else {

View File

@ -77,7 +77,7 @@ public class JpaAuthorizationCodeRepository implements AuthorizationCodeReposito
AuthorizationCodeEntity found = manager.find(AuthorizationCodeEntity.class, authorizationCodeEntity.getId());
if (found != null) {
manager.remove(found);
}
}
}
/* (non-Javadoc)
@ -89,7 +89,7 @@ public class JpaAuthorizationCodeRepository implements AuthorizationCodeReposito
query.setParameter(AuthorizationCodeEntity.PARAM_DATE, new Date()); // this gets anything that's already expired
return query.getResultList();
}
}

View File

@ -42,9 +42,9 @@ public class BlacklistAwareRedirectResolver extends DefaultRedirectResolver {
@Autowired
private BlacklistedSiteService blacklistService;
private boolean strictMatch = false;
/* (non-Javadoc)
* @see org.springframework.security.oauth2.provider.endpoint.RedirectResolver#resolveRedirect(java.lang.String, org.springframework.security.oauth2.provider.ClientDetails)
*/
@ -65,7 +65,7 @@ public class BlacklistAwareRedirectResolver extends DefaultRedirectResolver {
*/
@Override
protected boolean redirectMatches(String requestedRedirect, String redirectUri) {
if (isStrictMatch()) {
// we're doing a strict string match for all clients
return Strings.nullToEmpty(requestedRedirect).equals(redirectUri);
@ -73,7 +73,7 @@ public class BlacklistAwareRedirectResolver extends DefaultRedirectResolver {
// otherwise do the prefix-match from the library
return super.redirectMatches(requestedRedirect, redirectUri);
}
}
/**
@ -92,6 +92,6 @@ public class BlacklistAwareRedirectResolver extends DefaultRedirectResolver {
this.strictMatch = strictMatch;
}
}

View File

@ -57,7 +57,7 @@ public class DefaultIntrospectionResultAssembler implements IntrospectionResultA
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());
@ -65,14 +65,14 @@ public class DefaultIntrospectionResultAssembler implements IntrospectionResultA
o.put("scopes", scopes);
permissions.add(o);
}
result.put("permissions", permissions);
} else {
Set<String> scopes = Sets.intersection(authScopes, accessToken.getScope());
result.put(SCOPE, Joiner.on(SCOPE_SEPARATOR).join(scopes));
}
if (accessToken.getExpiration() != null) {
@ -110,7 +110,7 @@ public class DefaultIntrospectionResultAssembler implements IntrospectionResultA
result.put(ACTIVE, true);
Set<String> scopes = Sets.intersection(authScopes, authentication.getOAuth2Request().getScope());
result.put(SCOPE, Joiner.on(SCOPE_SEPARATOR).join(scopes));
if (refreshToken.getExpiration() != null) {

View File

@ -49,10 +49,10 @@ public class DefaultOAuth2AuthorizationCodeService implements AuthorizationCodeS
@Autowired
private AuthorizationCodeRepository repository;
@Autowired
private AuthenticationHolderRepository authenticationHolderRepository;
private int authCodeExpirationSeconds = 60 * 5; // expire in 5 minutes by default
private RandomValueStringGenerator generator = new RandomValueStringGenerator();
@ -75,8 +75,8 @@ public class DefaultOAuth2AuthorizationCodeService implements AuthorizationCodeS
authHolder = authenticationHolderRepository.save(authHolder);
// set the auth code to expire
Date expiration = new Date(System.currentTimeMillis() + (getAuthCodeExpirationSeconds() * 1000L));
Date expiration = new Date(System.currentTimeMillis() + (getAuthCodeExpirationSeconds() * 1000L));
AuthorizationCodeEntity entity = new AuthorizationCodeEntity(code, authHolder, expiration);
repository.save(entity);
@ -97,32 +97,32 @@ public class DefaultOAuth2AuthorizationCodeService implements AuthorizationCodeS
public OAuth2Authentication consumeAuthorizationCode(String code) throws InvalidGrantException {
AuthorizationCodeEntity result = repository.getByCode(code);
if (result == null) {
throw new InvalidGrantException("JpaAuthorizationCodeRepository: no authorization code found for value " + code);
}
OAuth2Authentication auth = result.getAuthenticationHolder().getAuthentication();
repository.remove(result);
return auth;
}
/**
* Find and remove all expired auth codes.
*/
@Transactional
public void clearExpiredAuthorizationCodes() {
Collection<AuthorizationCodeEntity> codes = repository.getExpiredCodes();
for (AuthorizationCodeEntity code : codes) {
repository.remove(code);
}
logger.info("Removed " + codes.size() + " expired authorization codes.");
}
/**

View File

@ -89,10 +89,10 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt
@Autowired
private StatsService statsService;
@Autowired
private ResourceSetService resourceSetService;
@Autowired
private ConfigurationPropertiesBean config;
@ -124,7 +124,7 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt
// make sure that clients with the "refresh_token" grant type have the "offline_access" scope, and vice versa
ensureRefreshTokenConsistency(client);
// make sure we don't have both a JWKS and a JWKS URI
ensureKeyConsistency(client);
@ -158,9 +158,9 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt
private void ensureNoReservedScopes(ClientDetailsEntity client) {
// make sure a client doesn't get any special system scopes
Set<SystemScope> requestedScope = scopeService.fromStrings(client.getScope());
requestedScope = scopeService.removeReservedScopes(requestedScope);
client.setScope(scopeService.toStrings(requestedScope));
}
@ -240,7 +240,7 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt
if (whitelistedSite != null) {
whitelistedSiteService.remove(whitelistedSite);
}
// clear out resource sets registered for this client
Collection<ResourceSet> resourceSets = resourceSetService.getAllForClient(client);
for (ResourceSet rs : resourceSets) {

View File

@ -151,8 +151,8 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
Set<SystemScope> scopes = scopeService.fromStrings(clientAuth.getScope());
// remove any of the special system scopes
scopes = scopeService.removeReservedScopes(scopes);
scopes = scopeService.removeReservedScopes(scopes);
token.setScope(scopeService.toStrings(scopes));
// make it expire if necessary
@ -280,7 +280,7 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
Set<String> scopeRequested = authRequest.getScope() == null ? new HashSet<String>() : new HashSet<>(authRequest.getScope());
Set<SystemScope> scope = scopeService.fromStrings(scopeRequested);
// remove any of the special system scopes
scope = scopeService.removeReservedScopes(scope);
@ -313,7 +313,7 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
// otherwise, make a new refresh token
OAuth2RefreshTokenEntity newRefresh = createRefreshToken(client, authHolder);
token.setRefreshToken(newRefresh);
// clean up the old refresh token
tokenRepository.removeRefreshToken(refreshToken);
}

View File

@ -62,7 +62,7 @@ public class DefaultSystemScopeService implements SystemScopeService {
return (input != null && input.isRestricted());
}
};
private Predicate<SystemScope> isReserved = new Predicate<SystemScope>() {
@Override
public boolean apply(SystemScope input) {

View File

@ -32,7 +32,7 @@ import com.google.common.collect.ImmutableSet;
*
*/
public abstract class AuthenticationUtilities {
/**
* Makes sure the authentication contains the given scope, throws an exception otherwise
* @param auth the authentication object to check
@ -63,7 +63,7 @@ public abstract class AuthenticationUtilities {
}
return false;
}
public static boolean hasRole(Authentication auth, String role) {
for (GrantedAuthority grantedAuthority : auth.getAuthorities()) {
@ -72,7 +72,7 @@ public abstract class AuthenticationUtilities {
}
}
return false;
}
}

View File

@ -70,7 +70,7 @@ public class IntrospectionEndpoint {
@Autowired
private UserInfoService userInfoService;
@Autowired
private ResourceSetService resourceSetService;
@ -94,52 +94,52 @@ public class IntrospectionEndpoint {
ClientDetailsEntity authClient = null;
Set<String> authScopes = new HashSet<>();
if (auth instanceof OAuth2Authentication) {
// the client authenticated with OAuth, do our UMA checks
ensureOAuthScope(auth, SystemScopeService.UMA_PROTECTION_SCOPE);
// get out the client that was issued the access token (not the token being introspected)
OAuth2Authentication o2a = (OAuth2Authentication) auth;
String authClientId = o2a.getOAuth2Request().getClientId();
authClient = clientService.loadClientByClientId(authClientId);
// the owner is the user who authorized the token in the first place
String ownerId = o2a.getUserAuthentication().getName();
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 {
// the client authenticated directly, make sure it's got the right access
String authClientId = auth.getName(); // direct authentication puts the client_id into the authentication's name field
authClient = clientService.loadClientByClientId(authClientId);
// directly authenticated clients get a subset of any scopes that they've registered for
authScopes.addAll(authClient.getScope());
if (!AuthenticationUtilities.hasRole(auth, "ROLE_CLIENT")
|| !authClient.isAllowIntrospection()) {
// this client isn't allowed to do direct introspection
logger.error("Client " + authClient.getClientId() + " is not allowed to call introspection endpoint");
model.addAttribute("code", HttpStatus.FORBIDDEN);
return HttpCodeView.VIEWNAME;
}
}
// by here we're allowed to introspect, now we need to look up the token in our token stores
// first make sure the token is there
@ -188,7 +188,7 @@ public class IntrospectionEndpoint {
}
// if it's a valid token, we'll print out information on it
if (accessToken != null) {
Map<String, Object> entity = introspectionResultAssembler.assembleFrom(accessToken, user, authScopes);
model.addAttribute(JsonEntityView.ENTITY, entity);
@ -202,9 +202,9 @@ public class IntrospectionEndpoint {
model.addAttribute(JsonEntityView.ENTITY, entity);
return JsonEntityView.VIEWNAME;
}
return JsonEntityView.VIEWNAME;
}
}

View File

@ -131,20 +131,20 @@ public class OAuthConfirmationController {
}
if (prompts.contains("none")) {
// if we've got a redirect URI then we'll send it
// if we've got a redirect URI then we'll send it
String url = redirectResolver.resolveRedirect(authRequest.getRedirectUri(), client);
try {
URIBuilder uriBuilder = new URIBuilder(url);
uriBuilder.addParameter("error", "interaction_required");
if (!Strings.isNullOrEmpty(authRequest.getState())) {
uriBuilder.addParameter("state", authRequest.getState()); // copy the state parameter if one was given
}
return "redirect:" + uriBuilder.toString();
} catch (URISyntaxException e) {
logger.error("Can't build redirect URI for prompt=none, sending error instead", e);
model.put("code", HttpStatus.FORBIDDEN);

View File

@ -52,7 +52,7 @@ import com.google.gson.Gson;
public class ScopeAPI {
public static final String URL = RootController.API_URL + "/scopes";
@Autowired
private SystemScopeService scopeService;

View File

@ -62,6 +62,7 @@ public class JWTBearerClientAssertionTokenEndpointFilter extends AbstractAuthent
public void afterPropertiesSet() {
super.afterPropertiesSet();
setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
if (exception instanceof BadCredentialsException) {
@ -71,6 +72,7 @@ public class JWTBearerClientAssertionTokenEndpointFilter extends AbstractAuthent
}
});
setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// no-op - just allow filter chain to continue to token endpoint
@ -109,13 +111,13 @@ public class JWTBearerClientAssertionTokenEndpointFilter extends AbstractAuthent
}
private static class ClientAssertionRequestMatcher implements RequestMatcher {
private RequestMatcher additionalMatcher;
public ClientAssertionRequestMatcher(RequestMatcher additionalMatcher) {
this.additionalMatcher = additionalMatcher;
}
@Override
public boolean matches(HttpServletRequest request) {
// check for appropriate parameters
@ -127,10 +129,10 @@ public class JWTBearerClientAssertionTokenEndpointFilter extends AbstractAuthent
} else if (!assertionType.equals("urn:ietf:params:oauth:client-assertion-type:jwt-bearer")) {
return false;
}
return additionalMatcher.matches(request);
}
}

View File

@ -47,30 +47,30 @@ public class JsonMessageSource extends AbstractMessageSource {
private static final Logger logger = LoggerFactory.getLogger(JsonMessageSource.class);
private Resource baseDirectory;
private Locale fallbackLocale = new Locale("en"); // US English is the fallback language
private Map<Locale, JsonObject> languageMaps = new HashMap<>();
@Override
protected MessageFormat resolveCode(String code, Locale locale) {
JsonObject lang = getLanguageMap(locale);
String value = getValue(code, lang);
if (value == null) {
// if we haven't found anything, try the default locale
lang = getLanguageMap(fallbackLocale);
value = getValue(code, lang);
}
if (value == null) {
value = code;
}
MessageFormat mf = new MessageFormat(value, locale);
return mf;
}
@ -81,44 +81,44 @@ public class JsonMessageSource extends AbstractMessageSource {
* @return
*/
private String getValue(String code, JsonObject lang) {
// if there's no language map, nothing to look up
if (lang == null) {
return null;
}
JsonElement e = lang;
Iterable<String> parts = Splitter.on('.').split(code);
Iterator<String> it = parts.iterator();
String value = null;
while (it.hasNext()) {
String p = it.next();
if (e.isJsonObject()) {
JsonObject o = e.getAsJsonObject();
if (o.has(p)) {
e = o.get(p); // found the next level
if (!it.hasNext()) {
// we've reached a leaf, grab it
if (e.isJsonPrimitive()) {
value = e.getAsString();
}
if (e.isJsonObject()) {
JsonObject o = e.getAsJsonObject();
if (o.has(p)) {
e = o.get(p); // found the next level
if (!it.hasNext()) {
// we've reached a leaf, grab it
if (e.isJsonPrimitive()) {
value = e.getAsString();
}
} else {
// didn't find it, stop processing
break;
}
} else {
// didn't find it, stop processing
break;
}
} else {
// didn't find it, stop processing
break;
}
}
return value;
}
/**
@ -126,28 +126,28 @@ public class JsonMessageSource extends AbstractMessageSource {
* @return
*/
private JsonObject getLanguageMap(Locale locale) {
if (!languageMaps.containsKey(locale)) {
try {
String filename = locale.getLanguage() + File.separator + "messages.json";
Resource r = getBaseDirectory().createRelative(filename);
logger.info("No locale loaded, trying to load from " + r);
JsonParser parser = new JsonParser();
JsonObject obj = (JsonObject) parser.parse(new InputStreamReader(r.getInputStream(), "UTF-8"));
languageMaps.put(locale, obj);
} catch (JsonIOException | JsonSyntaxException | IOException e) {
logger.error("Unable to load locale", e);
}
}
return languageMaps.get(locale);
}
/**

View File

@ -83,7 +83,7 @@ public class AuthorizationRequestFilter extends GenericFilterBean {
@Autowired
private ClientDetailsEntityService clientService;
@Autowired
private RedirectResolver redirectResolver;
@ -106,7 +106,7 @@ public class AuthorizationRequestFilter extends GenericFilterBean {
try {
// we have to create our own auth request in order to get at all the parmeters appropriately
AuthorizationRequest authRequest = null;
ClientDetailsEntity client = null;
authRequest = authRequestFactory.createAuthorizationRequest(createRequestMap(request.getParameterMap()));
@ -120,16 +120,16 @@ public class AuthorizationRequestFilter extends GenericFilterBean {
} else {
session.removeAttribute(LOGIN_HINT);
}
if (authRequest.getExtensions().get(PROMPT) != null) {
// we have a "prompt" parameter
String prompt = (String)authRequest.getExtensions().get(PROMPT);
List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt));
if (prompts.contains(PROMPT_NONE)) {
// see if the user's logged in
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
// user's been logged in already (by session management)
// we're OK, continue without prompting
@ -138,40 +138,40 @@ public class AuthorizationRequestFilter extends GenericFilterBean {
logger.info("Client requested no prompt");
// user hasn't been logged in, we need to "return an error"
if (client != null && authRequest.getRedirectUri() != null) {
// if we've got a redirect URI then we'll send it
// if we've got a redirect URI then we'll send it
String url = redirectResolver.resolveRedirect(authRequest.getRedirectUri(), client);
try {
URIBuilder uriBuilder = new URIBuilder(url);
uriBuilder.addParameter(ERROR, LOGIN_REQUIRED);
if (!Strings.isNullOrEmpty(authRequest.getState())) {
uriBuilder.addParameter(STATE, authRequest.getState()); // copy the state parameter if one was given
}
response.sendRedirect(uriBuilder.toString());
return;
} catch (URISyntaxException e) {
logger.error("Can't build redirect URI for prompt=none, sending error instead", e);
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
return;
}
}
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
return;
}
} else if (prompts.contains(PROMPT_LOGIN)) {
// first see if the user's already been prompted in this session
if (session.getAttribute(PROMPTED) == null) {
// user hasn't been PROMPTED yet, we need to check
session.setAttribute(PROMPT_REQUESTED, Boolean.TRUE);
// see if the user's logged in
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
@ -185,7 +185,7 @@ public class AuthorizationRequestFilter extends GenericFilterBean {
}
} else {
// user has been PROMPTED, we're fine
// but first, undo the prompt tag
session.removeAttribute(PROMPTED);
chain.doFilter(req, res);
@ -194,21 +194,21 @@ public class AuthorizationRequestFilter extends GenericFilterBean {
// prompt parameter is a value we don't care about, not our business
chain.doFilter(req, res);
}
} else if (authRequest.getExtensions().get(MAX_AGE) != null ||
(client != null && client.getDefaultMaxAge() != null)) {
// default to the client's stored value, check the string parameter
Integer max = (client != null ? client.getDefaultMaxAge() : null);
String maxAge = (String) authRequest.getExtensions().get(MAX_AGE);
if (maxAge != null) {
max = Integer.parseInt(maxAge);
}
if (max != null) {
Date authTime = (Date) session.getAttribute(AuthenticationTimeStamper.AUTH_TIMESTAMP);
Date now = new Date();
if (authTime != null) {
long seconds = (now.getTime() - authTime.getTime()) / 1000;
@ -223,7 +223,7 @@ public class AuthorizationRequestFilter extends GenericFilterBean {
// no prompt parameter, not our business
chain.doFilter(req, res);
}
} catch (InvalidClientException e) {
// we couldn't find the client, move on and let the rest of the system catch the error
chain.doFilter(req, res);

View File

@ -42,6 +42,7 @@ public class MultiUrlRequestMatcher implements RequestMatcher {
this.filterProcessesUrls = ImmutableSet.copyOf(filterProcessesUrls);
}
@Override
public boolean matches(HttpServletRequest request) {
String uri = request.getRequestURI();
int pathParamIndex = uri.indexOf(';');

View File

@ -58,7 +58,7 @@ public class JpaUserInfoRepository implements UserInfoRepository {
public UserInfo getByEmailAddress(String email) {
TypedQuery<DefaultUserInfo> query = manager.createNamedQuery(DefaultUserInfo.QUERY_BY_EMAIL, DefaultUserInfo.class);
query.setParameter(DefaultUserInfo.PARAM_EMAIL, email);
return getSingleResult(query.getResultList());
}

View File

@ -110,7 +110,7 @@ public class DefaultOIDCTokenService implements OIDCTokenService {
|| (client.getRequireAuthTime() != null && client.getRequireAuthTime())) {
if (request.getExtensions().get(AuthenticationTimeStamper.AUTH_TIMESTAMP) != null) {
Long authTimestamp = Long.parseLong((String) request.getExtensions().get(AuthenticationTimeStamper.AUTH_TIMESTAMP));
if (authTimestamp != null) {
idClaims.setClaim("auth_time", authTimestamp / 1000L);
@ -192,7 +192,7 @@ public class DefaultOIDCTokenService implements OIDCTokenService {
JWSHeader header = new JWSHeader(signingAlg, null, null, null, null, null, null, null, null, null,
jwtService.getDefaultSignerKeyId(),
null, null);
idToken = new SignedJWT(header, idClaims);
// sign it with the server's key

View File

@ -26,7 +26,7 @@ import org.mitre.uma.service.ResourceSetService;
import org.springframework.stereotype.Service;
/**
* Dummy resource set service that doesn't do anything; acts as a stub for the
* 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

View File

@ -36,7 +36,7 @@ public abstract class MITREidDataServiceSupport {
dateFormatter = new DateFormatter();
dateFormatter.setIso(ISO.DATE_TIME);
}
protected Date utcToDate(String value) {
if (value == null) {
return null;
@ -48,7 +48,7 @@ public abstract class MITREidDataServiceSupport {
}
return null;
}
protected String toUTCString(Date value) {
if (value == null) {
return null;

View File

@ -96,7 +96,7 @@ public class MITREidDataService_1_0 extends MITREidDataServiceSupport implements
private OAuth2TokenRepository tokenRepository;
@Autowired
private SystemScopeRepository sysScopeRepository;
/* (non-Javadoc)
* @see org.mitre.openid.connect.service.MITREidDataService#export(com.google.gson.stream.JsonWriter)
*/
@ -149,16 +149,16 @@ public class MITREidDataService_1_0 extends MITREidDataServiceSupport implements
reader.endObject();
continue;
default:
logger.debug("Found unexpected entry");
reader.skipValue();
continue; }
logger.debug("Found unexpected entry");
reader.skipValue();
continue; }
}
fixObjectReferences();
}
private Map<Long, String> refreshTokenToClientRefs = new HashMap<>();
private Map<Long, Long> refreshTokenToAuthHolderRefs = new HashMap<>();
private Map<Long, Long> refreshTokenOldToNewIdMap = new HashMap<>();
/**
* @param reader
* @throws IOException
@ -347,10 +347,10 @@ public class MITREidDataService_1_0 extends MITREidDataServiceSupport implements
} else if (subName.equals("userAuthentication")) {
// skip binary encoded version
reader.skipValue();
} else if (subName.equals("savedUserAuthentication")) {
userAuthentication = readSavedUserAuthentication(reader);
} else {
logger.debug("Found unexpected entry");
reader.skipValue();
@ -444,16 +444,16 @@ public class MITREidDataService_1_0 extends MITREidDataServiceSupport implements
reader.endObject();
return new OAuth2Request(authorizationParameters, clientId, authorities, approved, scope, resourceIds, redirectUri, responseTypes, null);
}
/**
* @param reader
* @return
* @throws IOException
* @throws IOException
*/
private SavedUserAuthentication readSavedUserAuthentication(JsonReader reader) throws IOException {
SavedUserAuthentication savedUserAuth = new SavedUserAuthentication();
reader.beginObject();
while (reader.hasNext()) {
switch(reader.peek()) {
case END_OBJECT:
@ -487,7 +487,7 @@ public class MITREidDataService_1_0 extends MITREidDataServiceSupport implements
continue;
}
}
reader.endObject();
return savedUserAuth;
}

View File

@ -99,7 +99,7 @@ public class MITREidDataService_1_1 extends MITREidDataServiceSupport implements
private OAuth2TokenRepository tokenRepository;
@Autowired
private SystemScopeRepository sysScopeRepository;
/* (non-Javadoc)
* @see org.mitre.openid.connect.service.MITREidDataService#export(com.google.gson.stream.JsonWriter)
*/
@ -350,10 +350,10 @@ public class MITREidDataService_1_1 extends MITREidDataServiceSupport implements
} else if (subName.equals("userAuthentication")) {
// skip binary encoded version
reader.skipValue();
} else if (subName.equals("savedUserAuthentication")) {
userAuthentication = readSavedUserAuthentication(reader);
} else {
logger.debug("Found unexpected entry");
reader.skipValue();
@ -454,16 +454,16 @@ public class MITREidDataService_1_1 extends MITREidDataServiceSupport implements
reader.endObject();
return new OAuth2Request(requestParameters, clientId, authorities, approved, scope, resourceIds, redirectUri, responseTypes, extensions);
}
/**
* @param reader
* @return
* @throws IOException
* @throws IOException
*/
private SavedUserAuthentication readSavedUserAuthentication(JsonReader reader) throws IOException {
SavedUserAuthentication savedUserAuth = new SavedUserAuthentication();
reader.beginObject();
while (reader.hasNext()) {
switch(reader.peek()) {
case END_OBJECT:
@ -497,7 +497,7 @@ public class MITREidDataService_1_1 extends MITREidDataServiceSupport implements
continue;
}
}
reader.endObject();
return savedUserAuth;
}
@ -922,5 +922,5 @@ public class MITREidDataService_1_1 extends MITREidDataServiceSupport implements
accessTokenOldToNewIdMap.clear();
grantOldToNewIdMap.clear();
}
}

View File

@ -163,7 +163,7 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
private OAuth2TokenRepository tokenRepository;
@Autowired
private SystemScopeRepository sysScopeRepository;
/* (non-Javadoc)
* @see org.mitre.openid.connect.service.MITREidDataService#export(com.google.gson.stream.JsonWriter)
*/
@ -275,7 +275,7 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
for (AuthenticationHolderEntity holder : authHolderRepository.getAll()) {
writer.beginObject();
writer.name(ID).value(holder.getId());
writer.name(REQUEST_PARAMETERS);
writer.beginObject();
for (Entry<String, String> entry : holder.getRequestParameters().entrySet()) {
@ -336,13 +336,13 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
writer.value(authority.getAuthority());
}
writer.endArray();
writer.endObject();
} else {
writer.nullValue();
}
writer.endObject();
logger.debug("Wrote authentication holder {}", holder.getId());
}
@ -804,12 +804,12 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
/**
* @param reader
* @return
* @throws IOException
* @throws IOException
*/
private SavedUserAuthentication readSavedUserAuthentication(JsonReader reader) throws IOException {
SavedUserAuthentication savedUserAuth = new SavedUserAuthentication();
reader.beginObject();
while (reader.hasNext()) {
switch(reader.peek()) {
case END_OBJECT:
@ -843,7 +843,7 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
continue;
}
}
reader.endObject();
return savedUserAuth;
}
@ -1274,5 +1274,5 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
grantOldToNewIdMap.clear();
logger.info("Done fixing object references.");
}
}

View File

@ -63,7 +63,7 @@ public abstract class AbstractClientEntityView extends AbstractView {
private static final Logger logger = LoggerFactory.getLogger(AbstractClientEntityView.class);
private JsonParser parser = new JsonParser();
private Gson gson = new GsonBuilder()
.setExclusionStrategies(getExclusionStrategy())
.registerTypeAdapter(JWSAlgorithm.class, new JsonSerializer<JWSAlgorithm>() {

View File

@ -37,7 +37,7 @@ import org.springframework.web.servlet.view.AbstractView;
public class HttpCodeView extends AbstractView {
public static final String VIEWNAME = "httpCodeView";
public static final String CODE = "code";
@Override

View File

@ -56,27 +56,27 @@ public class JsonEntityView extends AbstractView {
public static final String VIEWNAME = "jsonEntityView";
private Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return false;
.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return false;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
// skip the JPA binding wrapper
if (clazz.equals(BeanPropertyBindingResult.class)) {
return true;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
// skip the JPA binding wrapper
if (clazz.equals(BeanPropertyBindingResult.class)) {
return true;
}
return false;
}
})
.serializeNulls()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
return false;
}
})
.serializeNulls()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {

View File

@ -71,8 +71,8 @@ public class UserInfoJWTView extends UserInfoView {
public static final String JOSE_MEDIA_TYPE_VALUE = "application/jwt";
public static final MediaType JOSE_MEDIA_TYPE = new MediaType("application", "jwt");
@Autowired
private JWTSigningAndValidationService jwtService;

View File

@ -53,7 +53,7 @@ public class UserInfoView extends AbstractView {
public static final String USER_INFO = "userInfo";
public static final String VIEWNAME = "userInfoView";
private static JsonParser jsonParser = new JsonParser();
/**

View File

@ -224,13 +224,13 @@ public class ClientAPI {
}
client.setDynamicallyRegistered(false);
try {
ClientDetailsEntity newClient = clientService.saveNewClient(client);
m.addAttribute(JsonEntityView.ENTITY, newClient);
if (AuthenticationUtilities.isAdmin(auth)) {
return ClientEntityViewForAdmins.VIEWNAME;
} else {
@ -331,7 +331,7 @@ public class ClientAPI {
try {
ClientDetailsEntity newClient = clientService.updateClient(oldClient, client);
m.addAttribute(JsonEntityView.ENTITY, newClient);
if (AuthenticationUtilities.isAdmin(auth)) {
return ClientEntityViewForAdmins.VIEWNAME;
} else {

View File

@ -32,7 +32,7 @@ import com.nimbusds.jose.jwk.JWK;
public class JWKSetPublishingEndpoint {
public static final String URL = "jwk";
@Autowired
private JWTSigningAndValidationService jwtService;

View File

@ -220,7 +220,7 @@ public class ProtectedResourceRegistrationEndpoint {
if (allowedScopes == null || allowedScopes.isEmpty()) {
allowedScopes = scopeService.getDefaults();
}
newClient.setScope(scopeService.toStrings(allowedScopes));
return newClient;

View File

@ -31,7 +31,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RootController {
public static final String API_URL = "api";
@Autowired

View File

@ -28,7 +28,7 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
*
* Injects the server configuration bean into the request context.
* Injects the server configuration bean into the request context.
* This allows JSPs and the like to call "config.logoUrl" among others.
*
* @author jricher
@ -44,5 +44,5 @@ public class ServerConfigInterceptor extends HandlerInterceptorAdapter {
request.setAttribute("config", config);
return true;
}
}

View File

@ -54,7 +54,7 @@ import com.google.common.base.Strings;
public class UserInfoEndpoint {
public static final String URL = "userinfo";
@Autowired
private UserInfoService userInfoService;

View File

@ -47,84 +47,84 @@ public class TestBlacklistAwareRedirectResolver {
@Mock
private BlacklistedSiteService blacklistService;
@Mock
private ClientDetails client;
@InjectMocks
private BlacklistAwareRedirectResolver resolver;
private String blacklistedUri = "https://evil.example.com/";
private String goodUri = "https://good.example.com/";
private String pathUri = "https://good.example.com/with/path";
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
when(blacklistService.isBlacklisted(anyString())).thenReturn(false);
when(blacklistService.isBlacklisted(blacklistedUri)).thenReturn(true);
when(client.getAuthorizedGrantTypes()).thenReturn(ImmutableSet.of("authorization_code"));
when(client.getRegisteredRedirectUri()).thenReturn(ImmutableSet.of(goodUri, blacklistedUri));
}
@Test
public void testResolveRedirect_safe() {
// default uses prefix matching, both of these should work
String res1 = resolver.resolveRedirect(goodUri, client);
assertThat(res1, is(equalTo(goodUri)));
String res2 = resolver.resolveRedirect(pathUri, client);
assertThat(res2, is(equalTo(pathUri)));
}
@Test(expected = InvalidRequestException.class)
public void testResolveRedirect_blacklisted() {
// this should fail with an error
// this should fail with an error
resolver.resolveRedirect(blacklistedUri, client);
}
@Test
public void testRedirectMatches_strict() {
resolver.setStrictMatch(true);
// this is not an exact match
boolean res1 = resolver.redirectMatches(pathUri, goodUri);
assertThat(res1, is(false));
// this is an exact match
boolean res2 = resolver.redirectMatches(goodUri, goodUri);
assertThat(res2, is(true));
}
@Test
public void testRedirectMatches_default() {
// this is not an exact match (but that's OK)
boolean res1 = resolver.redirectMatches(pathUri, goodUri);
assertThat(res1, is(true));
// this is an exact match
boolean res2 = resolver.redirectMatches(goodUri, goodUri);
assertThat(res2, is(true));
}

View File

@ -62,7 +62,7 @@ public class TestDefaultIntrospectionResultAssembler {
authentication("name", request("clientId")));
UserInfo userInfo = userInfo("sub");
Set<String> authScopes = scopes("foo", "bar", "baz");
// when
@ -87,12 +87,12 @@ public class TestDefaultIntrospectionResultAssembler {
public void shouldAssembleExpectedResultForAccessToken_withPermissions() throws ParseException {
// given
OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"),
OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"),
permissions(permission(1L, "foo", "bar")),
"Bearer", authentication("name", request("clientId")));
UserInfo userInfo = userInfo("sub");
Set<String> authScopes = scopes("foo", "bar", "baz");
// when
@ -297,11 +297,11 @@ public class TestDefaultIntrospectionResultAssembler {
private Set<String> scopes(String... 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);

View File

@ -77,7 +77,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
@Mock
private SystemScopeService scopeService;
@Mock
private ResourceSetService resourceSetService;
@ -119,7 +119,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
return output;
}
});
Mockito.when(scopeService.toStrings(Matchers.anySet())).thenAnswer(new Answer<Set<String>>() {
@Override
public Set<String> answer(InvocationOnMock invocation) throws Throwable {
@ -132,7 +132,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
return output;
}
});
// we're not testing reserved scopes here, just pass through when it's called
Mockito.when(scopeService.removeReservedScopes(Matchers.anySet())).then(AdditionalAnswers.returnsFirstArg());
@ -208,7 +208,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
client = service.saveNewClient(client);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(false)));
}
@ -270,7 +270,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
Mockito.when(whitelistedSiteService.getByClientId(clientId)).thenReturn(site);
Mockito.when(resourceSetService.getAllForClient(client)).thenReturn(new HashSet<ResourceSet>());
service.deleteClient(client);
Mockito.verify(tokenRepository).clearTokensForClient(client);
@ -333,7 +333,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
client = service.updateClient(oldClient, client);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(true)));
}
@ -350,7 +350,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
client = service.updateClient(oldClient, client);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(false)));
}
}

View File

@ -129,7 +129,7 @@ public class TestDefaultOAuth2ProviderTokenService {
// by default in tests, allow refresh tokens
Mockito.when(client.isAllowRefresh()).thenReturn(true);
// by default, clear access tokens on refresh
Mockito.when(client.isClearAccessTokensOnRefresh()).thenReturn(true);
@ -167,7 +167,7 @@ public class TestDefaultOAuth2ProviderTokenService {
return output;
}
});
Mockito.when(scopeService.toStrings(Matchers.anySet())).thenAnswer(new Answer<Set<String>>() {
@Override
public Set<String> answer(InvocationOnMock invocation) throws Throwable {
@ -266,7 +266,7 @@ public class TestDefaultOAuth2ProviderTokenService {
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
Mockito.verify(tokenRepository, Mockito.never()).saveRefreshToken(Matchers.any(OAuth2RefreshTokenEntity.class));
assertThat(token.getRefreshToken(), is(nullValue()));
}
@ -285,7 +285,7 @@ public class TestDefaultOAuth2ProviderTokenService {
// Note: a refactor may be appropriate to only save refresh tokens once to the repository during creation.
Mockito.verify(tokenRepository, Mockito.atLeastOnce()).saveRefreshToken(Matchers.any(OAuth2RefreshTokenEntity.class));
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
assertThat(token.getRefreshToken(), is(notNullValue()));
}
@ -313,7 +313,7 @@ public class TestDefaultOAuth2ProviderTokenService {
Date upperBoundRefreshTokens = new Date(end + (refreshTokenValiditySeconds * 1000L) + DELTA);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
assertTrue(token.getExpiration().after(lowerBoundAccessTokens) && token.getExpiration().before(upperBoundAccessTokens));
assertTrue(token.getRefreshToken().getExpiration().after(lowerBoundRefreshTokens) && token.getRefreshToken().getExpiration().before(upperBoundRefreshTokens));
}
@ -324,7 +324,7 @@ public class TestDefaultOAuth2ProviderTokenService {
OAuth2AccessTokenEntity token = service.createAccessToken(authentication);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
assertThat(token.getClient().getClientId(), equalTo(clientId));
}
@ -334,7 +334,7 @@ public class TestDefaultOAuth2ProviderTokenService {
OAuth2AccessTokenEntity token = service.createAccessToken(authentication);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
assertThat(token.getScope(), equalTo(scope));
}
@ -351,7 +351,7 @@ public class TestDefaultOAuth2ProviderTokenService {
assertThat(token.getAuthenticationHolder().getAuthentication(), equalTo(authentication));
Mockito.verify(authenticationHolderRepository).save(Matchers.any(AuthenticationHolderEntity.class));
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
}
@Test(expected = InvalidTokenException.class)
@ -400,14 +400,14 @@ public class TestDefaultOAuth2ProviderTokenService {
Mockito.verify(tokenEnhancer).enhance(token, storedAuthentication);
Mockito.verify(tokenRepository).saveAccessToken(token);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
}
@Test
public void refreshAccessToken_rotateRefreshToken() {
when(client.isReuseRefreshToken()).thenReturn(false);
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
Mockito.verify(tokenRepository).clearAccessTokensForRefreshToken(refreshToken);
@ -420,14 +420,14 @@ public class TestDefaultOAuth2ProviderTokenService {
Mockito.verify(tokenRepository).saveAccessToken(token);
Mockito.verify(tokenRepository).removeRefreshToken(refreshToken);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
}
@Test
public void refreshAccessToken_keepAccessTokens() {
when(client.isClearAccessTokensOnRefresh()).thenReturn(false);
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
Mockito.verify(tokenRepository, never()).clearAccessTokensForRefreshToken(refreshToken);
@ -439,16 +439,16 @@ public class TestDefaultOAuth2ProviderTokenService {
Mockito.verify(tokenEnhancer).enhance(token, storedAuthentication);
Mockito.verify(tokenRepository).saveAccessToken(token);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
}
@Test
public void refreshAccessToken_requestingSameScope() {
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
assertThat(token.getScope(), equalTo(storedScope));
}
@ -462,7 +462,7 @@ public class TestDefaultOAuth2ProviderTokenService {
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
assertThat(token.getScope(), equalTo(lessScope));
}
@ -502,7 +502,7 @@ public class TestDefaultOAuth2ProviderTokenService {
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
assertThat(token.getScope(), equalTo(storedScope));
}
@ -514,7 +514,7 @@ public class TestDefaultOAuth2ProviderTokenService {
OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
assertThat(token.getScope(), equalTo(storedScope));
}
@ -538,7 +538,7 @@ public class TestDefaultOAuth2ProviderTokenService {
Date upperBoundAccessTokens = new Date(end + (accessTokenValiditySeconds * 1000L) + DELTA);
Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet());
assertTrue(token.getExpiration().after(lowerBoundAccessTokens) && token.getExpiration().before(upperBoundAccessTokens));
}

View File

@ -104,7 +104,7 @@ public class TestDefaultSystemScopeService {
restrictedScope1 = new SystemScope(restrictedScope1String);
restrictedScope1.setRestricted(true);
// structuredScope1 : structured scope
structuredScope1 = new SystemScope(structuredScope1String);
structuredScope1.setStructured(true);
@ -167,9 +167,9 @@ public class TestDefaultSystemScopeService {
Set<SystemScope> restricted = Sets.newHashSet(defaultScope1, defaultScope2, restrictedScope1);
assertThat(service.getRestricted(), equalTo(restricted));
}
@Test
public void fromStrings() {

View File

@ -123,7 +123,7 @@ public class TestMITREidDataService_1_0 {
@InjectMocks
private MITREidDataService_1_0 dataService;
private DateFormatter formatter;
@Before
@ -139,7 +139,7 @@ public class TestMITREidDataService_1_0 {
return entity1.getId().compareTo(entity2.getId());
}
}
@Test
public void testImportRefreshTokens() throws IOException, ParseException {
Date expirationDate1 = formatter.parse("2014-09-10T22:49:44.090+0000", Locale.ENGLISH);
@ -236,18 +236,18 @@ public class TestMITREidDataService_1_0 {
//2 times for token, 2 times to update client, 2 times to update authHolder
verify(tokenRepository, times(6)).saveRefreshToken(capturedRefreshTokens.capture());
List<OAuth2RefreshTokenEntity> savedRefreshTokens = new ArrayList(fakeDb.values()); //capturedRefreshTokens.getAllValues();
Collections.sort(savedRefreshTokens, new refreshTokenIdComparator());
List<OAuth2RefreshTokenEntity> savedRefreshTokens = new ArrayList(fakeDb.values()); //capturedRefreshTokens.getAllValues();
Collections.sort(savedRefreshTokens, new refreshTokenIdComparator());
assertThat(savedRefreshTokens.size(), is(2));
assertThat(savedRefreshTokens.size(), is(2));
assertThat(savedRefreshTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId()));
assertThat(savedRefreshTokens.get(0).getExpiration(), equalTo(token1.getExpiration()));
assertThat(savedRefreshTokens.get(0).getValue(), equalTo(token1.getValue()));
assertThat(savedRefreshTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId()));
assertThat(savedRefreshTokens.get(0).getExpiration(), equalTo(token1.getExpiration()));
assertThat(savedRefreshTokens.get(0).getValue(), equalTo(token1.getValue()));
assertThat(savedRefreshTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
assertThat(savedRefreshTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
assertThat(savedRefreshTokens.get(1).getValue(), equalTo(token2.getValue()));
assertThat(savedRefreshTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
assertThat(savedRefreshTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
assertThat(savedRefreshTokens.get(1).getValue(), equalTo(token2.getValue()));
}
private class accessTokenIdComparator implements Comparator<OAuth2AccessTokenEntity> {
@ -367,18 +367,18 @@ public class TestMITREidDataService_1_0 {
//2 times for token, 2 times to update client, 2 times to update authHolder, 2 times to update id token, 2 times to update refresh token
verify(tokenRepository, times(8)).saveAccessToken(capturedAccessTokens.capture());
List<OAuth2AccessTokenEntity> savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues();
Collections.sort(savedAccessTokens, new accessTokenIdComparator());
List<OAuth2AccessTokenEntity> savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues();
Collections.sort(savedAccessTokens, new accessTokenIdComparator());
assertThat(savedAccessTokens.size(), is(2));
assertThat(savedAccessTokens.size(), is(2));
assertThat(savedAccessTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId()));
assertThat(savedAccessTokens.get(0).getExpiration(), equalTo(token1.getExpiration()));
assertThat(savedAccessTokens.get(0).getValue(), equalTo(token1.getValue()));
assertThat(savedAccessTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId()));
assertThat(savedAccessTokens.get(0).getExpiration(), equalTo(token1.getExpiration()));
assertThat(savedAccessTokens.get(0).getValue(), equalTo(token1.getValue()));
assertThat(savedAccessTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue()));
assertThat(savedAccessTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue()));
}
@ -670,23 +670,23 @@ public class TestMITREidDataService_1_0 {
//2 for sites, 1 for updating access token ref on #1
verify(approvedSiteRepository, times(3)).save(capturedApprovedSites.capture());
List<ApprovedSite> savedSites = new ArrayList(fakeDb.values());
List<ApprovedSite> savedSites = new ArrayList(fakeDb.values());
assertThat(savedSites.size(), is(2));
assertThat(savedSites.size(), is(2));
assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId()));
assertThat(savedSites.get(0).getAccessDate(), equalTo(site1.getAccessDate()));
assertThat(savedSites.get(0).getCreationDate(), equalTo(site1.getCreationDate()));
assertThat(savedSites.get(0).getAllowedScopes(), equalTo(site1.getAllowedScopes()));
assertThat(savedSites.get(0).getTimeoutDate(), equalTo(site1.getTimeoutDate()));
assertThat(savedSites.get(0).getApprovedAccessTokens().size(), equalTo(site1.getApprovedAccessTokens().size()));
assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId()));
assertThat(savedSites.get(0).getAccessDate(), equalTo(site1.getAccessDate()));
assertThat(savedSites.get(0).getCreationDate(), equalTo(site1.getCreationDate()));
assertThat(savedSites.get(0).getAllowedScopes(), equalTo(site1.getAllowedScopes()));
assertThat(savedSites.get(0).getTimeoutDate(), equalTo(site1.getTimeoutDate()));
assertThat(savedSites.get(0).getApprovedAccessTokens().size(), equalTo(site1.getApprovedAccessTokens().size()));
assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId()));
assertThat(savedSites.get(1).getAccessDate(), equalTo(site2.getAccessDate()));
assertThat(savedSites.get(1).getCreationDate(), equalTo(site2.getCreationDate()));
assertThat(savedSites.get(1).getAllowedScopes(), equalTo(site2.getAllowedScopes()));
assertThat(savedSites.get(1).getTimeoutDate(), equalTo(site2.getTimeoutDate()));
assertThat(savedSites.get(1).getApprovedAccessTokens().size(), equalTo(site2.getApprovedAccessTokens().size()));
assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId()));
assertThat(savedSites.get(1).getAccessDate(), equalTo(site2.getAccessDate()));
assertThat(savedSites.get(1).getCreationDate(), equalTo(site2.getCreationDate()));
assertThat(savedSites.get(1).getAllowedScopes(), equalTo(site2.getAllowedScopes()));
assertThat(savedSites.get(1).getTimeoutDate(), equalTo(site2.getTimeoutDate()));
assertThat(savedSites.get(1).getApprovedAccessTokens().size(), equalTo(site2.getApprovedAccessTokens().size()));
}
@Test

View File

@ -240,18 +240,18 @@ public class TestMITREidDataService_1_1 {
//2 times for token, 2 times to update client, 2 times to update authHolder
verify(tokenRepository, times(6)).saveRefreshToken(capturedRefreshTokens.capture());
List<OAuth2RefreshTokenEntity> savedRefreshTokens = new ArrayList(fakeDb.values()); //capturedRefreshTokens.getAllValues();
Collections.sort(savedRefreshTokens, new refreshTokenIdComparator());
List<OAuth2RefreshTokenEntity> savedRefreshTokens = new ArrayList(fakeDb.values()); //capturedRefreshTokens.getAllValues();
Collections.sort(savedRefreshTokens, new refreshTokenIdComparator());
assertThat(savedRefreshTokens.size(), is(2));
assertThat(savedRefreshTokens.size(), is(2));
assertThat(savedRefreshTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId()));
assertThat(savedRefreshTokens.get(0).getExpiration(), equalTo(token1.getExpiration()));
assertThat(savedRefreshTokens.get(0).getValue(), equalTo(token1.getValue()));
assertThat(savedRefreshTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId()));
assertThat(savedRefreshTokens.get(0).getExpiration(), equalTo(token1.getExpiration()));
assertThat(savedRefreshTokens.get(0).getValue(), equalTo(token1.getValue()));
assertThat(savedRefreshTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
assertThat(savedRefreshTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
assertThat(savedRefreshTokens.get(1).getValue(), equalTo(token2.getValue()));
assertThat(savedRefreshTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
assertThat(savedRefreshTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
assertThat(savedRefreshTokens.get(1).getValue(), equalTo(token2.getValue()));
}
private class accessTokenIdComparator implements Comparator<OAuth2AccessTokenEntity> {
@ -372,18 +372,18 @@ public class TestMITREidDataService_1_1 {
//2 times for token, 2 times to update client, 2 times to update authHolder, 2 times to update id token, 2 times to update refresh token
verify(tokenRepository, times(8)).saveAccessToken(capturedAccessTokens.capture());
List<OAuth2AccessTokenEntity> savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues();
Collections.sort(savedAccessTokens, new accessTokenIdComparator());
List<OAuth2AccessTokenEntity> savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues();
Collections.sort(savedAccessTokens, new accessTokenIdComparator());
assertThat(savedAccessTokens.size(), is(2));
assertThat(savedAccessTokens.size(), is(2));
assertThat(savedAccessTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId()));
assertThat(savedAccessTokens.get(0).getExpiration(), equalTo(token1.getExpiration()));
assertThat(savedAccessTokens.get(0).getValue(), equalTo(token1.getValue()));
assertThat(savedAccessTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId()));
assertThat(savedAccessTokens.get(0).getExpiration(), equalTo(token1.getExpiration()));
assertThat(savedAccessTokens.get(0).getValue(), equalTo(token1.getValue()));
assertThat(savedAccessTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue()));
assertThat(savedAccessTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue()));
}
@Test
@ -674,23 +674,23 @@ public class TestMITREidDataService_1_1 {
//2 for sites, 1 for updating access token ref on #1
verify(approvedSiteRepository, times(3)).save(capturedApprovedSites.capture());
List<ApprovedSite> savedSites = new ArrayList(fakeDb.values());
List<ApprovedSite> savedSites = new ArrayList(fakeDb.values());
assertThat(savedSites.size(), is(2));
assertThat(savedSites.size(), is(2));
assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId()));
assertThat(savedSites.get(0).getAccessDate(), equalTo(site1.getAccessDate()));
assertThat(savedSites.get(0).getCreationDate(), equalTo(site1.getCreationDate()));
assertThat(savedSites.get(0).getAllowedScopes(), equalTo(site1.getAllowedScopes()));
assertThat(savedSites.get(0).getTimeoutDate(), equalTo(site1.getTimeoutDate()));
assertThat(savedSites.get(0).getApprovedAccessTokens().size(), equalTo(site1.getApprovedAccessTokens().size()));
assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId()));
assertThat(savedSites.get(0).getAccessDate(), equalTo(site1.getAccessDate()));
assertThat(savedSites.get(0).getCreationDate(), equalTo(site1.getCreationDate()));
assertThat(savedSites.get(0).getAllowedScopes(), equalTo(site1.getAllowedScopes()));
assertThat(savedSites.get(0).getTimeoutDate(), equalTo(site1.getTimeoutDate()));
assertThat(savedSites.get(0).getApprovedAccessTokens().size(), equalTo(site1.getApprovedAccessTokens().size()));
assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId()));
assertThat(savedSites.get(1).getAccessDate(), equalTo(site2.getAccessDate()));
assertThat(savedSites.get(1).getCreationDate(), equalTo(site2.getCreationDate()));
assertThat(savedSites.get(1).getAllowedScopes(), equalTo(site2.getAllowedScopes()));
assertThat(savedSites.get(1).getTimeoutDate(), equalTo(site2.getTimeoutDate()));
assertThat(savedSites.get(1).getApprovedAccessTokens().size(), equalTo(site2.getApprovedAccessTokens().size()));
assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId()));
assertThat(savedSites.get(1).getAccessDate(), equalTo(site2.getAccessDate()));
assertThat(savedSites.get(1).getCreationDate(), equalTo(site2.getCreationDate()));
assertThat(savedSites.get(1).getAllowedScopes(), equalTo(site2.getAllowedScopes()));
assertThat(savedSites.get(1).getTimeoutDate(), equalTo(site2.getTimeoutDate()));
assertThat(savedSites.get(1).getApprovedAccessTokens().size(), equalTo(site2.getApprovedAccessTokens().size()));
}
@Test

View File

@ -102,7 +102,7 @@ import static org.junit.Assert.fail;
@RunWith(MockitoJUnitRunner.class)
@SuppressWarnings(value = {"rawtypes", "unchecked"})
public class TestMITREidDataService_1_2 {
private static Logger logger = LoggerFactory.getLogger(TestMITREidDataService_1_2.class);
@Mock
@ -370,18 +370,18 @@ public class TestMITREidDataService_1_2 {
//2 times for token, 2 times to update client, 2 times to update authHolder
verify(tokenRepository, times(6)).saveRefreshToken(capturedRefreshTokens.capture());
List<OAuth2RefreshTokenEntity> savedRefreshTokens = new ArrayList(fakeDb.values()); //capturedRefreshTokens.getAllValues();
Collections.sort(savedRefreshTokens, new refreshTokenIdComparator());
List<OAuth2RefreshTokenEntity> savedRefreshTokens = new ArrayList(fakeDb.values()); //capturedRefreshTokens.getAllValues();
Collections.sort(savedRefreshTokens, new refreshTokenIdComparator());
assertThat(savedRefreshTokens.size(), is(2));
assertThat(savedRefreshTokens.size(), is(2));
assertThat(savedRefreshTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId()));
assertThat(savedRefreshTokens.get(0).getExpiration(), equalTo(token1.getExpiration()));
assertThat(savedRefreshTokens.get(0).getValue(), equalTo(token1.getValue()));
assertThat(savedRefreshTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId()));
assertThat(savedRefreshTokens.get(0).getExpiration(), equalTo(token1.getExpiration()));
assertThat(savedRefreshTokens.get(0).getValue(), equalTo(token1.getValue()));
assertThat(savedRefreshTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
assertThat(savedRefreshTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
assertThat(savedRefreshTokens.get(1).getValue(), equalTo(token2.getValue()));
assertThat(savedRefreshTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
assertThat(savedRefreshTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
assertThat(savedRefreshTokens.get(1).getValue(), equalTo(token2.getValue()));
}
@Test
@ -639,18 +639,18 @@ public class TestMITREidDataService_1_2 {
//2 times for token, 2 times to update client, 2 times to update authHolder, 2 times to update id token, 2 times to update refresh token
verify(tokenRepository, times(8)).saveAccessToken(capturedAccessTokens.capture());
List<OAuth2AccessTokenEntity> savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues();
Collections.sort(savedAccessTokens, new accessTokenIdComparator());
List<OAuth2AccessTokenEntity> savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues();
Collections.sort(savedAccessTokens, new accessTokenIdComparator());
assertThat(savedAccessTokens.size(), is(2));
assertThat(savedAccessTokens.size(), is(2));
assertThat(savedAccessTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId()));
assertThat(savedAccessTokens.get(0).getExpiration(), equalTo(token1.getExpiration()));
assertThat(savedAccessTokens.get(0).getValue(), equalTo(token1.getValue()));
assertThat(savedAccessTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId()));
assertThat(savedAccessTokens.get(0).getExpiration(), equalTo(token1.getExpiration()));
assertThat(savedAccessTokens.get(0).getValue(), equalTo(token1.getValue()));
assertThat(savedAccessTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue()));
assertThat(savedAccessTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue()));
}
@Test
@ -1357,23 +1357,23 @@ public class TestMITREidDataService_1_2 {
//2 for sites, 1 for updating access token ref on #1
verify(approvedSiteRepository, times(3)).save(capturedApprovedSites.capture());
List<ApprovedSite> savedSites = new ArrayList(fakeDb.values());
List<ApprovedSite> savedSites = new ArrayList(fakeDb.values());
assertThat(savedSites.size(), is(2));
assertThat(savedSites.size(), is(2));
assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId()));
assertThat(savedSites.get(0).getAccessDate(), equalTo(site1.getAccessDate()));
assertThat(savedSites.get(0).getCreationDate(), equalTo(site1.getCreationDate()));
assertThat(savedSites.get(0).getAllowedScopes(), equalTo(site1.getAllowedScopes()));
assertThat(savedSites.get(0).getTimeoutDate(), equalTo(site1.getTimeoutDate()));
assertThat(savedSites.get(0).getApprovedAccessTokens().size(), equalTo(site1.getApprovedAccessTokens().size()));
assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId()));
assertThat(savedSites.get(0).getAccessDate(), equalTo(site1.getAccessDate()));
assertThat(savedSites.get(0).getCreationDate(), equalTo(site1.getCreationDate()));
assertThat(savedSites.get(0).getAllowedScopes(), equalTo(site1.getAllowedScopes()));
assertThat(savedSites.get(0).getTimeoutDate(), equalTo(site1.getTimeoutDate()));
assertThat(savedSites.get(0).getApprovedAccessTokens().size(), equalTo(site1.getApprovedAccessTokens().size()));
assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId()));
assertThat(savedSites.get(1).getAccessDate(), equalTo(site2.getAccessDate()));
assertThat(savedSites.get(1).getCreationDate(), equalTo(site2.getCreationDate()));
assertThat(savedSites.get(1).getAllowedScopes(), equalTo(site2.getAllowedScopes()));
assertThat(savedSites.get(1).getTimeoutDate(), equalTo(site2.getTimeoutDate()));
assertThat(savedSites.get(1).getApprovedAccessTokens().size(), equalTo(site2.getApprovedAccessTokens().size()));
assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId()));
assertThat(savedSites.get(1).getAccessDate(), equalTo(site2.getAccessDate()));
assertThat(savedSites.get(1).getCreationDate(), equalTo(site2.getCreationDate()));
assertThat(savedSites.get(1).getAllowedScopes(), equalTo(site2.getAllowedScopes()));
assertThat(savedSites.get(1).getTimeoutDate(), equalTo(site2.getTimeoutDate()));
assertThat(savedSites.get(1).getApprovedAccessTokens().size(), equalTo(site2.getApprovedAccessTokens().size()));
}
@Test
@ -1407,7 +1407,7 @@ public class TestMITREidDataService_1_2 {
when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet<OAuth2AccessTokenEntity>());
when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet<OAuth2RefreshTokenEntity>());
when(sysScopeRepository.getAll()).thenReturn(new HashSet<SystemScope>());
// do the data export
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);

View File

@ -176,10 +176,10 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
private static final String PERMISSION = "permission";
private static final String TICKET = "ticket";
private static final String CLAIMS_SUPPLIED = "claimsSupplied";
private static final String SAVED_REGISTERED_CLIENTS = "savedRegisteredClients";
private static final String RESOURCE_SETS = "resourceSets";
/**
* Logger for this class
*/
@ -204,7 +204,7 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
private ResourceSetRepository resourceSetRepository;
@Autowired
private PermissionRepository permissionRepository;
/* (non-Javadoc)
* @see org.mitre.openid.connect.service.MITREidDataService#export(com.google.gson.stream.JsonWriter)
*/
@ -256,38 +256,38 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
writer.beginArray();
writeSystemScopes(writer);
writer.endArray();
writer.name(SAVED_REGISTERED_CLIENTS);
writer.beginArray();
writeSavedRegisteredClients(writer);
writer.endArray();
writer.name(RESOURCE_SETS);
writer.beginArray();
writeResourceSets(writer);
writer.endArray();
writer.name(PERMISSION_TICKETS);
writer.beginArray();
writePermissionTickets(writer);
writer.endArray();
writer.endObject(); // end mitreid-connect-1.2
}
/**
* @param writer
* @throws IOException
* @throws IOException
*/
private void writePermissionTickets(JsonWriter writer) throws IOException {
for (PermissionTicket ticket : permissionRepository.getAll()) {
writer.beginObject();
writer.name(CLAIMS_SUPPLIED);
writer.beginArray();
for (Claim claim : ticket.getClaimsSupplied()) {
writer.beginObject();
writer.name(ISSUER);
writer.beginArray();
for (String issuer : claim.getIssuer()) {
@ -307,7 +307,7 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
writer.endObject();
}
writer.endArray();
writer.name(EXPIRATION).value(toUTCString(ticket.getExpiration()));
writer.name(PERMISSION);
@ -323,16 +323,16 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
writer.endObject();
writer.name(TICKET).value(ticket.getTicket());
writer.endObject();
}
}
/**
* @param writer
* @throws IOException
* @throws IOException
*/
private void writeResourceSets(JsonWriter writer) throws IOException {
for (ResourceSet rs : resourceSetRepository.getAll()) {
@ -359,7 +359,7 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
writer.beginArray();
for (Claim claim : policy.getClaimsRequired()) {
writer.beginObject();
writer.name(ISSUER);
writer.beginArray();
for (String issuer : claim.getIssuer()) {
@ -391,7 +391,7 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
writer.endObject();
logger.debug("Finished writing resource set {}", rs.getId());
}
}
/**
@ -463,7 +463,7 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
writer.endObject();
}
writer.endArray();
writer.name(TYPE).value(token.getTokenType());
writer.name(VALUE).value(token.getValue());
writer.endObject();
@ -479,7 +479,7 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
for (AuthenticationHolderEntity holder : authHolderRepository.getAll()) {
writer.beginObject();
writer.name(ID).value(holder.getId());
writer.name(REQUEST_PARAMETERS);
writer.beginObject();
for (Entry<String, String> entry : holder.getRequestParameters().entrySet()) {
@ -540,13 +540,13 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
writer.value(authority.getAuthority());
}
writer.endArray();
writer.endObject();
} else {
writer.nullValue();
}
writer.endObject();
logger.debug("Wrote authentication holder {}", holder.getId());
}
@ -791,7 +791,7 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
}
fixObjectReferences();
}
/**
* @param reader
@ -907,7 +907,7 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
private Map<Long, Long> resourceSetOldToNewIdMap = new HashMap<>();
/**
* @param reader
*/
@ -1264,8 +1264,8 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
reader.endArray();
logger.info("Done reading access tokens");
}
private Map<Long, Long> authHolderOldToNewIdMap = new HashMap<Long, Long>();
/**
@ -1337,12 +1337,12 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
/**
* @param reader
* @return
* @throws IOException
* @throws IOException
*/
private SavedUserAuthentication readSavedUserAuthentication(JsonReader reader) throws IOException {
SavedUserAuthentication savedUserAuth = new SavedUserAuthentication();
reader.beginObject();
while (reader.hasNext()) {
switch(reader.peek()) {
case END_OBJECT:
@ -1376,7 +1376,7 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
continue;
}
}
reader.endObject();
return savedUserAuth;
}
@ -1445,7 +1445,7 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
reader.endArray();
logger.info("Done reading grants");
}
private Map<Long, Long> whitelistedSiteOldToNewIdMap = new HashMap<Long, Long>();
/**
@ -1814,8 +1814,8 @@ public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements
}
permissionToResourceRefs.clear();
resourceSetOldToNewIdMap.clear();
logger.info("Done fixing object references.");
}
}

View File

@ -40,7 +40,7 @@ public class JpaPermissionRepository implements PermissionRepository {
@PersistenceContext
private EntityManager em;
@Override
@Transactional
public PermissionTicket save(PermissionTicket p) {

View File

@ -41,7 +41,7 @@ public class JpaResourceSetRepository implements ResourceSetRepository {
@PersistenceContext
private EntityManager em;
private static Logger logger = LoggerFactory.getLogger(JpaResourceSetRepository.class);
@Override
@Transactional
public ResourceSet save(ResourceSet rs) {
@ -78,7 +78,7 @@ public class JpaResourceSetRepository implements ResourceSetRepository {
query.setParameter(ResourceSet.PARAM_CLIENTID, clientId);
return query.getResultList();
}
@Override
public Collection<ResourceSet> getAll() {
TypedQuery<ResourceSet> query = em.createNamedQuery(ResourceSet.QUERY_ALL, ResourceSet.class);

Some files were not shown because too many files have changed in this diff Show More