refactor: 💡 Remove DataAPI (#22)
parent
94e7bc87a1
commit
37aea39cf6
|
@ -1,73 +0,0 @@
|
|||
/*******************************************************************************
|
||||
* Copyright 2018 The MIT Internet Trust Consortium
|
||||
*
|
||||
* Portions copyright 2011-2013 The MITRE Corporation
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*******************************************************************************/
|
||||
package org.mitre.openid.connect.service;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
|
||||
/**
|
||||
* @author jricher
|
||||
* @author arielak
|
||||
*/
|
||||
public interface MITREidDataService {
|
||||
|
||||
/**
|
||||
* Data member for 1.X configurations
|
||||
*/
|
||||
String MITREID_CONNECT_1_0 = "mitreid-connect-1.0";
|
||||
String MITREID_CONNECT_1_1 = "mitreid-connect-1.1";
|
||||
String MITREID_CONNECT_1_2 = "mitreid-connect-1.2";
|
||||
String MITREID_CONNECT_1_3 = "mitreid-connect-1.3";
|
||||
|
||||
// member names
|
||||
String REFRESHTOKENS = "refreshTokens";
|
||||
String ACCESSTOKENS = "accessTokens";
|
||||
String WHITELISTEDSITES = "whitelistedSites";
|
||||
String BLACKLISTEDSITES = "blacklistedSites";
|
||||
String AUTHENTICATIONHOLDERS = "authenticationHolders";
|
||||
String GRANTS = "grants";
|
||||
String CLIENTS = "clients";
|
||||
String SYSTEMSCOPES = "systemScopes";
|
||||
|
||||
/**
|
||||
* Write out the current server state to the given JSON writer as a JSON object
|
||||
*
|
||||
* @param writer
|
||||
* @throws IOException
|
||||
*/
|
||||
void exportData(JsonWriter writer) throws IOException;
|
||||
|
||||
/**
|
||||
* Read in the current server state from the given JSON reader as a JSON object
|
||||
*
|
||||
* @param reader
|
||||
*/
|
||||
void importData(JsonReader reader) throws IOException;
|
||||
|
||||
/**
|
||||
* Return true if the this data service supports the given version. This is called before
|
||||
* handing the service the reader through its importData function.
|
||||
*
|
||||
* @param version
|
||||
* @return
|
||||
*/
|
||||
boolean supportsVersion(String version);
|
||||
|
||||
}
|
|
@ -1,67 +0,0 @@
|
|||
/*******************************************************************************
|
||||
* Copyright 2018 The MIT Internet Trust Consortium
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.mitre.openid.connect.service;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
|
||||
/**
|
||||
* A modular extension to the data import/export layer. Any instances of this need to be
|
||||
* declared as beans to be picked up by the data services.
|
||||
*
|
||||
* @author jricher
|
||||
*
|
||||
*/
|
||||
public interface MITREidDataServiceExtension {
|
||||
|
||||
/**
|
||||
* Export any data for this extension. This is called from the top level object.
|
||||
* All extensions MUST return the writer to a state such that another member of
|
||||
* the top level object can be written next.
|
||||
*
|
||||
* @param writer
|
||||
*/
|
||||
void exportExtensionData(JsonWriter writer) throws IOException;
|
||||
|
||||
/**
|
||||
* Import data that's part of this extension. This is called from the context of
|
||||
* reading the top level object. All extensions MUST return the reader to a state
|
||||
* such that another member of the top level object can be read next. The name of
|
||||
* the data element being imported is passed in as name. If the extension does not
|
||||
* support this data element, it must return without advancing the reader.
|
||||
*
|
||||
* Returns "true" if the item was processed, "false" otherwise.
|
||||
*
|
||||
* @param reader
|
||||
*/
|
||||
boolean importExtensionData(String name, JsonReader reader) throws IOException;
|
||||
|
||||
/**
|
||||
* Signal the extension to wrap up all object processing and finalize its
|
||||
*/
|
||||
void fixExtensionObjectReferences(MITREidDataServiceMaps maps);
|
||||
|
||||
/**
|
||||
* Return
|
||||
* @param mitreidConnect13
|
||||
* @return
|
||||
*/
|
||||
boolean supportsVersion(String version);
|
||||
|
||||
}
|
|
@ -1,95 +0,0 @@
|
|||
/*******************************************************************************
|
||||
* Copyright 2018 The MIT Internet Trust Consortium
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*******************************************************************************/
|
||||
|
||||
package org.mitre.openid.connect.service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author jricher
|
||||
*/
|
||||
public class MITREidDataServiceMaps {
|
||||
|
||||
private Map<Long, Long> accessTokenOldToNewIdMap = new HashMap<>();
|
||||
private Map<Long, Long> accessTokenToAuthHolderRefs = new HashMap<>();
|
||||
private Map<Long, String> accessTokenToClientRefs = new HashMap<>();
|
||||
private Map<Long, Long> accessTokenToRefreshTokenRefs = new HashMap<>();
|
||||
private Map<Long, Long> authHolderOldToNewIdMap = new HashMap<>();
|
||||
private Map<Long, Long> grantOldToNewIdMap = new HashMap<>();
|
||||
private Map<Long, Set<Long>> grantToAccessTokensRefs = new HashMap<>();
|
||||
private Map<Long, Long> refreshTokenOldToNewIdMap = new HashMap<>();
|
||||
private Map<Long, Long> refreshTokenToAuthHolderRefs = new HashMap<>();
|
||||
private Map<Long, String> refreshTokenToClientRefs = new HashMap<>();
|
||||
private Map<Long, Long> whitelistedSiteOldToNewIdMap = new HashMap<>();
|
||||
|
||||
public Map<Long, Long> getAccessTokenOldToNewIdMap() {
|
||||
return accessTokenOldToNewIdMap;
|
||||
}
|
||||
|
||||
public Map<Long, Long> getAccessTokenToAuthHolderRefs() {
|
||||
return accessTokenToAuthHolderRefs;
|
||||
}
|
||||
|
||||
public Map<Long, String> getAccessTokenToClientRefs() {
|
||||
return accessTokenToClientRefs;
|
||||
}
|
||||
|
||||
public Map<Long, Long> getAccessTokenToRefreshTokenRefs() {
|
||||
return accessTokenToRefreshTokenRefs;
|
||||
}
|
||||
|
||||
public Map<Long, Long> getAuthHolderOldToNewIdMap() {
|
||||
return authHolderOldToNewIdMap;
|
||||
}
|
||||
|
||||
public Map<Long, Long> getGrantOldToNewIdMap() {
|
||||
return grantOldToNewIdMap;
|
||||
}
|
||||
|
||||
public Map<Long, Set<Long>> getGrantToAccessTokensRefs() {
|
||||
return grantToAccessTokensRefs;
|
||||
}
|
||||
|
||||
public Map<Long, Long> getRefreshTokenOldToNewIdMap() {
|
||||
return refreshTokenOldToNewIdMap;
|
||||
}
|
||||
|
||||
public Map<Long, Long> getRefreshTokenToAuthHolderRefs() {
|
||||
return refreshTokenToAuthHolderRefs;
|
||||
}
|
||||
|
||||
public Map<Long, String> getRefreshTokenToClientRefs() {
|
||||
return refreshTokenToClientRefs;
|
||||
}
|
||||
|
||||
public Map<Long, Long> getWhitelistedSiteOldToNewIdMap() {
|
||||
return whitelistedSiteOldToNewIdMap;
|
||||
}
|
||||
|
||||
public void clearAll() {
|
||||
refreshTokenToClientRefs.clear();
|
||||
refreshTokenToAuthHolderRefs.clear();
|
||||
accessTokenToClientRefs.clear();
|
||||
accessTokenToAuthHolderRefs.clear();
|
||||
accessTokenToRefreshTokenRefs.clear();
|
||||
refreshTokenOldToNewIdMap.clear();
|
||||
accessTokenOldToNewIdMap.clear();
|
||||
grantOldToNewIdMap.clear();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,58 +0,0 @@
|
|||
/*******************************************************************************
|
||||
* Copyright 2018 The MIT Internet Trust Consortium
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*******************************************************************************/
|
||||
package org.mitre.openid.connect.service.impl;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.format.annotation.DateTimeFormat.ISO;
|
||||
import org.springframework.format.datetime.DateFormatter;
|
||||
|
||||
public abstract class MITREidDataServiceSupport {
|
||||
private final DateFormatter dateFormatter;
|
||||
/**
|
||||
* Logger for this class
|
||||
*/
|
||||
private static final Logger logger = LoggerFactory.getLogger(MITREidDataServiceSupport.class);
|
||||
|
||||
public MITREidDataServiceSupport() {
|
||||
dateFormatter = new DateFormatter();
|
||||
dateFormatter.setIso(ISO.DATE_TIME);
|
||||
}
|
||||
|
||||
protected Date utcToDate(String value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return dateFormatter.parse(value, Locale.ENGLISH);
|
||||
} catch (ParseException ex) {
|
||||
logger.error("Unable to parse datetime {}", value, ex);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected String toUTCString(Date value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return dateFormatter.print(value, Locale.ENGLISH);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,906 +0,0 @@
|
|||
/*******************************************************************************
|
||||
* Copyright 2018 The MIT Internet Trust Consortium
|
||||
*
|
||||
* Portions copyright 2011-2013 The MITRE Corporation
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*******************************************************************************/
|
||||
package org.mitre.openid.connect.service.impl;
|
||||
|
||||
import static org.mitre.util.JsonUtils.readMap;
|
||||
import static org.mitre.util.JsonUtils.readSet;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.ParseException;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.mitre.oauth2.model.AuthenticationHolderEntity;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity.AppType;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity.AuthMethod;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity.SubjectType;
|
||||
import org.mitre.oauth2.model.OAuth2AccessTokenEntity;
|
||||
import org.mitre.oauth2.model.OAuth2RefreshTokenEntity;
|
||||
import org.mitre.oauth2.model.SavedUserAuthentication;
|
||||
import org.mitre.oauth2.model.SystemScope;
|
||||
import org.mitre.oauth2.repository.AuthenticationHolderRepository;
|
||||
import org.mitre.oauth2.repository.OAuth2ClientRepository;
|
||||
import org.mitre.oauth2.repository.OAuth2TokenRepository;
|
||||
import org.mitre.oauth2.repository.SystemScopeRepository;
|
||||
import org.mitre.openid.connect.model.ApprovedSite;
|
||||
import org.mitre.openid.connect.model.BlacklistedSite;
|
||||
import org.mitre.openid.connect.model.WhitelistedSite;
|
||||
import org.mitre.openid.connect.repository.ApprovedSiteRepository;
|
||||
import org.mitre.openid.connect.repository.BlacklistedSiteRepository;
|
||||
import org.mitre.openid.connect.repository.WhitelistedSiteRepository;
|
||||
import org.mitre.openid.connect.service.MITREidDataService;
|
||||
import org.mitre.openid.connect.service.MITREidDataServiceExtension;
|
||||
import org.mitre.openid.connect.service.MITREidDataServiceMaps;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Request;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonToken;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
import com.nimbusds.jose.EncryptionMethod;
|
||||
import com.nimbusds.jose.JWEAlgorithm;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jwt.JWTParser;
|
||||
/**
|
||||
*
|
||||
* Data service to import MITREid 1.0 configuration.
|
||||
*
|
||||
* @author jricher
|
||||
* @author arielak
|
||||
*/
|
||||
@Service
|
||||
@SuppressWarnings(value = {"unchecked"})
|
||||
public class MITREidDataService_1_0 extends MITREidDataServiceSupport implements MITREidDataService {
|
||||
|
||||
/**
|
||||
* Logger for this class
|
||||
*/
|
||||
private static final Logger logger = LoggerFactory.getLogger(MITREidDataService_1_0.class);
|
||||
@Autowired
|
||||
private OAuth2ClientRepository clientRepository;
|
||||
@Autowired
|
||||
private ApprovedSiteRepository approvedSiteRepository;
|
||||
@Autowired
|
||||
private WhitelistedSiteRepository wlSiteRepository;
|
||||
@Autowired
|
||||
private BlacklistedSiteRepository blSiteRepository;
|
||||
@Autowired
|
||||
private AuthenticationHolderRepository authHolderRepository;
|
||||
@Autowired
|
||||
private OAuth2TokenRepository tokenRepository;
|
||||
@Autowired
|
||||
private SystemScopeRepository sysScopeRepository;
|
||||
@Autowired(required = false)
|
||||
private List<MITREidDataServiceExtension> extensions = Collections.emptyList();
|
||||
|
||||
private MITREidDataServiceMaps maps = new MITREidDataServiceMaps();
|
||||
|
||||
private static final String THIS_VERSION = MITREID_CONNECT_1_0;
|
||||
|
||||
@Override
|
||||
public boolean supportsVersion(String version) {
|
||||
return THIS_VERSION.equals(version);
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.mitre.openid.connect.service.MITREidDataService#export(com.google.gson.stream.JsonWriter)
|
||||
*/
|
||||
|
||||
@Override
|
||||
public void exportData(JsonWriter writer) throws IOException {
|
||||
throw new UnsupportedOperationException("Can not export 1.0 format from this version.");
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.mitre.openid.connect.service.MITREidDataService#importData(com.google.gson.stream.JsonReader)
|
||||
*/
|
||||
@Override
|
||||
public void importData(JsonReader reader) throws IOException {
|
||||
|
||||
logger.info("Reading configuration for 1.0");
|
||||
|
||||
// this *HAS* to start as an object
|
||||
reader.beginObject();
|
||||
|
||||
while (reader.hasNext()) {
|
||||
JsonToken tok = reader.peek();
|
||||
switch (tok) {
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
// find out which member it is
|
||||
if (name.equals(CLIENTS)) {
|
||||
readClients(reader);
|
||||
} else if (name.equals(GRANTS)) {
|
||||
readGrants(reader);
|
||||
} else if (name.equals(WHITELISTEDSITES)) {
|
||||
readWhitelistedSites(reader);
|
||||
} else if (name.equals(BLACKLISTEDSITES)) {
|
||||
readBlacklistedSites(reader);
|
||||
} else if (name.equals(AUTHENTICATIONHOLDERS)) {
|
||||
readAuthenticationHolders(reader);
|
||||
} else if (name.equals(ACCESSTOKENS)) {
|
||||
readAccessTokens(reader);
|
||||
} else if (name.equals(REFRESHTOKENS)) {
|
||||
readRefreshTokens(reader);
|
||||
} else if (name.equals(SYSTEMSCOPES)) {
|
||||
readSystemScopes(reader);
|
||||
} else {
|
||||
for (MITREidDataServiceExtension extension : extensions) {
|
||||
if (extension.supportsVersion(THIS_VERSION)) {
|
||||
if (extension.supportsVersion(THIS_VERSION)) {
|
||||
extension.importExtensionData(name, reader);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// unknown token, skip it
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
case END_OBJECT:
|
||||
// the object ended, we're done here
|
||||
reader.endObject();
|
||||
continue;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue; }
|
||||
}
|
||||
fixObjectReferences();
|
||||
for (MITREidDataServiceExtension extension : extensions) {
|
||||
if (extension.supportsVersion(THIS_VERSION)) {
|
||||
extension.fixExtensionObjectReferences(maps);
|
||||
break;
|
||||
}
|
||||
}
|
||||
maps.clearAll();
|
||||
}
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readRefreshTokens(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
OAuth2RefreshTokenEntity token = new OAuth2RefreshTokenEntity();
|
||||
reader.beginObject();
|
||||
Long currentId = null;
|
||||
String clientId = null;
|
||||
Long authHolderId = null;
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("id")) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals("expiration")) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
token.setExpiration(date);
|
||||
} else if (name.equals("value")) {
|
||||
String value = reader.nextString();
|
||||
try {
|
||||
token.setJwt(JWTParser.parse(value));
|
||||
} catch (ParseException ex) {
|
||||
logger.error("Unable to set refresh token value to {}", value, ex);
|
||||
}
|
||||
} else if (name.equals("clientId")) {
|
||||
clientId = reader.nextString();
|
||||
} else if (name.equals("authenticationHolderId")) {
|
||||
authHolderId = reader.nextLong();
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = tokenRepository.saveRefreshToken(token).getId();
|
||||
maps.getRefreshTokenToClientRefs().put(currentId, clientId);
|
||||
maps.getRefreshTokenToAuthHolderRefs().put(currentId, authHolderId);
|
||||
maps.getRefreshTokenOldToNewIdMap().put(currentId, newId);
|
||||
logger.debug("Read refresh token {}", currentId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading refresh tokens");
|
||||
}
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readAccessTokens(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();
|
||||
reader.beginObject();
|
||||
Long currentId = null;
|
||||
String clientId = null;
|
||||
Long authHolderId = null;
|
||||
Long refreshTokenId = null;
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("id")) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals("expiration")) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
token.setExpiration(date);
|
||||
} else if (name.equals("value")) {
|
||||
String value = reader.nextString();
|
||||
try {
|
||||
// all tokens are JWTs
|
||||
token.setJwt(JWTParser.parse(value));
|
||||
} catch (ParseException ex) {
|
||||
logger.error("Unable to set refresh token value to {}", value, ex);
|
||||
}
|
||||
} else if (name.equals("clientId")) {
|
||||
clientId = reader.nextString();
|
||||
} else if (name.equals("authenticationHolderId")) {
|
||||
authHolderId = reader.nextLong();
|
||||
} else if (name.equals("refreshTokenId")) {
|
||||
refreshTokenId = reader.nextLong();
|
||||
} else if (name.equals("scope")) {
|
||||
Set<String> scope = readSet(reader);
|
||||
token.setScope(scope);
|
||||
} else if (name.equals("type")) {
|
||||
token.setTokenType(reader.nextString());
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = tokenRepository.saveAccessToken(token).getId();
|
||||
maps.getAccessTokenToClientRefs().put(currentId, clientId);
|
||||
maps.getAccessTokenToAuthHolderRefs().put(currentId, authHolderId);
|
||||
if (refreshTokenId != null) {
|
||||
maps.getAccessTokenToRefreshTokenRefs().put(currentId, refreshTokenId);
|
||||
}
|
||||
maps.getAccessTokenOldToNewIdMap().put(currentId, newId);
|
||||
logger.debug("Read access token {}", currentId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading access tokens");
|
||||
}
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readAuthenticationHolders(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
AuthenticationHolderEntity ahe = new AuthenticationHolderEntity();
|
||||
reader.beginObject();
|
||||
Long currentId = null;
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("id")) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals("ownerId")) {
|
||||
//not needed
|
||||
reader.skipValue();
|
||||
} else if (name.equals("authentication")) {
|
||||
OAuth2Request clientAuthorization = null;
|
||||
Authentication userAuthentication = null;
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String subName = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (subName.equals("clientAuthorization")) {
|
||||
clientAuthorization = readAuthorizationRequest(reader);
|
||||
} 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();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
OAuth2Authentication auth = new OAuth2Authentication(clientAuthorization, userAuthentication);
|
||||
ahe.setAuthentication(auth);
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = authHolderRepository.save(ahe).getId();
|
||||
maps.getAuthHolderOldToNewIdMap().put(currentId, newId);
|
||||
logger.debug("Read authentication holder {}", currentId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading authentication holders");
|
||||
}
|
||||
|
||||
//used by readAuthenticationHolders
|
||||
private OAuth2Request readAuthorizationRequest(JsonReader reader) throws IOException {
|
||||
Set<String> scope = new LinkedHashSet<>();
|
||||
Set<String> resourceIds = new HashSet<>();
|
||||
boolean approved = false;
|
||||
Collection<GrantedAuthority> authorities = new HashSet<>();
|
||||
Map<String, String> authorizationParameters = new HashMap<>();
|
||||
Set<String> responseTypes = new HashSet<>();
|
||||
String redirectUri = null;
|
||||
String clientId = null;
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("authorizationParameters")) {
|
||||
authorizationParameters = readMap(reader);
|
||||
} else if (name.equals("approvalParameters")) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("clientId")) {
|
||||
clientId = reader.nextString();
|
||||
} else if (name.equals("scope")) {
|
||||
scope = readSet(reader);
|
||||
} else if (name.equals("resourceIds")) {
|
||||
resourceIds = readSet(reader);
|
||||
} else if (name.equals("authorities")) {
|
||||
Set<String> authorityStrs = readSet(reader);
|
||||
authorities = new HashSet<>();
|
||||
for (String s : authorityStrs) {
|
||||
GrantedAuthority ga = new SimpleGrantedAuthority(s);
|
||||
authorities.add(ga);
|
||||
}
|
||||
} else if (name.equals("approved")) {
|
||||
approved = reader.nextBoolean();
|
||||
} else if (name.equals("denied")) {
|
||||
if (approved == false) {
|
||||
approved = !reader.nextBoolean();
|
||||
}
|
||||
} else if (name.equals("redirectUri")) {
|
||||
redirectUri = reader.nextString();
|
||||
} else if (name.equals("responseTypes")) {
|
||||
responseTypes = readSet(reader);
|
||||
} else {
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
return new OAuth2Request(authorizationParameters, clientId, authorities, approved, scope, resourceIds, redirectUri, responseTypes, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param reader
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
private SavedUserAuthentication readSavedUserAuthentication(JsonReader reader) throws IOException {
|
||||
SavedUserAuthentication savedUserAuth = new SavedUserAuthentication();
|
||||
reader.beginObject();
|
||||
|
||||
while (reader.hasNext()) {
|
||||
switch(reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("name")) {
|
||||
savedUserAuth.setName(reader.nextString());
|
||||
} else if (name.equals("sourceClass")) {
|
||||
savedUserAuth.setSourceClass(reader.nextString());
|
||||
} else if (name.equals("authenticated")) {
|
||||
savedUserAuth.setAuthenticated(reader.nextBoolean());
|
||||
} else if (name.equals("authorities")) {
|
||||
Set<String> authorityStrs = readSet(reader);
|
||||
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
|
||||
for (String s : authorityStrs) {
|
||||
GrantedAuthority ga = new SimpleGrantedAuthority(s);
|
||||
authorities.add(ga);
|
||||
}
|
||||
savedUserAuth.setAuthorities(authorities);
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
reader.endObject();
|
||||
return savedUserAuth;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readGrants(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
ApprovedSite site = new ApprovedSite();
|
||||
Long currentId = null;
|
||||
Long whitelistedSiteId = null;
|
||||
Set<Long> tokenIds = null;
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("id")) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals("accessDate")) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
site.setAccessDate(date);
|
||||
} else if (name.equals("clientId")) {
|
||||
site.setClientId(reader.nextString());
|
||||
} else if (name.equals("creationDate")) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
site.setCreationDate(date);
|
||||
} else if (name.equals("timeoutDate")) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
site.setTimeoutDate(date);
|
||||
} else if (name.equals("userId")) {
|
||||
site.setUserId(reader.nextString());
|
||||
} else if (name.equals("allowedScopes")) {
|
||||
Set<String> allowedScopes = readSet(reader);
|
||||
site.setAllowedScopes(allowedScopes);
|
||||
} else if (name.equals("whitelistedSiteId")) {
|
||||
whitelistedSiteId = reader.nextLong();
|
||||
} else if (name.equals("approvedAccessTokens")) {
|
||||
tokenIds = readSet(reader);
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = approvedSiteRepository.save(site).getId();
|
||||
maps.getGrantOldToNewIdMap().put(currentId, newId);
|
||||
if (whitelistedSiteId != null) {
|
||||
logger.debug("Ignoring whitelisted site marker on approved site.");
|
||||
}
|
||||
if (tokenIds != null) {
|
||||
maps.getGrantToAccessTokensRefs().put(currentId, tokenIds);
|
||||
}
|
||||
logger.debug("Read grant {}", currentId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading grants");
|
||||
}
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readWhitelistedSites(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
WhitelistedSite wlSite = new WhitelistedSite();
|
||||
Long currentId = null;
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (name.equals("id")) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals("clientId")) {
|
||||
wlSite.setClientId(reader.nextString());
|
||||
} else if (name.equals("creatorUserId")) {
|
||||
wlSite.setCreatorUserId(reader.nextString());
|
||||
} else if (name.equals("allowedScopes")) {
|
||||
Set<String> allowedScopes = readSet(reader);
|
||||
wlSite.setAllowedScopes(allowedScopes);
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = wlSiteRepository.save(wlSite).getId();
|
||||
maps.getWhitelistedSiteOldToNewIdMap().put(currentId, newId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading whitelisted sites");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readBlacklistedSites(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
BlacklistedSite blSite = new BlacklistedSite();
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (name.equals("id")) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("uri")) {
|
||||
blSite.setUri(reader.nextString());
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
blSiteRepository.save(blSite);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading blacklisted sites");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readClients(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
ClientDetailsEntity client = new ClientDetailsEntity();
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("clientId")) {
|
||||
client.setClientId(reader.nextString());
|
||||
} else if (name.equals("resourceIds")) {
|
||||
Set<String> resourceIds = readSet(reader);
|
||||
client.setResourceIds(resourceIds);
|
||||
} else if (name.equals("secret")) {
|
||||
client.setClientSecret(reader.nextString());
|
||||
} else if (name.equals("scope")) {
|
||||
Set<String> scope = readSet(reader);
|
||||
client.setScope(scope);
|
||||
} else if (name.equals("authorities")) {
|
||||
Set<String> authorityStrs = readSet(reader);
|
||||
Set<GrantedAuthority> authorities = new HashSet<>();
|
||||
for (String s : authorityStrs) {
|
||||
GrantedAuthority ga = new SimpleGrantedAuthority(s);
|
||||
authorities.add(ga);
|
||||
}
|
||||
client.setAuthorities(authorities);
|
||||
} else if (name.equals("accessTokenValiditySeconds")) {
|
||||
client.setAccessTokenValiditySeconds(reader.nextInt());
|
||||
} else if (name.equals("refreshTokenValiditySeconds")) {
|
||||
client.setRefreshTokenValiditySeconds(reader.nextInt());
|
||||
} else if (name.equals("redirectUris")) {
|
||||
Set<String> redirectUris = readSet(reader);
|
||||
client.setRedirectUris(redirectUris);
|
||||
} else if (name.equals("name")) {
|
||||
client.setClientName(reader.nextString());
|
||||
} else if (name.equals("uri")) {
|
||||
client.setClientUri(reader.nextString());
|
||||
} else if (name.equals("logoUri")) {
|
||||
client.setLogoUri(reader.nextString());
|
||||
} else if (name.equals("contacts")) {
|
||||
Set<String> contacts = readSet(reader);
|
||||
client.setContacts(contacts);
|
||||
} else if (name.equals("tosUri")) {
|
||||
client.setTosUri(reader.nextString());
|
||||
} else if (name.equals("tokenEndpointAuthMethod")) {
|
||||
AuthMethod am = AuthMethod.getByValue(reader.nextString());
|
||||
client.setTokenEndpointAuthMethod(am);
|
||||
} else if (name.equals("grantTypes")) {
|
||||
Set<String> grantTypes = readSet(reader);
|
||||
client.setGrantTypes(grantTypes);
|
||||
} else if (name.equals("responseTypes")) {
|
||||
Set<String> responseTypes = readSet(reader);
|
||||
client.setResponseTypes(responseTypes);
|
||||
} else if (name.equals("policyUri")) {
|
||||
client.setPolicyUri(reader.nextString());
|
||||
} else if (name.equals("applicationType")) {
|
||||
AppType appType = AppType.getByValue(reader.nextString());
|
||||
client.setApplicationType(appType);
|
||||
} else if (name.equals("sectorIdentifierUri")) {
|
||||
client.setSectorIdentifierUri(reader.nextString());
|
||||
} else if (name.equals("subjectType")) {
|
||||
SubjectType st = SubjectType.getByValue(reader.nextString());
|
||||
client.setSubjectType(st);
|
||||
} else if (name.equals("jwks_uri")) {
|
||||
client.setJwksUri(reader.nextString());
|
||||
} else if (name.equals("requestObjectSigningAlg")) {
|
||||
JWSAlgorithm alg = JWSAlgorithm.parse(reader.nextString());
|
||||
client.setRequestObjectSigningAlg(alg);
|
||||
} else if (name.equals("userInfoEncryptedResponseAlg")) {
|
||||
JWEAlgorithm alg = JWEAlgorithm.parse(reader.nextString());
|
||||
client.setUserInfoEncryptedResponseAlg(alg);
|
||||
} else if (name.equals("userInfoEncryptedResponseEnc")) {
|
||||
EncryptionMethod alg = EncryptionMethod.parse(reader.nextString());
|
||||
client.setUserInfoEncryptedResponseEnc(alg);
|
||||
} else if (name.equals("userInfoSignedResponseAlg")) {
|
||||
JWSAlgorithm alg = JWSAlgorithm.parse(reader.nextString());
|
||||
client.setUserInfoSignedResponseAlg(alg);
|
||||
} else if (name.equals("idTokenSignedResonseAlg")) {
|
||||
JWSAlgorithm alg = JWSAlgorithm.parse(reader.nextString());
|
||||
client.setIdTokenSignedResponseAlg(alg);
|
||||
} else if (name.equals("idTokenEncryptedResponseAlg")) {
|
||||
JWEAlgorithm alg = JWEAlgorithm.parse(reader.nextString());
|
||||
client.setIdTokenEncryptedResponseAlg(alg);
|
||||
} else if (name.equals("idTokenEncryptedResponseEnc")) {
|
||||
EncryptionMethod alg = EncryptionMethod.parse(reader.nextString());
|
||||
client.setIdTokenEncryptedResponseEnc(alg);
|
||||
} else if (name.equals("tokenEndpointAuthSigningAlg")) {
|
||||
JWSAlgorithm alg = JWSAlgorithm.parse(reader.nextString());
|
||||
client.setTokenEndpointAuthSigningAlg(alg);
|
||||
} else if (name.equals("defaultMaxAge")) {
|
||||
client.setDefaultMaxAge(reader.nextInt());
|
||||
} else if (name.equals("requireAuthTime")) {
|
||||
client.setRequireAuthTime(reader.nextBoolean());
|
||||
} else if (name.equals("defaultACRValues")) {
|
||||
Set<String> defaultACRvalues = readSet(reader);
|
||||
client.setDefaultACRvalues(defaultACRvalues);
|
||||
} else if (name.equals("initiateLoginUri")) {
|
||||
client.setInitiateLoginUri(reader.nextString());
|
||||
} else if (name.equals("postLogoutRedirectUri")) {
|
||||
HashSet<String> postLogoutUris = Sets.newHashSet(reader.nextString());
|
||||
client.setPostLogoutRedirectUris(postLogoutUris);
|
||||
} else if (name.equals("requestUris")) {
|
||||
Set<String> requestUris = readSet(reader);
|
||||
client.setRequestUris(requestUris);
|
||||
} else if (name.equals("description")) {
|
||||
client.setClientDescription(reader.nextString());
|
||||
} else if (name.equals("allowIntrospection")) {
|
||||
client.setAllowIntrospection(reader.nextBoolean());
|
||||
} else if (name.equals("reuseRefreshToken")) {
|
||||
client.setReuseRefreshToken(reader.nextBoolean());
|
||||
} else if (name.equals("dynamicallyRegistered")) {
|
||||
client.setDynamicallyRegistered(reader.nextBoolean());
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
clientRepository.saveClient(client);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading clients");
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the list of system scopes from the reader and insert them into the
|
||||
* scope repository.
|
||||
*
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readSystemScopes(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
SystemScope scope = new SystemScope();
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("value")) {
|
||||
scope.setValue(reader.nextString());
|
||||
} else if (name.equals("description")) {
|
||||
scope.setDescription(reader.nextString());
|
||||
} else if (name.equals("allowDynReg")) {
|
||||
// previously "allowDynReg" scopes are now tagged as "not restricted" and vice versa
|
||||
scope.setRestricted(!reader.nextBoolean());
|
||||
} else if (name.equals("defaultScope")) {
|
||||
scope.setDefaultScope(reader.nextBoolean());
|
||||
} else if (name.equals("icon")) {
|
||||
scope.setIcon(reader.nextString());
|
||||
} else {
|
||||
logger.debug("found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
sysScopeRepository.save(scope);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading system scopes");
|
||||
}
|
||||
|
||||
private void fixObjectReferences() {
|
||||
for (Long oldRefreshTokenId : maps.getRefreshTokenToClientRefs().keySet()) {
|
||||
String clientRef = maps.getRefreshTokenToClientRefs().get(oldRefreshTokenId);
|
||||
ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef);
|
||||
Long newRefreshTokenId = maps.getRefreshTokenOldToNewIdMap().get(oldRefreshTokenId);
|
||||
OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId);
|
||||
refreshToken.setClient(client);
|
||||
tokenRepository.saveRefreshToken(refreshToken);
|
||||
}
|
||||
for (Long oldRefreshTokenId : maps.getRefreshTokenToAuthHolderRefs().keySet()) {
|
||||
Long oldAuthHolderId = maps.getRefreshTokenToAuthHolderRefs().get(oldRefreshTokenId);
|
||||
Long newAuthHolderId = maps.getAuthHolderOldToNewIdMap().get(oldAuthHolderId);
|
||||
AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId);
|
||||
Long newRefreshTokenId = maps.getRefreshTokenOldToNewIdMap().get(oldRefreshTokenId);
|
||||
OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId);
|
||||
refreshToken.setAuthenticationHolder(authHolder);
|
||||
tokenRepository.saveRefreshToken(refreshToken);
|
||||
}
|
||||
for (Long oldAccessTokenId : maps.getAccessTokenToClientRefs().keySet()) {
|
||||
String clientRef = maps.getAccessTokenToClientRefs().get(oldAccessTokenId);
|
||||
ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef);
|
||||
Long newAccessTokenId = maps.getAccessTokenOldToNewIdMap().get(oldAccessTokenId);
|
||||
OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId);
|
||||
accessToken.setClient(client);
|
||||
tokenRepository.saveAccessToken(accessToken);
|
||||
}
|
||||
for (Long oldAccessTokenId : maps.getAccessTokenToAuthHolderRefs().keySet()) {
|
||||
Long oldAuthHolderId = maps.getAccessTokenToAuthHolderRefs().get(oldAccessTokenId);
|
||||
Long newAuthHolderId = maps.getAuthHolderOldToNewIdMap().get(oldAuthHolderId);
|
||||
AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId);
|
||||
Long newAccessTokenId = maps.getAccessTokenOldToNewIdMap().get(oldAccessTokenId);
|
||||
OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId);
|
||||
accessToken.setAuthenticationHolder(authHolder);
|
||||
tokenRepository.saveAccessToken(accessToken);
|
||||
}
|
||||
maps.getAccessTokenToAuthHolderRefs().clear();
|
||||
for (Long oldAccessTokenId : maps.getAccessTokenToRefreshTokenRefs().keySet()) {
|
||||
Long oldRefreshTokenId = maps.getAccessTokenToRefreshTokenRefs().get(oldAccessTokenId);
|
||||
Long newRefreshTokenId = maps.getRefreshTokenOldToNewIdMap().get(oldRefreshTokenId);
|
||||
OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId);
|
||||
Long newAccessTokenId = maps.getAccessTokenOldToNewIdMap().get(oldAccessTokenId);
|
||||
OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId);
|
||||
accessToken.setRefreshToken(refreshToken);
|
||||
tokenRepository.saveAccessToken(accessToken);
|
||||
}
|
||||
for (Long oldGrantId : maps.getGrantToAccessTokensRefs().keySet()) {
|
||||
Set<Long> oldAccessTokenIds = maps.getGrantToAccessTokensRefs().get(oldGrantId);
|
||||
|
||||
Long newGrantId = maps.getGrantOldToNewIdMap().get(oldGrantId);
|
||||
ApprovedSite site = approvedSiteRepository.getById(newGrantId);
|
||||
|
||||
for(Long oldTokenId : oldAccessTokenIds) {
|
||||
Long newTokenId = maps.getAccessTokenOldToNewIdMap().get(oldTokenId);
|
||||
OAuth2AccessTokenEntity token = tokenRepository.getAccessTokenById(newTokenId);
|
||||
token.setApprovedSite(site);
|
||||
tokenRepository.saveAccessToken(token);
|
||||
}
|
||||
|
||||
approvedSiteRepository.save(site);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,920 +0,0 @@
|
|||
/*******************************************************************************
|
||||
* Copyright 2018 The MIT Internet Trust Consortium
|
||||
*
|
||||
* Portions copyright 2011-2013 The MITRE Corporation
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*******************************************************************************/
|
||||
package org.mitre.openid.connect.service.impl;
|
||||
|
||||
import static org.mitre.util.JsonUtils.readMap;
|
||||
import static org.mitre.util.JsonUtils.readSet;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.text.ParseException;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
import org.mitre.oauth2.model.AuthenticationHolderEntity;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity.AppType;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity.AuthMethod;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity.SubjectType;
|
||||
import org.mitre.oauth2.model.OAuth2AccessTokenEntity;
|
||||
import org.mitre.oauth2.model.OAuth2RefreshTokenEntity;
|
||||
import org.mitre.oauth2.model.SavedUserAuthentication;
|
||||
import org.mitre.oauth2.model.SystemScope;
|
||||
import org.mitre.oauth2.repository.AuthenticationHolderRepository;
|
||||
import org.mitre.oauth2.repository.OAuth2ClientRepository;
|
||||
import org.mitre.oauth2.repository.OAuth2TokenRepository;
|
||||
import org.mitre.oauth2.repository.SystemScopeRepository;
|
||||
import org.mitre.openid.connect.model.ApprovedSite;
|
||||
import org.mitre.openid.connect.model.BlacklistedSite;
|
||||
import org.mitre.openid.connect.model.WhitelistedSite;
|
||||
import org.mitre.openid.connect.repository.ApprovedSiteRepository;
|
||||
import org.mitre.openid.connect.repository.BlacklistedSiteRepository;
|
||||
import org.mitre.openid.connect.repository.WhitelistedSiteRepository;
|
||||
import org.mitre.openid.connect.service.MITREidDataService;
|
||||
import org.mitre.openid.connect.service.MITREidDataServiceExtension;
|
||||
import org.mitre.openid.connect.service.MITREidDataServiceMaps;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Request;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.google.common.collect.Sets;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonToken;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
import com.nimbusds.jose.EncryptionMethod;
|
||||
import com.nimbusds.jose.JWEAlgorithm;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jwt.JWTParser;
|
||||
|
||||
/**
|
||||
*
|
||||
* Data service to import MITREid 1.1 configuration.
|
||||
*
|
||||
* @author jricher
|
||||
* @author arielak
|
||||
*/
|
||||
@Service
|
||||
@SuppressWarnings(value = {"unchecked"})
|
||||
public class MITREidDataService_1_1 extends MITREidDataServiceSupport implements MITREidDataService {
|
||||
|
||||
/**
|
||||
* Logger for this class
|
||||
*/
|
||||
private static final Logger logger = LoggerFactory.getLogger(MITREidDataService_1_1.class);
|
||||
@Autowired
|
||||
private OAuth2ClientRepository clientRepository;
|
||||
@Autowired
|
||||
private ApprovedSiteRepository approvedSiteRepository;
|
||||
@Autowired
|
||||
private WhitelistedSiteRepository wlSiteRepository;
|
||||
@Autowired
|
||||
private BlacklistedSiteRepository blSiteRepository;
|
||||
@Autowired
|
||||
private AuthenticationHolderRepository authHolderRepository;
|
||||
@Autowired
|
||||
private OAuth2TokenRepository tokenRepository;
|
||||
@Autowired
|
||||
private SystemScopeRepository sysScopeRepository;
|
||||
@Autowired(required = false)
|
||||
private List<MITREidDataServiceExtension> extensions = Collections.emptyList();
|
||||
|
||||
private static final String THIS_VERSION = MITREID_CONNECT_1_1;
|
||||
|
||||
private MITREidDataServiceMaps maps = new MITREidDataServiceMaps();
|
||||
|
||||
@Override
|
||||
public boolean supportsVersion(String version) {
|
||||
return THIS_VERSION.equals(version);
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.mitre.openid.connect.service.MITREidDataService#export(com.google.gson.stream.JsonWriter)
|
||||
*/
|
||||
@Override
|
||||
public void exportData(JsonWriter writer) throws IOException {
|
||||
throw new UnsupportedOperationException("Can not export 1.1 format from this version.");
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.mitre.openid.connect.service.MITREidDataService#importData(com.google.gson.stream.JsonReader)
|
||||
*/
|
||||
@Override
|
||||
public void importData(JsonReader reader) throws IOException {
|
||||
|
||||
logger.info("Reading configuration for 1.1");
|
||||
|
||||
// this *HAS* to start as an object
|
||||
reader.beginObject();
|
||||
|
||||
while (reader.hasNext()) {
|
||||
JsonToken tok = reader.peek();
|
||||
switch (tok) {
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
// find out which member it is
|
||||
if (name.equals(CLIENTS)) {
|
||||
readClients(reader);
|
||||
} else if (name.equals(GRANTS)) {
|
||||
readGrants(reader);
|
||||
} else if (name.equals(WHITELISTEDSITES)) {
|
||||
readWhitelistedSites(reader);
|
||||
} else if (name.equals(BLACKLISTEDSITES)) {
|
||||
readBlacklistedSites(reader);
|
||||
} else if (name.equals(AUTHENTICATIONHOLDERS)) {
|
||||
readAuthenticationHolders(reader);
|
||||
} else if (name.equals(ACCESSTOKENS)) {
|
||||
readAccessTokens(reader);
|
||||
} else if (name.equals(REFRESHTOKENS)) {
|
||||
readRefreshTokens(reader);
|
||||
} else if (name.equals(SYSTEMSCOPES)) {
|
||||
readSystemScopes(reader);
|
||||
} else {
|
||||
for (MITREidDataServiceExtension extension : extensions) {
|
||||
if (extension.supportsVersion(THIS_VERSION)) {
|
||||
if (extension.supportsVersion(THIS_VERSION)) {
|
||||
extension.importExtensionData(name, reader);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// unknown token, skip it
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
case END_OBJECT:
|
||||
// the object ended, we're done here
|
||||
reader.endObject();
|
||||
continue;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
fixObjectReferences();
|
||||
for (MITREidDataServiceExtension extension : extensions) {
|
||||
if (extension.supportsVersion(THIS_VERSION)) {
|
||||
extension.fixExtensionObjectReferences(maps);
|
||||
break;
|
||||
}
|
||||
}
|
||||
maps.clearAll();
|
||||
}
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readRefreshTokens(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
OAuth2RefreshTokenEntity token = new OAuth2RefreshTokenEntity();
|
||||
reader.beginObject();
|
||||
Long currentId = null;
|
||||
String clientId = null;
|
||||
Long authHolderId = null;
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("id")) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals("expiration")) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
token.setExpiration(date);
|
||||
} else if (name.equals("value")) {
|
||||
String value = reader.nextString();
|
||||
try {
|
||||
token.setJwt(JWTParser.parse(value));
|
||||
} catch (ParseException ex) {
|
||||
logger.error("Unable to set refresh token value to {}", value, ex);
|
||||
}
|
||||
} else if (name.equals("clientId")) {
|
||||
clientId = reader.nextString();
|
||||
} else if (name.equals("authenticationHolderId")) {
|
||||
authHolderId = reader.nextLong();
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = tokenRepository.saveRefreshToken(token).getId();
|
||||
maps.getRefreshTokenToClientRefs().put(currentId, clientId);
|
||||
maps.getRefreshTokenToAuthHolderRefs().put(currentId, authHolderId);
|
||||
maps.getRefreshTokenOldToNewIdMap().put(currentId, newId);
|
||||
logger.debug("Read refresh token {}", currentId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading refresh tokens");
|
||||
}
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readAccessTokens(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();
|
||||
reader.beginObject();
|
||||
Long currentId = null;
|
||||
String clientId = null;
|
||||
Long authHolderId = null;
|
||||
Long refreshTokenId = null;
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("id")) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals("expiration")) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
token.setExpiration(date);
|
||||
} else if (name.equals("value")) {
|
||||
String value = reader.nextString();
|
||||
try {
|
||||
// all tokens are JWTs
|
||||
token.setJwt(JWTParser.parse(value));
|
||||
} catch (ParseException ex) {
|
||||
logger.error("Unable to set refresh token value to {}", value, ex);
|
||||
}
|
||||
} else if (name.equals("clientId")) {
|
||||
clientId = reader.nextString();
|
||||
} else if (name.equals("authenticationHolderId")) {
|
||||
authHolderId = reader.nextLong();
|
||||
} else if (name.equals("refreshTokenId")) {
|
||||
refreshTokenId = reader.nextLong();
|
||||
} else if (name.equals("scope")) {
|
||||
Set<String> scope = readSet(reader);
|
||||
token.setScope(scope);
|
||||
} else if (name.equals("type")) {
|
||||
token.setTokenType(reader.nextString());
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = tokenRepository.saveAccessToken(token).getId();
|
||||
maps.getAccessTokenToClientRefs().put(currentId, clientId);
|
||||
maps.getAccessTokenToAuthHolderRefs().put(currentId, authHolderId);
|
||||
if (refreshTokenId != null) {
|
||||
maps.getAccessTokenToRefreshTokenRefs().put(currentId, refreshTokenId);
|
||||
}
|
||||
maps.getAccessTokenOldToNewIdMap().put(currentId, newId);
|
||||
logger.debug("Read access token {}", currentId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading access tokens");
|
||||
}
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readAuthenticationHolders(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
AuthenticationHolderEntity ahe = new AuthenticationHolderEntity();
|
||||
reader.beginObject();
|
||||
Long currentId = null;
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("id")) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals("ownerId")) {
|
||||
//not needed
|
||||
reader.skipValue();
|
||||
} else if (name.equals("authentication")) {
|
||||
OAuth2Request clientAuthorization = null;
|
||||
Authentication userAuthentication = null;
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String subName = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue(); // skip null values
|
||||
} else if (subName.equals("clientAuthorization")) {
|
||||
clientAuthorization = readAuthorizationRequest(reader);
|
||||
} 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();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
OAuth2Authentication auth = new OAuth2Authentication(clientAuthorization, userAuthentication);
|
||||
ahe.setAuthentication(auth);
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = authHolderRepository.save(ahe).getId();
|
||||
maps.getAuthHolderOldToNewIdMap().put(currentId, newId);
|
||||
logger.debug("Read authentication holder {}", currentId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading authentication holders");
|
||||
}
|
||||
|
||||
//used by readAuthenticationHolders
|
||||
private OAuth2Request readAuthorizationRequest(JsonReader reader) throws IOException {
|
||||
Set<String> scope = new LinkedHashSet<>();
|
||||
Set<String> resourceIds = new HashSet<>();
|
||||
boolean approved = false;
|
||||
Collection<GrantedAuthority> authorities = new HashSet<>();
|
||||
Map<String, String> requestParameters = new HashMap<>();
|
||||
Set<String> responseTypes = new HashSet<>();
|
||||
Map<String, Serializable> extensions = new HashMap<>();
|
||||
String redirectUri = null;
|
||||
String clientId = null;
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("requestParameters")) {
|
||||
requestParameters = readMap(reader);
|
||||
} else if (name.equals("clientId")) {
|
||||
clientId = reader.nextString();
|
||||
} else if (name.equals("scope")) {
|
||||
scope = readSet(reader);
|
||||
} else if (name.equals("resourceIds")) {
|
||||
resourceIds = readSet(reader);
|
||||
} else if (name.equals("authorities")) {
|
||||
Set<String> authorityStrs = readSet(reader);
|
||||
authorities = new HashSet<>();
|
||||
for (String s : authorityStrs) {
|
||||
GrantedAuthority ga = new SimpleGrantedAuthority(s);
|
||||
authorities.add(ga);
|
||||
}
|
||||
} else if (name.equals("approved")) {
|
||||
approved = reader.nextBoolean();
|
||||
} else if (name.equals("denied")) {
|
||||
if (approved == false) {
|
||||
approved = !reader.nextBoolean();
|
||||
}
|
||||
} else if (name.equals("redirectUri")) {
|
||||
redirectUri = reader.nextString();
|
||||
} else if (name.equals("responseTypes")) {
|
||||
responseTypes = readSet(reader);
|
||||
} else if (name.equals("extensions")) {
|
||||
// skip the binary encoded version
|
||||
reader.skipValue();
|
||||
} else if (name.equals("extensionStrings")) {
|
||||
Map<String, String> extEnc = readMap(reader);
|
||||
for (Entry<String, String> entry : extEnc.entrySet()) {
|
||||
extensions.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
} else {
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
return new OAuth2Request(requestParameters, clientId, authorities, approved, scope, resourceIds, redirectUri, responseTypes, extensions);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param reader
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
private SavedUserAuthentication readSavedUserAuthentication(JsonReader reader) throws IOException {
|
||||
SavedUserAuthentication savedUserAuth = new SavedUserAuthentication();
|
||||
reader.beginObject();
|
||||
|
||||
while (reader.hasNext()) {
|
||||
switch(reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("name")) {
|
||||
savedUserAuth.setName(reader.nextString());
|
||||
} else if (name.equals("sourceClass")) {
|
||||
savedUserAuth.setSourceClass(reader.nextString());
|
||||
} else if (name.equals("authenticated")) {
|
||||
savedUserAuth.setAuthenticated(reader.nextBoolean());
|
||||
} else if (name.equals("authorities")) {
|
||||
Set<String> authorityStrs = readSet(reader);
|
||||
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
|
||||
for (String s : authorityStrs) {
|
||||
GrantedAuthority ga = new SimpleGrantedAuthority(s);
|
||||
authorities.add(ga);
|
||||
}
|
||||
savedUserAuth.setAuthorities(authorities);
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
reader.endObject();
|
||||
return savedUserAuth;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readGrants(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
ApprovedSite site = new ApprovedSite();
|
||||
Long currentId = null;
|
||||
Long whitelistedSiteId = null;
|
||||
Set<Long> tokenIds = null;
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("id")) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals("accessDate")) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
site.setAccessDate(date);
|
||||
} else if (name.equals("clientId")) {
|
||||
site.setClientId(reader.nextString());
|
||||
} else if (name.equals("creationDate")) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
site.setCreationDate(date);
|
||||
} else if (name.equals("timeoutDate")) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
site.setTimeoutDate(date);
|
||||
} else if (name.equals("userId")) {
|
||||
site.setUserId(reader.nextString());
|
||||
} else if (name.equals("allowedScopes")) {
|
||||
Set<String> allowedScopes = readSet(reader);
|
||||
site.setAllowedScopes(allowedScopes);
|
||||
} else if (name.equals("whitelistedSiteId")) {
|
||||
whitelistedSiteId = reader.nextLong();
|
||||
} else if (name.equals("approvedAccessTokens")) {
|
||||
tokenIds = readSet(reader);
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = approvedSiteRepository.save(site).getId();
|
||||
maps.getGrantOldToNewIdMap().put(currentId, newId);
|
||||
if (whitelistedSiteId != null) {
|
||||
logger.debug("Ignoring whitelisted site marker on approved site.");
|
||||
}
|
||||
if (tokenIds != null) {
|
||||
maps.getGrantToAccessTokensRefs().put(currentId, tokenIds);
|
||||
}
|
||||
logger.debug("Read grant {}", currentId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading grants");
|
||||
}
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readWhitelistedSites(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
WhitelistedSite wlSite = new WhitelistedSite();
|
||||
Long currentId = null;
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (name.equals("id")) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals("clientId")) {
|
||||
wlSite.setClientId(reader.nextString());
|
||||
} else if (name.equals("creatorUserId")) {
|
||||
wlSite.setCreatorUserId(reader.nextString());
|
||||
} else if (name.equals("allowedScopes")) {
|
||||
Set<String> allowedScopes = readSet(reader);
|
||||
wlSite.setAllowedScopes(allowedScopes);
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = wlSiteRepository.save(wlSite).getId();
|
||||
maps.getWhitelistedSiteOldToNewIdMap().put(currentId, newId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading whitelisted sites");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readBlacklistedSites(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
BlacklistedSite blSite = new BlacklistedSite();
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (name.equals("id")) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("uri")) {
|
||||
blSite.setUri(reader.nextString());
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
blSiteRepository.save(blSite);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading blacklisted sites");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readClients(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
ClientDetailsEntity client = new ClientDetailsEntity();
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("clientId")) {
|
||||
client.setClientId(reader.nextString());
|
||||
} else if (name.equals("resourceIds")) {
|
||||
Set<String> resourceIds = readSet(reader);
|
||||
client.setResourceIds(resourceIds);
|
||||
} else if (name.equals("secret")) {
|
||||
client.setClientSecret(reader.nextString());
|
||||
} else if (name.equals("scope")) {
|
||||
Set<String> scope = readSet(reader);
|
||||
client.setScope(scope);
|
||||
} else if (name.equals("authorities")) {
|
||||
Set<String> authorityStrs = readSet(reader);
|
||||
Set<GrantedAuthority> authorities = new HashSet<>();
|
||||
for (String s : authorityStrs) {
|
||||
GrantedAuthority ga = new SimpleGrantedAuthority(s);
|
||||
authorities.add(ga);
|
||||
}
|
||||
client.setAuthorities(authorities);
|
||||
} else if (name.equals("accessTokenValiditySeconds")) {
|
||||
client.setAccessTokenValiditySeconds(reader.nextInt());
|
||||
} else if (name.equals("refreshTokenValiditySeconds")) {
|
||||
client.setRefreshTokenValiditySeconds(reader.nextInt());
|
||||
} else if (name.equals("redirectUris")) {
|
||||
Set<String> redirectUris = readSet(reader);
|
||||
client.setRedirectUris(redirectUris);
|
||||
} else if (name.equals("name")) {
|
||||
client.setClientName(reader.nextString());
|
||||
} else if (name.equals("uri")) {
|
||||
client.setClientUri(reader.nextString());
|
||||
} else if (name.equals("logoUri")) {
|
||||
client.setLogoUri(reader.nextString());
|
||||
} else if (name.equals("contacts")) {
|
||||
Set<String> contacts = readSet(reader);
|
||||
client.setContacts(contacts);
|
||||
} else if (name.equals("tosUri")) {
|
||||
client.setTosUri(reader.nextString());
|
||||
} else if (name.equals("tokenEndpointAuthMethod")) {
|
||||
AuthMethod am = AuthMethod.getByValue(reader.nextString());
|
||||
client.setTokenEndpointAuthMethod(am);
|
||||
} else if (name.equals("grantTypes")) {
|
||||
Set<String> grantTypes = readSet(reader);
|
||||
client.setGrantTypes(grantTypes);
|
||||
} else if (name.equals("responseTypes")) {
|
||||
Set<String> responseTypes = readSet(reader);
|
||||
client.setResponseTypes(responseTypes);
|
||||
} else if (name.equals("policyUri")) {
|
||||
client.setPolicyUri(reader.nextString());
|
||||
} else if (name.equals("applicationType")) {
|
||||
AppType appType = AppType.getByValue(reader.nextString());
|
||||
client.setApplicationType(appType);
|
||||
} else if (name.equals("sectorIdentifierUri")) {
|
||||
client.setSectorIdentifierUri(reader.nextString());
|
||||
} else if (name.equals("subjectType")) {
|
||||
SubjectType st = SubjectType.getByValue(reader.nextString());
|
||||
client.setSubjectType(st);
|
||||
} else if (name.equals("jwks_uri")) {
|
||||
client.setJwksUri(reader.nextString());
|
||||
} else if (name.equals("requestObjectSigningAlg")) {
|
||||
JWSAlgorithm alg = JWSAlgorithm.parse(reader.nextString());
|
||||
client.setRequestObjectSigningAlg(alg);
|
||||
} else if (name.equals("userInfoEncryptedResponseAlg")) {
|
||||
JWEAlgorithm alg = JWEAlgorithm.parse(reader.nextString());
|
||||
client.setUserInfoEncryptedResponseAlg(alg);
|
||||
} else if (name.equals("userInfoEncryptedResponseEnc")) {
|
||||
EncryptionMethod alg = EncryptionMethod.parse(reader.nextString());
|
||||
client.setUserInfoEncryptedResponseEnc(alg);
|
||||
} else if (name.equals("userInfoSignedResponseAlg")) {
|
||||
JWSAlgorithm alg = JWSAlgorithm.parse(reader.nextString());
|
||||
client.setUserInfoSignedResponseAlg(alg);
|
||||
} else if (name.equals("idTokenSignedResonseAlg")) {
|
||||
JWSAlgorithm alg = JWSAlgorithm.parse(reader.nextString());
|
||||
client.setIdTokenSignedResponseAlg(alg);
|
||||
} else if (name.equals("idTokenEncryptedResponseAlg")) {
|
||||
JWEAlgorithm alg = JWEAlgorithm.parse(reader.nextString());
|
||||
client.setIdTokenEncryptedResponseAlg(alg);
|
||||
} else if (name.equals("idTokenEncryptedResponseEnc")) {
|
||||
EncryptionMethod alg = EncryptionMethod.parse(reader.nextString());
|
||||
client.setIdTokenEncryptedResponseEnc(alg);
|
||||
} else if (name.equals("tokenEndpointAuthSigningAlg")) {
|
||||
JWSAlgorithm alg = JWSAlgorithm.parse(reader.nextString());
|
||||
client.setTokenEndpointAuthSigningAlg(alg);
|
||||
} else if (name.equals("defaultMaxAge")) {
|
||||
client.setDefaultMaxAge(reader.nextInt());
|
||||
} else if (name.equals("requireAuthTime")) {
|
||||
client.setRequireAuthTime(reader.nextBoolean());
|
||||
} else if (name.equals("defaultACRValues")) {
|
||||
Set<String> defaultACRvalues = readSet(reader);
|
||||
client.setDefaultACRvalues(defaultACRvalues);
|
||||
} else if (name.equals("initiateLoginUri")) {
|
||||
client.setInitiateLoginUri(reader.nextString());
|
||||
} else if (name.equals("postLogoutRedirectUri")) {
|
||||
HashSet<String> postLogoutUris = Sets.newHashSet(reader.nextString());
|
||||
client.setPostLogoutRedirectUris(postLogoutUris);
|
||||
} else if (name.equals("requestUris")) {
|
||||
Set<String> requestUris = readSet(reader);
|
||||
client.setRequestUris(requestUris);
|
||||
} else if (name.equals("description")) {
|
||||
client.setClientDescription(reader.nextString());
|
||||
} else if (name.equals("allowIntrospection")) {
|
||||
client.setAllowIntrospection(reader.nextBoolean());
|
||||
} else if (name.equals("reuseRefreshToken")) {
|
||||
client.setReuseRefreshToken(reader.nextBoolean());
|
||||
} else if (name.equals("dynamicallyRegistered")) {
|
||||
client.setDynamicallyRegistered(reader.nextBoolean());
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
clientRepository.saveClient(client);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading clients");
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the list of system scopes from the reader and insert them into the
|
||||
* scope repository.
|
||||
*
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readSystemScopes(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
SystemScope scope = new SystemScope();
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals("value")) {
|
||||
scope.setValue(reader.nextString());
|
||||
} else if (name.equals("description")) {
|
||||
scope.setDescription(reader.nextString());
|
||||
} else if (name.equals("allowDynReg")) {
|
||||
// previously "allowDynReg" scopes are now tagged as "not restricted" and vice versa
|
||||
scope.setRestricted(!reader.nextBoolean());
|
||||
} else if (name.equals("defaultScope")) {
|
||||
scope.setDefaultScope(reader.nextBoolean());
|
||||
} else if (name.equals("structured")) {
|
||||
logger.warn("Found a structured scope, ignoring structure");
|
||||
} else if (name.equals("structuredParameter")) {
|
||||
logger.warn("Found a structured scope, ignoring structure");
|
||||
} else if (name.equals("icon")) {
|
||||
scope.setIcon(reader.nextString());
|
||||
} else {
|
||||
logger.debug("found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
sysScopeRepository.save(scope);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading system scopes");
|
||||
}
|
||||
|
||||
private void fixObjectReferences() {
|
||||
for (Long oldRefreshTokenId : maps.getRefreshTokenToClientRefs().keySet()) {
|
||||
String clientRef = maps.getRefreshTokenToClientRefs().get(oldRefreshTokenId);
|
||||
ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef);
|
||||
Long newRefreshTokenId = maps.getRefreshTokenOldToNewIdMap().get(oldRefreshTokenId);
|
||||
OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId);
|
||||
refreshToken.setClient(client);
|
||||
tokenRepository.saveRefreshToken(refreshToken);
|
||||
}
|
||||
for (Long oldRefreshTokenId : maps.getRefreshTokenToAuthHolderRefs().keySet()) {
|
||||
Long oldAuthHolderId = maps.getRefreshTokenToAuthHolderRefs().get(oldRefreshTokenId);
|
||||
Long newAuthHolderId = maps.getAuthHolderOldToNewIdMap().get(oldAuthHolderId);
|
||||
AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId);
|
||||
Long newRefreshTokenId = maps.getRefreshTokenOldToNewIdMap().get(oldRefreshTokenId);
|
||||
OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId);
|
||||
refreshToken.setAuthenticationHolder(authHolder);
|
||||
tokenRepository.saveRefreshToken(refreshToken);
|
||||
}
|
||||
for (Long oldAccessTokenId : maps.getAccessTokenToClientRefs().keySet()) {
|
||||
String clientRef = maps.getAccessTokenToClientRefs().get(oldAccessTokenId);
|
||||
ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef);
|
||||
Long newAccessTokenId = maps.getAccessTokenOldToNewIdMap().get(oldAccessTokenId);
|
||||
OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId);
|
||||
accessToken.setClient(client);
|
||||
tokenRepository.saveAccessToken(accessToken);
|
||||
}
|
||||
maps.getAccessTokenToClientRefs().clear();
|
||||
for (Long oldAccessTokenId : maps.getAccessTokenToAuthHolderRefs().keySet()) {
|
||||
Long oldAuthHolderId = maps.getAccessTokenToAuthHolderRefs().get(oldAccessTokenId);
|
||||
Long newAuthHolderId = maps.getAuthHolderOldToNewIdMap().get(oldAuthHolderId);
|
||||
AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId);
|
||||
Long newAccessTokenId = maps.getAccessTokenOldToNewIdMap().get(oldAccessTokenId);
|
||||
OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId);
|
||||
accessToken.setAuthenticationHolder(authHolder);
|
||||
tokenRepository.saveAccessToken(accessToken);
|
||||
}
|
||||
for (Long oldAccessTokenId : maps.getAccessTokenToRefreshTokenRefs().keySet()) {
|
||||
Long oldRefreshTokenId = maps.getAccessTokenToRefreshTokenRefs().get(oldAccessTokenId);
|
||||
Long newRefreshTokenId = maps.getRefreshTokenOldToNewIdMap().get(oldRefreshTokenId);
|
||||
OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId);
|
||||
Long newAccessTokenId = maps.getAccessTokenOldToNewIdMap().get(oldAccessTokenId);
|
||||
OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId);
|
||||
accessToken.setRefreshToken(refreshToken);
|
||||
tokenRepository.saveAccessToken(accessToken);
|
||||
}
|
||||
for (Long oldGrantId : maps.getGrantToAccessTokensRefs().keySet()) {
|
||||
Set<Long> oldAccessTokenIds = maps.getGrantToAccessTokensRefs().get(oldGrantId);
|
||||
|
||||
Long newGrantId = maps.getGrantOldToNewIdMap().get(oldGrantId);
|
||||
ApprovedSite site = approvedSiteRepository.getById(newGrantId);
|
||||
|
||||
for(Long oldTokenId : oldAccessTokenIds) {
|
||||
Long newTokenId = maps.getAccessTokenOldToNewIdMap().get(oldTokenId);
|
||||
OAuth2AccessTokenEntity token = tokenRepository.getAccessTokenById(newTokenId);
|
||||
token.setApprovedSite(site);
|
||||
tokenRepository.saveAccessToken(token);
|
||||
}
|
||||
|
||||
approvedSiteRepository.save(site);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,901 +0,0 @@
|
|||
/*******************************************************************************
|
||||
* Copyright 2018 The MIT Internet Trust Consortium
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*******************************************************************************/
|
||||
package org.mitre.openid.connect.service.impl;
|
||||
|
||||
import static org.mitre.util.JsonUtils.readMap;
|
||||
import static org.mitre.util.JsonUtils.readSet;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.ParseException;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.mitre.oauth2.model.AuthenticationHolderEntity;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity.AppType;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity.AuthMethod;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity.SubjectType;
|
||||
import org.mitre.oauth2.model.OAuth2AccessTokenEntity;
|
||||
import org.mitre.oauth2.model.OAuth2RefreshTokenEntity;
|
||||
import org.mitre.oauth2.model.SavedUserAuthentication;
|
||||
import org.mitre.oauth2.model.SystemScope;
|
||||
import org.mitre.oauth2.repository.AuthenticationHolderRepository;
|
||||
import org.mitre.oauth2.repository.OAuth2ClientRepository;
|
||||
import org.mitre.oauth2.repository.OAuth2TokenRepository;
|
||||
import org.mitre.oauth2.repository.SystemScopeRepository;
|
||||
import org.mitre.openid.connect.model.ApprovedSite;
|
||||
import org.mitre.openid.connect.model.BlacklistedSite;
|
||||
import org.mitre.openid.connect.model.WhitelistedSite;
|
||||
import org.mitre.openid.connect.repository.ApprovedSiteRepository;
|
||||
import org.mitre.openid.connect.repository.BlacklistedSiteRepository;
|
||||
import org.mitre.openid.connect.repository.WhitelistedSiteRepository;
|
||||
import org.mitre.openid.connect.service.MITREidDataService;
|
||||
import org.mitre.openid.connect.service.MITREidDataServiceExtension;
|
||||
import org.mitre.openid.connect.service.MITREidDataServiceMaps;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonToken;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
import com.nimbusds.jose.EncryptionMethod;
|
||||
import com.nimbusds.jose.JWEAlgorithm;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jose.jwk.JWKSet;
|
||||
import com.nimbusds.jwt.JWTParser;
|
||||
|
||||
/**
|
||||
*
|
||||
* Data service to import and export MITREid 1.2 configuration.
|
||||
*
|
||||
* @author jricher
|
||||
* @author arielak
|
||||
*/
|
||||
@Service
|
||||
@SuppressWarnings(value = {"unchecked"})
|
||||
public class MITREidDataService_1_2 extends MITREidDataServiceSupport implements MITREidDataService {
|
||||
|
||||
private static final String DEFAULT_SCOPE = "defaultScope";
|
||||
private static final String STRUCTURED_PARAMETER = "structuredParameter";
|
||||
private static final String STRUCTURED = "structured";
|
||||
private static final String RESTRICTED = "restricted";
|
||||
private static final String ICON = "icon";
|
||||
private static final String DYNAMICALLY_REGISTERED = "dynamicallyRegistered";
|
||||
private static final String CLEAR_ACCESS_TOKENS_ON_REFRESH = "clearAccessTokensOnRefresh";
|
||||
private static final String REUSE_REFRESH_TOKEN = "reuseRefreshToken";
|
||||
private static final String ALLOW_INTROSPECTION = "allowIntrospection";
|
||||
private static final String DESCRIPTION = "description";
|
||||
private static final String REQUEST_URIS = "requestUris";
|
||||
private static final String POST_LOGOUT_REDIRECT_URI = "postLogoutRedirectUri";
|
||||
private static final String INTITATE_LOGIN_URI = "intitateLoginUri";
|
||||
private static final String DEFAULT_ACR_VALUES = "defaultACRValues";
|
||||
private static final String REQUIRE_AUTH_TIME = "requireAuthTime";
|
||||
private static final String DEFAULT_MAX_AGE = "defaultMaxAge";
|
||||
private static final String TOKEN_ENDPOINT_AUTH_SIGNING_ALG = "tokenEndpointAuthSigningAlg";
|
||||
private static final String USER_INFO_ENCRYPTED_RESPONSE_ENC = "userInfoEncryptedResponseEnc";
|
||||
private static final String USER_INFO_ENCRYPTED_RESPONSE_ALG = "userInfoEncryptedResponseAlg";
|
||||
private static final String USER_INFO_SIGNED_RESPONSE_ALG = "userInfoSignedResponseAlg";
|
||||
private static final String ID_TOKEN_ENCRYPTED_RESPONSE_ENC = "idTokenEncryptedResponseEnc";
|
||||
private static final String ID_TOKEN_ENCRYPTED_RESPONSE_ALG = "idTokenEncryptedResponseAlg";
|
||||
private static final String ID_TOKEN_SIGNED_RESPONSE_ALG = "idTokenSignedResponseAlg";
|
||||
private static final String REQUEST_OBJECT_SIGNING_ALG = "requestObjectSigningAlg";
|
||||
private static final String SUBJECT_TYPE = "subjectType";
|
||||
private static final String SECTOR_IDENTIFIER_URI = "sectorIdentifierUri";
|
||||
private static final String APPLICATION_TYPE = "applicationType";
|
||||
private static final String JWKS = "jwks";
|
||||
private static final String JWKS_URI = "jwksUri";
|
||||
private static final String POLICY_URI = "policyUri";
|
||||
private static final String GRANT_TYPES = "grantTypes";
|
||||
private static final String TOKEN_ENDPOINT_AUTH_METHOD = "tokenEndpointAuthMethod";
|
||||
private static final String TOS_URI = "tosUri";
|
||||
private static final String CONTACTS = "contacts";
|
||||
private static final String LOGO_URI = "logoUri";
|
||||
private static final String REDIRECT_URIS = "redirectUris";
|
||||
private static final String REFRESH_TOKEN_VALIDITY_SECONDS = "refreshTokenValiditySeconds";
|
||||
private static final String ACCESS_TOKEN_VALIDITY_SECONDS = "accessTokenValiditySeconds";
|
||||
private static final String SECRET = "secret";
|
||||
private static final String URI = "uri";
|
||||
private static final String CREATOR_USER_ID = "creatorUserId";
|
||||
private static final String APPROVED_ACCESS_TOKENS = "approvedAccessTokens";
|
||||
private static final String ALLOWED_SCOPES = "allowedScopes";
|
||||
private static final String USER_ID = "userId";
|
||||
private static final String TIMEOUT_DATE = "timeoutDate";
|
||||
private static final String CREATION_DATE = "creationDate";
|
||||
private static final String ACCESS_DATE = "accessDate";
|
||||
private static final String AUTHENTICATED = "authenticated";
|
||||
private static final String SOURCE_CLASS = "sourceClass";
|
||||
private static final String NAME = "name";
|
||||
private static final String SAVED_USER_AUTHENTICATION = "savedUserAuthentication";
|
||||
private static final String EXTENSIONS = "extensions";
|
||||
private static final String RESPONSE_TYPES = "responseTypes";
|
||||
private static final String REDIRECT_URI = "redirectUri";
|
||||
private static final String APPROVED = "approved";
|
||||
private static final String AUTHORITIES = "authorities";
|
||||
private static final String RESOURCE_IDS = "resourceIds";
|
||||
private static final String REQUEST_PARAMETERS = "requestParameters";
|
||||
private static final String TYPE = "type";
|
||||
private static final String SCOPE = "scope";
|
||||
private static final String REFRESH_TOKEN_ID = "refreshTokenId";
|
||||
private static final String VALUE = "value";
|
||||
private static final String AUTHENTICATION_HOLDER_ID = "authenticationHolderId";
|
||||
private static final String CLIENT_ID = "clientId";
|
||||
private static final String EXPIRATION = "expiration";
|
||||
private static final String CLAIMS_REDIRECT_URIS = "claimsRedirectUris";
|
||||
private static final String ID = "id";
|
||||
/**
|
||||
* Logger for this class
|
||||
*/
|
||||
private static final Logger logger = LoggerFactory.getLogger(MITREidDataService_1_2.class);
|
||||
@Autowired
|
||||
private OAuth2ClientRepository clientRepository;
|
||||
@Autowired
|
||||
private ApprovedSiteRepository approvedSiteRepository;
|
||||
@Autowired
|
||||
private WhitelistedSiteRepository wlSiteRepository;
|
||||
@Autowired
|
||||
private BlacklistedSiteRepository blSiteRepository;
|
||||
@Autowired
|
||||
private AuthenticationHolderRepository authHolderRepository;
|
||||
@Autowired
|
||||
private OAuth2TokenRepository tokenRepository;
|
||||
@Autowired
|
||||
private SystemScopeRepository sysScopeRepository;
|
||||
@Autowired(required = false)
|
||||
private List<MITREidDataServiceExtension> extensions = Collections.emptyList();
|
||||
|
||||
private MITREidDataServiceMaps maps = new MITREidDataServiceMaps();
|
||||
|
||||
private static final String THIS_VERSION = MITREID_CONNECT_1_2;
|
||||
|
||||
@Override
|
||||
public boolean supportsVersion(String version) {
|
||||
return THIS_VERSION.equals(version);
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.mitre.openid.connect.service.MITREidDataService#export(com.google.gson.stream.JsonWriter)
|
||||
*/
|
||||
@Override
|
||||
public void exportData(JsonWriter writer) throws IOException {
|
||||
|
||||
throw new UnsupportedOperationException("Can not export 1.2 format from this version.");
|
||||
}
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.mitre.openid.connect.service.MITREidDataService#importData(com.google.gson.stream.JsonReader)
|
||||
*/
|
||||
@Override
|
||||
public void importData(JsonReader reader) throws IOException {
|
||||
|
||||
logger.info("Reading configuration for 1.2");
|
||||
|
||||
// this *HAS* to start as an object
|
||||
reader.beginObject();
|
||||
|
||||
while (reader.hasNext()) {
|
||||
JsonToken tok = reader.peek();
|
||||
switch (tok) {
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
// find out which member it is
|
||||
if (name.equals(CLIENTS)) {
|
||||
readClients(reader);
|
||||
} else if (name.equals(GRANTS)) {
|
||||
readGrants(reader);
|
||||
} else if (name.equals(WHITELISTEDSITES)) {
|
||||
readWhitelistedSites(reader);
|
||||
} else if (name.equals(BLACKLISTEDSITES)) {
|
||||
readBlacklistedSites(reader);
|
||||
} else if (name.equals(AUTHENTICATIONHOLDERS)) {
|
||||
readAuthenticationHolders(reader);
|
||||
} else if (name.equals(ACCESSTOKENS)) {
|
||||
readAccessTokens(reader);
|
||||
} else if (name.equals(REFRESHTOKENS)) {
|
||||
readRefreshTokens(reader);
|
||||
} else if (name.equals(SYSTEMSCOPES)) {
|
||||
readSystemScopes(reader);
|
||||
} else {
|
||||
for (MITREidDataServiceExtension extension : extensions) {
|
||||
if (extension.supportsVersion(THIS_VERSION)) {
|
||||
extension.importExtensionData(name, reader);
|
||||
break;
|
||||
}
|
||||
}
|
||||
// unknown token, skip it
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
case END_OBJECT:
|
||||
// the object ended, we're done here
|
||||
reader.endObject();
|
||||
continue;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
fixObjectReferences();
|
||||
for (MITREidDataServiceExtension extension : extensions) {
|
||||
if (extension.supportsVersion(THIS_VERSION)) {
|
||||
extension.fixExtensionObjectReferences(maps);
|
||||
break;
|
||||
}
|
||||
}
|
||||
maps.clearAll();
|
||||
}
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readRefreshTokens(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
OAuth2RefreshTokenEntity token = new OAuth2RefreshTokenEntity();
|
||||
reader.beginObject();
|
||||
Long currentId = null;
|
||||
String clientId = null;
|
||||
Long authHolderId = null;
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals(ID)) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals(EXPIRATION)) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
token.setExpiration(date);
|
||||
} else if (name.equals(VALUE)) {
|
||||
String value = reader.nextString();
|
||||
try {
|
||||
token.setJwt(JWTParser.parse(value));
|
||||
} catch (ParseException ex) {
|
||||
logger.error("Unable to set refresh token value to {}", value, ex);
|
||||
}
|
||||
} else if (name.equals(CLIENT_ID)) {
|
||||
clientId = reader.nextString();
|
||||
} else if (name.equals(AUTHENTICATION_HOLDER_ID)) {
|
||||
authHolderId = reader.nextLong();
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = tokenRepository.saveRefreshToken(token).getId();
|
||||
maps.getRefreshTokenToClientRefs().put(currentId, clientId);
|
||||
maps.getRefreshTokenToAuthHolderRefs().put(currentId, authHolderId);
|
||||
maps.getRefreshTokenOldToNewIdMap().put(currentId, newId);
|
||||
logger.debug("Read refresh token {}", currentId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading refresh tokens");
|
||||
}
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readAccessTokens(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();
|
||||
reader.beginObject();
|
||||
Long currentId = null;
|
||||
String clientId = null;
|
||||
Long authHolderId = null;
|
||||
Long refreshTokenId = null;
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals(ID)) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals(EXPIRATION)) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
token.setExpiration(date);
|
||||
} else if (name.equals(VALUE)) {
|
||||
String value = reader.nextString();
|
||||
try {
|
||||
// all tokens are JWTs
|
||||
token.setJwt(JWTParser.parse(value));
|
||||
} catch (ParseException ex) {
|
||||
logger.error("Unable to set refresh token value to {}", value, ex);
|
||||
}
|
||||
} else if (name.equals(CLIENT_ID)) {
|
||||
clientId = reader.nextString();
|
||||
} else if (name.equals(AUTHENTICATION_HOLDER_ID)) {
|
||||
authHolderId = reader.nextLong();
|
||||
} else if (name.equals(REFRESH_TOKEN_ID)) {
|
||||
refreshTokenId = reader.nextLong();
|
||||
} else if (name.equals(SCOPE)) {
|
||||
Set<String> scope = readSet(reader);
|
||||
token.setScope(scope);
|
||||
} else if (name.equals(TYPE)) {
|
||||
token.setTokenType(reader.nextString());
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = tokenRepository.saveAccessToken(token).getId();
|
||||
maps.getAccessTokenToClientRefs().put(currentId, clientId);
|
||||
maps.getAccessTokenToAuthHolderRefs().put(currentId, authHolderId);
|
||||
if (refreshTokenId != null) {
|
||||
maps.getAccessTokenToRefreshTokenRefs().put(currentId, refreshTokenId);
|
||||
}
|
||||
maps.getAccessTokenOldToNewIdMap().put(currentId, newId);
|
||||
logger.debug("Read access token {}", currentId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading access tokens");
|
||||
}
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readAuthenticationHolders(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
AuthenticationHolderEntity ahe = new AuthenticationHolderEntity();
|
||||
reader.beginObject();
|
||||
Long currentId = null;
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals(ID)) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals(REQUEST_PARAMETERS)) {
|
||||
ahe.setRequestParameters(readMap(reader));
|
||||
} else if (name.equals(CLIENT_ID)) {
|
||||
ahe.setClientId(reader.nextString());
|
||||
} else if (name.equals(SCOPE)) {
|
||||
ahe.setScope(readSet(reader));
|
||||
} else if (name.equals(RESOURCE_IDS)) {
|
||||
ahe.setResourceIds(readSet(reader));
|
||||
} else if (name.equals(AUTHORITIES)) {
|
||||
Set<String> authorityStrs = readSet(reader);
|
||||
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
|
||||
for (String s : authorityStrs) {
|
||||
GrantedAuthority ga = new SimpleGrantedAuthority(s);
|
||||
authorities.add(ga);
|
||||
}
|
||||
ahe.setAuthorities(authorities);
|
||||
} else if (name.equals(APPROVED)) {
|
||||
ahe.setApproved(reader.nextBoolean());
|
||||
} else if (name.equals(REDIRECT_URI)) {
|
||||
ahe.setRedirectUri(reader.nextString());
|
||||
} else if (name.equals(RESPONSE_TYPES)) {
|
||||
ahe.setResponseTypes(readSet(reader));
|
||||
} else if (name.equals(EXTENSIONS)) {
|
||||
ahe.setExtensions(readMap(reader));
|
||||
} else if (name.equals(SAVED_USER_AUTHENTICATION)) {
|
||||
ahe.setUserAuth(readSavedUserAuthentication(reader));
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = authHolderRepository.save(ahe).getId();
|
||||
maps.getAuthHolderOldToNewIdMap().put(currentId, newId);
|
||||
logger.debug("Read authentication holder {}", currentId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading authentication holders");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param reader
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
private SavedUserAuthentication readSavedUserAuthentication(JsonReader reader) throws IOException {
|
||||
SavedUserAuthentication savedUserAuth = new SavedUserAuthentication();
|
||||
reader.beginObject();
|
||||
|
||||
while (reader.hasNext()) {
|
||||
switch(reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals(NAME)) {
|
||||
savedUserAuth.setName(reader.nextString());
|
||||
} else if (name.equals(SOURCE_CLASS)) {
|
||||
savedUserAuth.setSourceClass(reader.nextString());
|
||||
} else if (name.equals(AUTHENTICATED)) {
|
||||
savedUserAuth.setAuthenticated(reader.nextBoolean());
|
||||
} else if (name.equals(AUTHORITIES)) {
|
||||
Set<String> authorityStrs = readSet(reader);
|
||||
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
|
||||
for (String s : authorityStrs) {
|
||||
GrantedAuthority ga = new SimpleGrantedAuthority(s);
|
||||
authorities.add(ga);
|
||||
}
|
||||
savedUserAuth.setAuthorities(authorities);
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
reader.endObject();
|
||||
return savedUserAuth;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readGrants(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
ApprovedSite site = new ApprovedSite();
|
||||
Long currentId = null;
|
||||
Set<Long> tokenIds = null;
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals(ID)) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals(ACCESS_DATE)) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
site.setAccessDate(date);
|
||||
} else if (name.equals(CLIENT_ID)) {
|
||||
site.setClientId(reader.nextString());
|
||||
} else if (name.equals(CREATION_DATE)) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
site.setCreationDate(date);
|
||||
} else if (name.equals(TIMEOUT_DATE)) {
|
||||
Date date = utcToDate(reader.nextString());
|
||||
site.setTimeoutDate(date);
|
||||
} else if (name.equals(USER_ID)) {
|
||||
site.setUserId(reader.nextString());
|
||||
} else if (name.equals(ALLOWED_SCOPES)) {
|
||||
Set<String> allowedScopes = readSet(reader);
|
||||
site.setAllowedScopes(allowedScopes);
|
||||
} else if (name.equals(APPROVED_ACCESS_TOKENS)) {
|
||||
tokenIds = readSet(reader);
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = approvedSiteRepository.save(site).getId();
|
||||
maps.getGrantOldToNewIdMap().put(currentId, newId);
|
||||
if (tokenIds != null) {
|
||||
maps.getGrantToAccessTokensRefs().put(currentId, tokenIds);
|
||||
}
|
||||
logger.debug("Read grant {}", currentId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading grants");
|
||||
}
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readWhitelistedSites(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
WhitelistedSite wlSite = new WhitelistedSite();
|
||||
Long currentId = null;
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (name.equals(ID)) {
|
||||
currentId = reader.nextLong();
|
||||
} else if (name.equals(CLIENT_ID)) {
|
||||
wlSite.setClientId(reader.nextString());
|
||||
} else if (name.equals(CREATOR_USER_ID)) {
|
||||
wlSite.setCreatorUserId(reader.nextString());
|
||||
} else if (name.equals(ALLOWED_SCOPES)) {
|
||||
Set<String> allowedScopes = readSet(reader);
|
||||
wlSite.setAllowedScopes(allowedScopes);
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
Long newId = wlSiteRepository.save(wlSite).getId();
|
||||
maps.getWhitelistedSiteOldToNewIdMap().put(currentId, newId);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading whitelisted sites");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readBlacklistedSites(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
BlacklistedSite blSite = new BlacklistedSite();
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (name.equals(ID)) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals(URI)) {
|
||||
blSite.setUri(reader.nextString());
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
blSiteRepository.save(blSite);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading blacklisted sites");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readClients(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
ClientDetailsEntity client = new ClientDetailsEntity();
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals(CLIENT_ID)) {
|
||||
client.setClientId(reader.nextString());
|
||||
} else if (name.equals(RESOURCE_IDS)) {
|
||||
Set<String> resourceIds = readSet(reader);
|
||||
client.setResourceIds(resourceIds);
|
||||
} else if (name.equals(SECRET)) {
|
||||
client.setClientSecret(reader.nextString());
|
||||
} else if (name.equals(SCOPE)) {
|
||||
Set<String> scope = readSet(reader);
|
||||
client.setScope(scope);
|
||||
} else if (name.equals(AUTHORITIES)) {
|
||||
Set<String> authorityStrs = readSet(reader);
|
||||
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
|
||||
for (String s : authorityStrs) {
|
||||
GrantedAuthority ga = new SimpleGrantedAuthority(s);
|
||||
authorities.add(ga);
|
||||
}
|
||||
client.setAuthorities(authorities);
|
||||
} else if (name.equals(ACCESS_TOKEN_VALIDITY_SECONDS)) {
|
||||
client.setAccessTokenValiditySeconds(reader.nextInt());
|
||||
} else if (name.equals(REFRESH_TOKEN_VALIDITY_SECONDS)) {
|
||||
client.setRefreshTokenValiditySeconds(reader.nextInt());
|
||||
} else if (name.equals(REDIRECT_URIS)) {
|
||||
Set<String> redirectUris = readSet(reader);
|
||||
client.setRedirectUris(redirectUris);
|
||||
} else if (name.equals(CLAIMS_REDIRECT_URIS)) {
|
||||
Set<String> claimsRedirectUris = readSet(reader);
|
||||
client.setClaimsRedirectUris(claimsRedirectUris);
|
||||
} else if (name.equals(NAME)) {
|
||||
client.setClientName(reader.nextString());
|
||||
} else if (name.equals(URI)) {
|
||||
client.setClientUri(reader.nextString());
|
||||
} else if (name.equals(LOGO_URI)) {
|
||||
client.setLogoUri(reader.nextString());
|
||||
} else if (name.equals(CONTACTS)) {
|
||||
Set<String> contacts = readSet(reader);
|
||||
client.setContacts(contacts);
|
||||
} else if (name.equals(TOS_URI)) {
|
||||
client.setTosUri(reader.nextString());
|
||||
} else if (name.equals(TOKEN_ENDPOINT_AUTH_METHOD)) {
|
||||
AuthMethod am = AuthMethod.getByValue(reader.nextString());
|
||||
client.setTokenEndpointAuthMethod(am);
|
||||
} else if (name.equals(GRANT_TYPES)) {
|
||||
Set<String> grantTypes = readSet(reader);
|
||||
client.setGrantTypes(grantTypes);
|
||||
} else if (name.equals(RESPONSE_TYPES)) {
|
||||
Set<String> responseTypes = readSet(reader);
|
||||
client.setResponseTypes(responseTypes);
|
||||
} else if (name.equals(POLICY_URI)) {
|
||||
client.setPolicyUri(reader.nextString());
|
||||
} else if (name.equals(APPLICATION_TYPE)) {
|
||||
AppType appType = AppType.getByValue(reader.nextString());
|
||||
client.setApplicationType(appType);
|
||||
} else if (name.equals(SECTOR_IDENTIFIER_URI)) {
|
||||
client.setSectorIdentifierUri(reader.nextString());
|
||||
} else if (name.equals(SUBJECT_TYPE)) {
|
||||
SubjectType st = SubjectType.getByValue(reader.nextString());
|
||||
client.setSubjectType(st);
|
||||
} else if (name.equals(JWKS_URI)) {
|
||||
client.setJwksUri(reader.nextString());
|
||||
} else if (name.equals(JWKS)) {
|
||||
try {
|
||||
client.setJwks(JWKSet.parse(reader.nextString()));
|
||||
} catch (ParseException e) {
|
||||
logger.error("Couldn't parse JWK Set", e);
|
||||
}
|
||||
} else if (name.equals(REQUEST_OBJECT_SIGNING_ALG)) {
|
||||
JWSAlgorithm alg = JWSAlgorithm.parse(reader.nextString());
|
||||
client.setRequestObjectSigningAlg(alg);
|
||||
} else if (name.equals(USER_INFO_ENCRYPTED_RESPONSE_ALG)) {
|
||||
JWEAlgorithm alg = JWEAlgorithm.parse(reader.nextString());
|
||||
client.setUserInfoEncryptedResponseAlg(alg);
|
||||
} else if (name.equals(USER_INFO_ENCRYPTED_RESPONSE_ENC)) {
|
||||
EncryptionMethod alg = EncryptionMethod.parse(reader.nextString());
|
||||
client.setUserInfoEncryptedResponseEnc(alg);
|
||||
} else if (name.equals(USER_INFO_SIGNED_RESPONSE_ALG)) {
|
||||
JWSAlgorithm alg = JWSAlgorithm.parse(reader.nextString());
|
||||
client.setUserInfoSignedResponseAlg(alg);
|
||||
} else if (name.equals(ID_TOKEN_SIGNED_RESPONSE_ALG)) {
|
||||
JWSAlgorithm alg = JWSAlgorithm.parse(reader.nextString());
|
||||
client.setIdTokenSignedResponseAlg(alg);
|
||||
} else if (name.equals(ID_TOKEN_ENCRYPTED_RESPONSE_ALG)) {
|
||||
JWEAlgorithm alg = JWEAlgorithm.parse(reader.nextString());
|
||||
client.setIdTokenEncryptedResponseAlg(alg);
|
||||
} else if (name.equals(ID_TOKEN_ENCRYPTED_RESPONSE_ENC)) {
|
||||
EncryptionMethod alg = EncryptionMethod.parse(reader.nextString());
|
||||
client.setIdTokenEncryptedResponseEnc(alg);
|
||||
} else if (name.equals(TOKEN_ENDPOINT_AUTH_SIGNING_ALG)) {
|
||||
JWSAlgorithm alg = JWSAlgorithm.parse(reader.nextString());
|
||||
client.setTokenEndpointAuthSigningAlg(alg);
|
||||
} else if (name.equals(DEFAULT_MAX_AGE)) {
|
||||
client.setDefaultMaxAge(reader.nextInt());
|
||||
} else if (name.equals(REQUIRE_AUTH_TIME)) {
|
||||
client.setRequireAuthTime(reader.nextBoolean());
|
||||
} else if (name.equals(DEFAULT_ACR_VALUES)) {
|
||||
Set<String> defaultACRvalues = readSet(reader);
|
||||
client.setDefaultACRvalues(defaultACRvalues);
|
||||
} else if (name.equals("initiateLoginUri")) {
|
||||
client.setInitiateLoginUri(reader.nextString());
|
||||
} else if (name.equals(POST_LOGOUT_REDIRECT_URI)) {
|
||||
Set<String> postLogoutUris = readSet(reader);
|
||||
client.setPostLogoutRedirectUris(postLogoutUris);
|
||||
} else if (name.equals(REQUEST_URIS)) {
|
||||
Set<String> requestUris = readSet(reader);
|
||||
client.setRequestUris(requestUris);
|
||||
} else if (name.equals(DESCRIPTION)) {
|
||||
client.setClientDescription(reader.nextString());
|
||||
} else if (name.equals(ALLOW_INTROSPECTION)) {
|
||||
client.setAllowIntrospection(reader.nextBoolean());
|
||||
} else if (name.equals(REUSE_REFRESH_TOKEN)) {
|
||||
client.setReuseRefreshToken(reader.nextBoolean());
|
||||
} else if (name.equals(CLEAR_ACCESS_TOKENS_ON_REFRESH)) {
|
||||
client.setClearAccessTokensOnRefresh(reader.nextBoolean());
|
||||
} else if (name.equals(DYNAMICALLY_REGISTERED)) {
|
||||
client.setDynamicallyRegistered(reader.nextBoolean());
|
||||
} else {
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
clientRepository.saveClient(client);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading clients");
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the list of system scopes from the reader and insert them into the
|
||||
* scope repository.
|
||||
*
|
||||
* @param reader
|
||||
* @throws IOException
|
||||
*/
|
||||
private void readSystemScopes(JsonReader reader) throws IOException {
|
||||
reader.beginArray();
|
||||
while (reader.hasNext()) {
|
||||
SystemScope scope = new SystemScope();
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
switch (reader.peek()) {
|
||||
case END_OBJECT:
|
||||
continue;
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
if (reader.peek() == JsonToken.NULL) {
|
||||
reader.skipValue();
|
||||
} else if (name.equals(VALUE)) {
|
||||
scope.setValue(reader.nextString());
|
||||
} else if (name.equals(DESCRIPTION)) {
|
||||
scope.setDescription(reader.nextString());
|
||||
} else if (name.equals(RESTRICTED)) {
|
||||
scope.setRestricted(reader.nextBoolean());
|
||||
} else if (name.equals(DEFAULT_SCOPE)) {
|
||||
scope.setDefaultScope(reader.nextBoolean());
|
||||
} else if (name.equals(ICON)) {
|
||||
scope.setIcon(reader.nextString());
|
||||
} else if (name.equals(STRUCTURED)) {
|
||||
logger.warn("Found a structured scope, ignoring structure");
|
||||
} else if (name.equals(STRUCTURED_PARAMETER)) {
|
||||
logger.warn("Found a structured scope, ignoring structure");
|
||||
} else {
|
||||
logger.debug("found unexpected entry");
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
logger.debug("Found unexpected entry");
|
||||
reader.skipValue();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
sysScopeRepository.save(scope);
|
||||
}
|
||||
reader.endArray();
|
||||
logger.info("Done reading system scopes");
|
||||
}
|
||||
|
||||
private void fixObjectReferences() {
|
||||
logger.info("Fixing object references...");
|
||||
for (Long oldRefreshTokenId : maps.getRefreshTokenToClientRefs().keySet()) {
|
||||
String clientRef = maps.getRefreshTokenToClientRefs().get(oldRefreshTokenId);
|
||||
ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef);
|
||||
Long newRefreshTokenId = maps.getRefreshTokenOldToNewIdMap().get(oldRefreshTokenId);
|
||||
OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId);
|
||||
refreshToken.setClient(client);
|
||||
tokenRepository.saveRefreshToken(refreshToken);
|
||||
}
|
||||
for (Long oldRefreshTokenId : maps.getRefreshTokenToAuthHolderRefs().keySet()) {
|
||||
Long oldAuthHolderId = maps.getRefreshTokenToAuthHolderRefs().get(oldRefreshTokenId);
|
||||
Long newAuthHolderId = maps.getAuthHolderOldToNewIdMap().get(oldAuthHolderId);
|
||||
AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId);
|
||||
Long newRefreshTokenId = maps.getRefreshTokenOldToNewIdMap().get(oldRefreshTokenId);
|
||||
OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId);
|
||||
refreshToken.setAuthenticationHolder(authHolder);
|
||||
tokenRepository.saveRefreshToken(refreshToken);
|
||||
}
|
||||
for (Long oldAccessTokenId : maps.getAccessTokenToClientRefs().keySet()) {
|
||||
String clientRef = maps.getAccessTokenToClientRefs().get(oldAccessTokenId);
|
||||
ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef);
|
||||
Long newAccessTokenId = maps.getAccessTokenOldToNewIdMap().get(oldAccessTokenId);
|
||||
OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId);
|
||||
accessToken.setClient(client);
|
||||
tokenRepository.saveAccessToken(accessToken);
|
||||
}
|
||||
for (Long oldAccessTokenId : maps.getAccessTokenToAuthHolderRefs().keySet()) {
|
||||
Long oldAuthHolderId = maps.getAccessTokenToAuthHolderRefs().get(oldAccessTokenId);
|
||||
Long newAuthHolderId = maps.getAuthHolderOldToNewIdMap().get(oldAuthHolderId);
|
||||
AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId);
|
||||
Long newAccessTokenId = maps.getAccessTokenOldToNewIdMap().get(oldAccessTokenId);
|
||||
OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId);
|
||||
accessToken.setAuthenticationHolder(authHolder);
|
||||
tokenRepository.saveAccessToken(accessToken);
|
||||
}
|
||||
for (Long oldAccessTokenId : maps.getAccessTokenToRefreshTokenRefs().keySet()) {
|
||||
Long oldRefreshTokenId = maps.getAccessTokenToRefreshTokenRefs().get(oldAccessTokenId);
|
||||
Long newRefreshTokenId = maps.getRefreshTokenOldToNewIdMap().get(oldRefreshTokenId);
|
||||
OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId);
|
||||
Long newAccessTokenId = maps.getAccessTokenOldToNewIdMap().get(oldAccessTokenId);
|
||||
OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId);
|
||||
accessToken.setRefreshToken(refreshToken);
|
||||
tokenRepository.saveAccessToken(accessToken);
|
||||
}
|
||||
for (Long oldGrantId : maps.getGrantToAccessTokensRefs().keySet()) {
|
||||
Set<Long> oldAccessTokenIds = maps.getGrantToAccessTokensRefs().get(oldGrantId);
|
||||
|
||||
Long newGrantId = maps.getGrantOldToNewIdMap().get(oldGrantId);
|
||||
ApprovedSite site = approvedSiteRepository.getById(newGrantId);
|
||||
|
||||
for(Long oldTokenId : oldAccessTokenIds) {
|
||||
Long newTokenId = maps.getAccessTokenOldToNewIdMap().get(oldTokenId);
|
||||
OAuth2AccessTokenEntity token = tokenRepository.getAccessTokenById(newTokenId);
|
||||
token.setApprovedSite(site);
|
||||
tokenRepository.saveAccessToken(token);
|
||||
}
|
||||
|
||||
approvedSiteRepository.save(site);
|
||||
}
|
||||
logger.info("Done fixing object references.");
|
||||
}
|
||||
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -1,156 +0,0 @@
|
|||
/*******************************************************************************
|
||||
* Copyright 2018 The MIT Internet Trust Consortium
|
||||
*
|
||||
* Portions copyright 2011-2013 The MITRE Corporation
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*******************************************************************************/
|
||||
package org.mitre.openid.connect.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.security.Principal;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.mitre.openid.connect.config.ConfigurationPropertiesBean;
|
||||
import org.mitre.openid.connect.service.MITREidDataService;
|
||||
import org.mitre.openid.connect.service.impl.MITREidDataService_1_3;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonToken;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
|
||||
/**
|
||||
* API endpoint for importing and exporting the current state of a server.
|
||||
* Includes all tokens, grants, whitelists, blacklists, and clients.
|
||||
*
|
||||
* @author jricher
|
||||
*
|
||||
*/
|
||||
@Controller
|
||||
@RequestMapping("/" + DataAPI.URL)
|
||||
@PreAuthorize("hasRole('ROLE_ADMIN')") // you need to be an admin to even think about this -- this is a potentially dangerous API!!
|
||||
public class DataAPI {
|
||||
|
||||
public static final String URL = RootController.API_URL + "/data";
|
||||
|
||||
/**
|
||||
* Logger for this class
|
||||
*/
|
||||
private static final Logger logger = LoggerFactory.getLogger(DataAPI.class);
|
||||
|
||||
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
|
||||
|
||||
@Autowired
|
||||
private ConfigurationPropertiesBean config;
|
||||
|
||||
@Autowired
|
||||
private List<MITREidDataService> importers;
|
||||
|
||||
private List<String> supportedVersions = ImmutableList.of(
|
||||
MITREidDataService.MITREID_CONNECT_1_0,
|
||||
MITREidDataService.MITREID_CONNECT_1_1,
|
||||
MITREidDataService.MITREID_CONNECT_1_2,
|
||||
MITREidDataService.MITREID_CONNECT_1_3);
|
||||
|
||||
@Autowired
|
||||
private MITREidDataService_1_3 exporter;
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
public String importData(Reader in, Model m) throws IOException {
|
||||
|
||||
JsonReader reader = new JsonReader(in);
|
||||
|
||||
reader.beginObject();
|
||||
|
||||
while (reader.hasNext()) {
|
||||
JsonToken tok = reader.peek();
|
||||
switch (tok) {
|
||||
case NAME:
|
||||
String name = reader.nextName();
|
||||
|
||||
if (supportedVersions.contains(name)) {
|
||||
// we're working with a known data version tag
|
||||
for (MITREidDataService dataService : importers) {
|
||||
// dispatch to the correct service
|
||||
if (dataService.supportsVersion(name)) {
|
||||
dataService.importData(reader);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// consume the next bit silently for now
|
||||
logger.debug("Skipping value for " + name); // TODO: write these out?
|
||||
reader.skipValue();
|
||||
}
|
||||
break;
|
||||
case END_OBJECT:
|
||||
break;
|
||||
case END_DOCUMENT:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
reader.endObject();
|
||||
|
||||
return "httpCodeView";
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
|
||||
public void exportData(HttpServletResponse resp, Principal prin) throws IOException {
|
||||
|
||||
resp.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
|
||||
// this writer puts things out onto the wire
|
||||
JsonWriter writer = new JsonWriter(resp.getWriter());
|
||||
writer.setIndent(" ");
|
||||
|
||||
try {
|
||||
|
||||
writer.beginObject();
|
||||
|
||||
writer.name("exported-at");
|
||||
writer.value(dateFormat.format(new Date()));
|
||||
|
||||
writer.name("exported-from");
|
||||
writer.value(config.getIssuer());
|
||||
|
||||
writer.name("exported-by");
|
||||
writer.value(prin.getName());
|
||||
|
||||
// delegate to the service to do the actual export
|
||||
exporter.exportData(writer);
|
||||
|
||||
writer.endObject(); // end root
|
||||
writer.close();
|
||||
|
||||
} catch (IOException e) {
|
||||
logger.error("Unable to export data", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,938 +0,0 @@
|
|||
/*******************************************************************************
|
||||
* Copyright 2018 The MIT Internet Trust Consortium
|
||||
*
|
||||
* Portions copyright 2011-2013 The MITRE Corporation
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*******************************************************************************/
|
||||
package org.mitre.openid.connect.service.impl;
|
||||
|
||||
import static org.mockito.Matchers.anyLong;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Matchers.isA;
|
||||
import static org.mockito.Matchers.isNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
import java.text.ParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mitre.oauth2.model.AuthenticationHolderEntity;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity;
|
||||
import org.mitre.oauth2.model.OAuth2AccessTokenEntity;
|
||||
import org.mitre.oauth2.model.OAuth2RefreshTokenEntity;
|
||||
import org.mitre.oauth2.model.SystemScope;
|
||||
import org.mitre.oauth2.repository.AuthenticationHolderRepository;
|
||||
import org.mitre.oauth2.repository.OAuth2ClientRepository;
|
||||
import org.mitre.oauth2.repository.OAuth2TokenRepository;
|
||||
import org.mitre.oauth2.repository.SystemScopeRepository;
|
||||
import org.mitre.openid.connect.model.ApprovedSite;
|
||||
import org.mitre.openid.connect.model.BlacklistedSite;
|
||||
import org.mitre.openid.connect.model.WhitelistedSite;
|
||||
import org.mitre.openid.connect.repository.ApprovedSiteRepository;
|
||||
import org.mitre.openid.connect.repository.BlacklistedSiteRepository;
|
||||
import org.mitre.openid.connect.repository.WhitelistedSiteRepository;
|
||||
import org.mitre.openid.connect.service.MITREidDataService;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.springframework.format.annotation.DateTimeFormat.ISO;
|
||||
import org.springframework.format.datetime.DateFormatter;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Request;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
import com.nimbusds.jwt.JWTParser;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.Mockito.withSettings;
|
||||
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
@SuppressWarnings(value = {"rawtypes", "unchecked"})
|
||||
public class TestMITREidDataService_1_0 {
|
||||
|
||||
@Mock
|
||||
private OAuth2ClientRepository clientRepository;
|
||||
@Mock
|
||||
private ApprovedSiteRepository approvedSiteRepository;
|
||||
@Mock
|
||||
private WhitelistedSiteRepository wlSiteRepository;
|
||||
@Mock
|
||||
private BlacklistedSiteRepository blSiteRepository;
|
||||
@Mock
|
||||
private AuthenticationHolderRepository authHolderRepository;
|
||||
@Mock
|
||||
private OAuth2TokenRepository tokenRepository;
|
||||
@Mock
|
||||
private SystemScopeRepository sysScopeRepository;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<OAuth2RefreshTokenEntity> capturedRefreshTokens;
|
||||
@Captor
|
||||
private ArgumentCaptor<OAuth2AccessTokenEntity> capturedAccessTokens;
|
||||
@Captor
|
||||
private ArgumentCaptor<ClientDetailsEntity> capturedClients;
|
||||
@Captor
|
||||
private ArgumentCaptor<BlacklistedSite> capturedBlacklistedSites;
|
||||
@Captor
|
||||
private ArgumentCaptor<WhitelistedSite> capturedWhitelistedSites;
|
||||
@Captor
|
||||
private ArgumentCaptor<ApprovedSite> capturedApprovedSites;
|
||||
@Captor
|
||||
private ArgumentCaptor<AuthenticationHolderEntity> capturedAuthHolders;
|
||||
@Captor
|
||||
private ArgumentCaptor<SystemScope> capturedScope;
|
||||
|
||||
@InjectMocks
|
||||
private MITREidDataService_1_0 dataService;
|
||||
|
||||
private DateFormatter formatter;
|
||||
|
||||
@Before
|
||||
public void prepare() {
|
||||
formatter = new DateFormatter();
|
||||
formatter.setIso(ISO.DATE_TIME);
|
||||
Mockito.reset(clientRepository, approvedSiteRepository, authHolderRepository, tokenRepository, sysScopeRepository, wlSiteRepository, blSiteRepository);
|
||||
}
|
||||
|
||||
private class refreshTokenIdComparator implements Comparator<OAuth2RefreshTokenEntity> {
|
||||
@Override
|
||||
public int compare(OAuth2RefreshTokenEntity entity1, OAuth2RefreshTokenEntity entity2) {
|
||||
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);
|
||||
|
||||
ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class);
|
||||
when(mockedClient1.getClientId()).thenReturn("mocked_client_1");
|
||||
|
||||
AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class);
|
||||
|
||||
OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity();
|
||||
token1.setId(1L);
|
||||
token1.setClient(mockedClient1);
|
||||
token1.setExpiration(expirationDate1);
|
||||
token1.setJwt(JWTParser.parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."));
|
||||
token1.setAuthenticationHolder(mockedAuthHolder1);
|
||||
|
||||
Date expirationDate2 = formatter.parse("2015-01-07T18:31:50.079+0000", Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class);
|
||||
when(mockedClient2.getClientId()).thenReturn("mocked_client_2");
|
||||
|
||||
AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class);
|
||||
|
||||
OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity();
|
||||
token2.setId(2L);
|
||||
token2.setClient(mockedClient2);
|
||||
token2.setExpiration(expirationDate2);
|
||||
token2.setJwt(JWTParser.parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."));
|
||||
token2.setAuthenticationHolder(mockedAuthHolder2);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\","
|
||||
+ "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," +
|
||||
"{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\","
|
||||
+ "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
System.err.println(configJson);
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, OAuth2RefreshTokenEntity> fakeDb = new HashMap<>();
|
||||
when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
|
||||
Long id = 343L;
|
||||
@Override
|
||||
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0];
|
||||
if(_token.getId() == null) {
|
||||
_token.setId(id++);
|
||||
}
|
||||
fakeDb.put(_token.getId(), _token);
|
||||
return _token;
|
||||
}
|
||||
});
|
||||
when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
|
||||
@Override
|
||||
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeDb.get(_id);
|
||||
}
|
||||
});
|
||||
when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer<ClientDetailsEntity>() {
|
||||
@Override
|
||||
public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
String _clientId = (String) invocation.getArguments()[0];
|
||||
ClientDetailsEntity _client = mock(ClientDetailsEntity.class);
|
||||
when(_client.getClientId()).thenReturn(_clientId);
|
||||
return _client;
|
||||
}
|
||||
});
|
||||
when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
Long id = 678L;
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class);
|
||||
id++;
|
||||
return _auth;
|
||||
}
|
||||
});
|
||||
dataService.importData(reader);
|
||||
//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());
|
||||
|
||||
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(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> {
|
||||
@Override
|
||||
public int compare(OAuth2AccessTokenEntity entity1, OAuth2AccessTokenEntity entity2) {
|
||||
return entity1.getId().compareTo(entity2.getId());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportAccessTokens() throws IOException, ParseException {
|
||||
Date expirationDate1 = formatter.parse("2014-09-10T22:49:44.090+0000", Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class);
|
||||
when(mockedClient1.getClientId()).thenReturn("mocked_client_1");
|
||||
|
||||
AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class);
|
||||
|
||||
OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity();
|
||||
token1.setId(1L);
|
||||
token1.setClient(mockedClient1);
|
||||
token1.setExpiration(expirationDate1);
|
||||
token1.setJwt(JWTParser.parse("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0"));
|
||||
token1.setAuthenticationHolder(mockedAuthHolder1);
|
||||
token1.setScope(ImmutableSet.of("id-token"));
|
||||
token1.setTokenType("Bearer");
|
||||
|
||||
String expiration2 = "2015-01-07T18:31:50.079+0000";
|
||||
Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class);
|
||||
when(mockedClient2.getClientId()).thenReturn("mocked_client_2");
|
||||
|
||||
AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class);
|
||||
|
||||
OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class);
|
||||
|
||||
OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity();
|
||||
token2.setId(2L);
|
||||
token2.setClient(mockedClient2);
|
||||
token2.setExpiration(expirationDate2);
|
||||
token2.setJwt(JWTParser.parse("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ"));
|
||||
token2.setAuthenticationHolder(mockedAuthHolder2);
|
||||
token2.setRefreshToken(mockRefreshToken2);
|
||||
token2.setScope(ImmutableSet.of("openid", "offline_access", "email", "profile"));
|
||||
token2.setTokenType("Bearer");
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\","
|
||||
+ "\"refreshTokenId\":null,\"idTokenId\":null,\"scope\":[\"id-token\"],\"type\":\"Bearer\","
|
||||
+ "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0\"}," +
|
||||
"{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\","
|
||||
+ "\"refreshTokenId\":1,\"idTokenId\":1,\"scope\":[\"openid\",\"offline_access\",\"email\",\"profile\"],\"type\":\"Bearer\","
|
||||
+ "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, OAuth2AccessTokenEntity> fakeDb = new HashMap<>();
|
||||
when(tokenRepository.saveAccessToken(isA(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
|
||||
Long id = 343L;
|
||||
@Override
|
||||
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
OAuth2AccessTokenEntity _token = (OAuth2AccessTokenEntity) invocation.getArguments()[0];
|
||||
if(_token.getId() == null) {
|
||||
_token.setId(id++);
|
||||
}
|
||||
fakeDb.put(_token.getId(), _token);
|
||||
return _token;
|
||||
}
|
||||
});
|
||||
when(tokenRepository.getAccessTokenById(anyLong())).thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
|
||||
@Override
|
||||
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeDb.get(_id);
|
||||
}
|
||||
});
|
||||
when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer<ClientDetailsEntity>() {
|
||||
@Override
|
||||
public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
String _clientId = (String) invocation.getArguments()[0];
|
||||
ClientDetailsEntity _client = mock(ClientDetailsEntity.class);
|
||||
when(_client.getClientId()).thenReturn(_clientId);
|
||||
return _client;
|
||||
}
|
||||
});
|
||||
when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
Long id = 234L;
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class);
|
||||
id++;
|
||||
return _auth;
|
||||
}
|
||||
});
|
||||
dataService.importData(reader);
|
||||
//2 times for token, 2 times to update client, 2 times to update authHolder, 1 times to update refresh token
|
||||
verify(tokenRepository, times(7)).saveAccessToken(capturedAccessTokens.capture());
|
||||
|
||||
List<OAuth2AccessTokenEntity> savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues();
|
||||
Collections.sort(savedAccessTokens, new accessTokenIdComparator());
|
||||
|
||||
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(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
|
||||
assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
|
||||
assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue()));
|
||||
}
|
||||
|
||||
|
||||
//several new client fields added in 1.1, perhaps additional tests for these should be added
|
||||
@Test
|
||||
public void testImportClients() throws IOException {
|
||||
ClientDetailsEntity client1 = new ClientDetailsEntity();
|
||||
client1.setId(1L);
|
||||
client1.setAccessTokenValiditySeconds(3600);
|
||||
client1.setClientId("client1");
|
||||
client1.setClientSecret("clientsecret1");
|
||||
client1.setRedirectUris(ImmutableSet.of("http://foo.com/"));
|
||||
client1.setScope(ImmutableSet.of("foo", "bar", "baz", "dolphin"));
|
||||
client1.setGrantTypes(ImmutableSet.of("implicit", "authorization_code", "urn:ietf:params:oauth:grant_type:redelegate", "refresh_token"));
|
||||
client1.setAllowIntrospection(true);
|
||||
|
||||
ClientDetailsEntity client2 = new ClientDetailsEntity();
|
||||
client2.setId(2L);
|
||||
client2.setAccessTokenValiditySeconds(3600);
|
||||
client2.setClientId("client2");
|
||||
client2.setClientSecret("clientsecret2");
|
||||
client2.setRedirectUris(ImmutableSet.of("http://bar.baz.com/"));
|
||||
client2.setScope(ImmutableSet.of("foo", "dolphin", "electric-wombat"));
|
||||
client2.setGrantTypes(ImmutableSet.of("client_credentials", "urn:ietf:params:oauth:grant_type:redelegate"));
|
||||
client2.setAllowIntrospection(false);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"accessTokenValiditySeconds\":3600,\"clientId\":\"client1\",\"secret\":\"clientsecret1\","
|
||||
+ "\"redirectUris\":[\"http://foo.com/\"],"
|
||||
+ "\"scope\":[\"foo\",\"bar\",\"baz\",\"dolphin\"],"
|
||||
+ "\"grantTypes\":[\"implicit\",\"authorization_code\",\"urn:ietf:params:oauth:grant_type:redelegate\",\"refresh_token\"],"
|
||||
+ "\"allowIntrospection\":true}," +
|
||||
"{\"id\":2,\"accessTokenValiditySeconds\":3600,\"clientId\":\"client2\",\"secret\":\"clientsecret2\","
|
||||
+ "\"redirectUris\":[\"http://bar.baz.com/\"],"
|
||||
+ "\"scope\":[\"foo\",\"dolphin\",\"electric-wombat\"],"
|
||||
+ "\"grantTypes\":[\"client_credentials\",\"urn:ietf:params:oauth:grant_type:redelegate\"],"
|
||||
+ "\"allowIntrospection\":false}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(clientRepository, times(2)).saveClient(capturedClients.capture());
|
||||
|
||||
List<ClientDetailsEntity> savedClients = capturedClients.getAllValues();
|
||||
|
||||
assertThat(savedClients.size(), is(2));
|
||||
|
||||
assertThat(savedClients.get(0).getAccessTokenValiditySeconds(), equalTo(client1.getAccessTokenValiditySeconds()));
|
||||
assertThat(savedClients.get(0).getClientId(), equalTo(client1.getClientId()));
|
||||
assertThat(savedClients.get(0).getClientSecret(), equalTo(client1.getClientSecret()));
|
||||
assertThat(savedClients.get(0).getRedirectUris(), equalTo(client1.getRedirectUris()));
|
||||
assertThat(savedClients.get(0).getScope(), equalTo(client1.getScope()));
|
||||
assertThat(savedClients.get(0).getGrantTypes(), equalTo(client1.getGrantTypes()));
|
||||
assertThat(savedClients.get(0).isAllowIntrospection(), equalTo(client1.isAllowIntrospection()));
|
||||
|
||||
assertThat(savedClients.get(1).getAccessTokenValiditySeconds(), equalTo(client2.getAccessTokenValiditySeconds()));
|
||||
assertThat(savedClients.get(1).getClientId(), equalTo(client2.getClientId()));
|
||||
assertThat(savedClients.get(1).getClientSecret(), equalTo(client2.getClientSecret()));
|
||||
assertThat(savedClients.get(1).getRedirectUris(), equalTo(client2.getRedirectUris()));
|
||||
assertThat(savedClients.get(1).getScope(), equalTo(client2.getScope()));
|
||||
assertThat(savedClients.get(1).getGrantTypes(), equalTo(client2.getGrantTypes()));
|
||||
assertThat(savedClients.get(1).isAllowIntrospection(), equalTo(client2.isAllowIntrospection()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportBlacklistedSites() throws IOException {
|
||||
BlacklistedSite site1 = new BlacklistedSite();
|
||||
site1.setId(1L);
|
||||
site1.setUri("http://foo.com");
|
||||
|
||||
BlacklistedSite site2 = new BlacklistedSite();
|
||||
site2.setId(2L);
|
||||
site2.setUri("http://bar.com");
|
||||
|
||||
BlacklistedSite site3 = new BlacklistedSite();
|
||||
site3.setId(3L);
|
||||
site3.setUri("http://baz.com");
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [" +
|
||||
|
||||
"{\"id\":1,\"uri\":\"http://foo.com\"}," +
|
||||
"{\"id\":2,\"uri\":\"http://bar.com\"}," +
|
||||
"{\"id\":3,\"uri\":\"http://baz.com\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(blSiteRepository, times(3)).save(capturedBlacklistedSites.capture());
|
||||
|
||||
List<BlacklistedSite> savedSites = capturedBlacklistedSites.getAllValues();
|
||||
|
||||
assertThat(savedSites.size(), is(3));
|
||||
|
||||
assertThat(savedSites.get(0).getUri(), equalTo(site1.getUri()));
|
||||
assertThat(savedSites.get(1).getUri(), equalTo(site2.getUri()));
|
||||
assertThat(savedSites.get(2).getUri(), equalTo(site3.getUri()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportWhitelistedSites() throws IOException {
|
||||
WhitelistedSite site1 = new WhitelistedSite();
|
||||
site1.setId(1L);
|
||||
site1.setClientId("foo");
|
||||
|
||||
WhitelistedSite site2 = new WhitelistedSite();
|
||||
site2.setId(2L);
|
||||
site2.setClientId("bar");
|
||||
|
||||
WhitelistedSite site3 = new WhitelistedSite();
|
||||
site3.setId(3L);
|
||||
site3.setClientId("baz");
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"foo\"}," +
|
||||
"{\"id\":2,\"clientId\":\"bar\"}," +
|
||||
"{\"id\":3,\"clientId\":\"baz\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, WhitelistedSite> fakeDb = new HashMap<>();
|
||||
when(wlSiteRepository.save(isA(WhitelistedSite.class))).thenAnswer(new Answer<WhitelistedSite>() {
|
||||
Long id = 345L;
|
||||
@Override
|
||||
public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable {
|
||||
WhitelistedSite _site = (WhitelistedSite) invocation.getArguments()[0];
|
||||
if(_site.getId() == null) {
|
||||
_site.setId(id++);
|
||||
}
|
||||
fakeDb.put(_site.getId(), _site);
|
||||
return _site;
|
||||
}
|
||||
});
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(wlSiteRepository, times(3)).save(capturedWhitelistedSites.capture());
|
||||
|
||||
List<WhitelistedSite> savedSites = capturedWhitelistedSites.getAllValues();
|
||||
|
||||
assertThat(savedSites.size(), is(3));
|
||||
|
||||
assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId()));
|
||||
assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId()));
|
||||
assertThat(savedSites.get(2).getClientId(), equalTo(site3.getClientId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportGrants() throws IOException, ParseException {
|
||||
Date creationDate1 = formatter.parse("2014-09-10T22:49:44.090+0000", Locale.ENGLISH);
|
||||
Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+0000", Locale.ENGLISH);
|
||||
|
||||
OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class);
|
||||
ApprovedSite site1 = new ApprovedSite();
|
||||
site1.setId(1L);
|
||||
site1.setClientId("foo");
|
||||
site1.setCreationDate(creationDate1);
|
||||
site1.setAccessDate(accessDate1);
|
||||
site1.setUserId("user1");
|
||||
site1.setAllowedScopes(ImmutableSet.of("openid", "phone"));
|
||||
|
||||
Date creationDate2 = formatter.parse("2014-09-11T18:49:44.090+0000", Locale.ENGLISH);
|
||||
Date accessDate2 = formatter.parse("2014-09-11T20:49:44.090+0000", Locale.ENGLISH);
|
||||
Date timeoutDate2 = formatter.parse("2014-10-01T20:49:44.090+0000", Locale.ENGLISH);
|
||||
|
||||
ApprovedSite site2 = new ApprovedSite();
|
||||
site2.setId(2L);
|
||||
site2.setClientId("bar");
|
||||
site2.setCreationDate(creationDate2);
|
||||
site2.setAccessDate(accessDate2);
|
||||
site2.setUserId("user2");
|
||||
site2.setAllowedScopes(ImmutableSet.of("openid", "offline_access", "email", "profile"));
|
||||
site2.setTimeoutDate(timeoutDate2);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"foo\",\"creationDate\":\"2014-09-10T22:49:44.090+0000\",\"accessDate\":\"2014-09-10T23:49:44.090+0000\","
|
||||
+ "\"userId\":\"user1\",\"whitelistedSiteId\":null,\"allowedScopes\":[\"openid\",\"phone\"], \"whitelistedSiteId\":1,"
|
||||
+ "\"approvedAccessTokens\":[1]}," +
|
||||
"{\"id\":2,\"clientId\":\"bar\",\"creationDate\":\"2014-09-11T18:49:44.090+0000\",\"accessDate\":\"2014-09-11T20:49:44.090+0000\","
|
||||
+ "\"timeoutDate\":\"2014-10-01T20:49:44.090+0000\",\"userId\":\"user2\","
|
||||
+ "\"allowedScopes\":[\"openid\",\"offline_access\",\"email\",\"profile\"]}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, ApprovedSite> fakeDb = new HashMap<>();
|
||||
when(approvedSiteRepository.save(isA(ApprovedSite.class))).thenAnswer(new Answer<ApprovedSite>() {
|
||||
Long id = 343L;
|
||||
@Override
|
||||
public ApprovedSite answer(InvocationOnMock invocation) throws Throwable {
|
||||
ApprovedSite _site = (ApprovedSite) invocation.getArguments()[0];
|
||||
if(_site.getId() == null) {
|
||||
_site.setId(id++);
|
||||
}
|
||||
fakeDb.put(_site.getId(), _site);
|
||||
return _site;
|
||||
}
|
||||
});
|
||||
when(approvedSiteRepository.getById(anyLong())).thenAnswer(new Answer<ApprovedSite>() {
|
||||
@Override
|
||||
public ApprovedSite answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeDb.get(_id);
|
||||
}
|
||||
});
|
||||
when(tokenRepository.getAccessTokenById(isNull(Long.class))).thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
|
||||
Long id = 221L;
|
||||
@Override
|
||||
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
return mock(OAuth2AccessTokenEntity.class);
|
||||
}
|
||||
});
|
||||
|
||||
dataService.importData(reader);
|
||||
//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());
|
||||
|
||||
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(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()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportAuthenticationHolders() throws IOException {
|
||||
OAuth2Request req1 = new OAuth2Request(new HashMap<String, String>(), "client1", new ArrayList<GrantedAuthority>(),
|
||||
true, new HashSet<String>(), new HashSet<String>(), "http://foo.com",
|
||||
new HashSet<String>(), null);
|
||||
Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable());
|
||||
OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1);
|
||||
|
||||
AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity();
|
||||
holder1.setId(1L);
|
||||
holder1.setAuthentication(auth1);
|
||||
|
||||
OAuth2Request req2 = new OAuth2Request(new HashMap<String, String>(), "client2", new ArrayList<GrantedAuthority>(),
|
||||
true, new HashSet<String>(), new HashSet<String>(), "http://bar.com",
|
||||
new HashSet<String>(), null);
|
||||
Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable());
|
||||
OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2);
|
||||
|
||||
AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity();
|
||||
holder2.setId(2L);
|
||||
holder2.setAuthentication(auth2);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client1\",\"redirectUri\":\"http://foo.com\"},"
|
||||
+ "\"userAuthentication\":null}}," +
|
||||
"{\"id\":2,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client2\",\"redirectUri\":\"http://bar.com\"},"
|
||||
+ "\"userAuthentication\":null}}" +
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, AuthenticationHolderEntity> fakeDb = new HashMap<>();
|
||||
when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
Long id = 356L;
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
AuthenticationHolderEntity _holder = (AuthenticationHolderEntity) invocation.getArguments()[0];
|
||||
if(_holder.getId() == null) {
|
||||
_holder.setId(id++);
|
||||
}
|
||||
fakeDb.put(_holder.getId(), _holder);
|
||||
return _holder;
|
||||
}
|
||||
});
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(authHolderRepository, times(2)).save(capturedAuthHolders.capture());
|
||||
|
||||
List<AuthenticationHolderEntity> savedAuthHolders = capturedAuthHolders.getAllValues();
|
||||
|
||||
assertThat(savedAuthHolders.size(), is(2));
|
||||
assertThat(savedAuthHolders.get(0).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder1.getAuthentication().getOAuth2Request().getClientId()));
|
||||
assertThat(savedAuthHolders.get(1).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder2.getAuthentication().getOAuth2Request().getClientId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportSystemScopes() throws IOException {
|
||||
SystemScope scope1 = new SystemScope();
|
||||
scope1.setId(1L);
|
||||
scope1.setValue("scope1");
|
||||
scope1.setDescription("Scope 1");
|
||||
scope1.setRestricted(true);
|
||||
scope1.setDefaultScope(false);
|
||||
scope1.setIcon("glass");
|
||||
|
||||
SystemScope scope2 = new SystemScope();
|
||||
scope2.setId(2L);
|
||||
scope2.setValue("scope2");
|
||||
scope2.setDescription("Scope 2");
|
||||
scope2.setRestricted(false);
|
||||
scope2.setDefaultScope(false);
|
||||
scope2.setIcon("ball");
|
||||
|
||||
SystemScope scope3 = new SystemScope();
|
||||
scope3.setId(3L);
|
||||
scope3.setValue("scope3");
|
||||
scope3.setDescription("Scope 3");
|
||||
scope3.setRestricted(false);
|
||||
scope3.setDefaultScope(true);
|
||||
scope3.setIcon("road");
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [" +
|
||||
|
||||
"{\"id\":1,\"description\":\"Scope 1\",\"icon\":\"glass\",\"value\":\"scope1\",\"allowDynReg\":false,\"defaultScope\":false}," +
|
||||
"{\"id\":2,\"description\":\"Scope 2\",\"icon\":\"ball\",\"value\":\"scope2\",\"allowDynReg\":true,\"defaultScope\":false}," +
|
||||
"{\"id\":3,\"description\":\"Scope 3\",\"icon\":\"road\",\"value\":\"scope3\",\"allowDynReg\":true,\"defaultScope\":true}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(sysScopeRepository, times(3)).save(capturedScope.capture());
|
||||
|
||||
List<SystemScope> savedScopes = capturedScope.getAllValues();
|
||||
|
||||
assertThat(savedScopes.size(), is(3));
|
||||
assertThat(savedScopes.get(0).getValue(), equalTo(scope1.getValue()));
|
||||
assertThat(savedScopes.get(0).getDescription(), equalTo(scope1.getDescription()));
|
||||
assertThat(savedScopes.get(0).getIcon(), equalTo(scope1.getIcon()));
|
||||
assertThat(savedScopes.get(0).isDefaultScope(), equalTo(scope1.isDefaultScope()));
|
||||
assertThat(savedScopes.get(0).isRestricted(), equalTo(scope1.isRestricted()));
|
||||
|
||||
assertThat(savedScopes.get(1).getValue(), equalTo(scope2.getValue()));
|
||||
assertThat(savedScopes.get(1).getDescription(), equalTo(scope2.getDescription()));
|
||||
assertThat(savedScopes.get(1).getIcon(), equalTo(scope2.getIcon()));
|
||||
assertThat(savedScopes.get(1).isDefaultScope(), equalTo(scope2.isDefaultScope()));
|
||||
assertThat(savedScopes.get(1).isRestricted(), equalTo(scope2.isRestricted()));
|
||||
|
||||
assertThat(savedScopes.get(2).getValue(), equalTo(scope3.getValue()));
|
||||
assertThat(savedScopes.get(2).getDescription(), equalTo(scope3.getDescription()));
|
||||
assertThat(savedScopes.get(2).getIcon(), equalTo(scope3.getIcon()));
|
||||
assertThat(savedScopes.get(2).isDefaultScope(), equalTo(scope3.isDefaultScope()));
|
||||
assertThat(savedScopes.get(2).isRestricted(), equalTo(scope3.isRestricted()));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException, ParseException {
|
||||
String expiration1 = "2014-09-10T22:49:44.090+0000";
|
||||
Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class);
|
||||
|
||||
OAuth2Request req1 = new OAuth2Request(new HashMap<String, String>(), "client1", new ArrayList<GrantedAuthority>(),
|
||||
true, new HashSet<String>(), new HashSet<String>(), "http://foo.com",
|
||||
new HashSet<String>(), null);
|
||||
Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable());
|
||||
OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1);
|
||||
|
||||
AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity();
|
||||
holder1.setId(1L);
|
||||
holder1.setAuthentication(auth1);
|
||||
|
||||
OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity();
|
||||
token1.setId(1L);
|
||||
token1.setClient(mockedClient1);
|
||||
token1.setExpiration(expirationDate1);
|
||||
token1.setJwt(JWTParser.parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."));
|
||||
token1.setAuthenticationHolder(holder1);
|
||||
|
||||
String expiration2 = "2015-01-07T18:31:50.079+0000";
|
||||
Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class);
|
||||
|
||||
OAuth2Request req2 = new OAuth2Request(new HashMap<String, String>(), "client2", new ArrayList<GrantedAuthority>(),
|
||||
true, new HashSet<String>(), new HashSet<String>(), "http://bar.com",
|
||||
new HashSet<String>(), null);
|
||||
Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable());
|
||||
OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2);
|
||||
|
||||
AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity();
|
||||
holder2.setId(2L);
|
||||
holder2.setAuthentication(auth2);
|
||||
|
||||
OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity();
|
||||
token2.setId(2L);
|
||||
token2.setClient(mockedClient2);
|
||||
token2.setExpiration(expirationDate2);
|
||||
token2.setJwt(JWTParser.parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."));
|
||||
token2.setAuthenticationHolder(holder2);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client1\",\"redirectUri\":\"http://foo.com\"},"
|
||||
+ "\"userAuthentication\":null}}," +
|
||||
"{\"id\":2,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client2\",\"redirectUri\":\"http://bar.com\"},"
|
||||
+ "\"userAuthentication\":null}}" +
|
||||
" ]," +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\","
|
||||
+ "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," +
|
||||
"{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\","
|
||||
+ "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
final Map<Long, OAuth2RefreshTokenEntity> fakeRefreshTokenTable = new HashMap<>();
|
||||
final Map<Long, AuthenticationHolderEntity> fakeAuthHolderTable = new HashMap<>();
|
||||
when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
|
||||
Long id = 343L;
|
||||
@Override
|
||||
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0];
|
||||
if(_token.getId() == null) {
|
||||
_token.setId(id++);
|
||||
}
|
||||
fakeRefreshTokenTable.put(_token.getId(), _token);
|
||||
return _token;
|
||||
}
|
||||
});
|
||||
when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
|
||||
@Override
|
||||
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeRefreshTokenTable.get(_id);
|
||||
}
|
||||
});
|
||||
when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer<ClientDetailsEntity>() {
|
||||
@Override
|
||||
public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
String _clientId = (String) invocation.getArguments()[0];
|
||||
ClientDetailsEntity _client = mock(ClientDetailsEntity.class);
|
||||
return _client;
|
||||
}
|
||||
});
|
||||
when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
Long id = 356L;
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
AuthenticationHolderEntity _holder = (AuthenticationHolderEntity) invocation.getArguments()[0];
|
||||
if(_holder.getId() == null) {
|
||||
_holder.setId(id++);
|
||||
}
|
||||
fakeAuthHolderTable.put(_holder.getId(), _holder);
|
||||
return _holder;
|
||||
}
|
||||
});
|
||||
when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeAuthHolderTable.get(_id);
|
||||
}
|
||||
});
|
||||
dataService.importData(reader);
|
||||
|
||||
List<OAuth2RefreshTokenEntity> savedRefreshTokens = new ArrayList(fakeRefreshTokenTable.values()); //capturedRefreshTokens.getAllValues();
|
||||
Collections.sort(savedRefreshTokens, new refreshTokenIdComparator());
|
||||
|
||||
assertThat(savedRefreshTokens.get(0).getAuthenticationHolder().getId(), equalTo(356L));
|
||||
assertThat(savedRefreshTokens.get(1).getAuthenticationHolder().getId(), equalTo(357L));
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void testExportDisabled() throws IOException {
|
||||
JsonWriter writer = new JsonWriter(new StringWriter());
|
||||
dataService.exportData(writer);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,943 +0,0 @@
|
|||
/*******************************************************************************
|
||||
* Copyright 2018 The MIT Internet Trust Consortium
|
||||
*
|
||||
* Portions copyright 2011-2013 The MITRE Corporation
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*******************************************************************************/
|
||||
package org.mitre.openid.connect.service.impl;
|
||||
|
||||
import static org.mockito.Matchers.anyLong;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Matchers.isA;
|
||||
import static org.mockito.Matchers.isNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
import java.text.ParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mitre.oauth2.model.AuthenticationHolderEntity;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity;
|
||||
import org.mitre.oauth2.model.OAuth2AccessTokenEntity;
|
||||
import org.mitre.oauth2.model.OAuth2RefreshTokenEntity;
|
||||
import org.mitre.oauth2.model.SystemScope;
|
||||
import org.mitre.oauth2.repository.AuthenticationHolderRepository;
|
||||
import org.mitre.oauth2.repository.OAuth2ClientRepository;
|
||||
import org.mitre.oauth2.repository.OAuth2TokenRepository;
|
||||
import org.mitre.oauth2.repository.SystemScopeRepository;
|
||||
import org.mitre.openid.connect.model.ApprovedSite;
|
||||
import org.mitre.openid.connect.model.BlacklistedSite;
|
||||
import org.mitre.openid.connect.model.WhitelistedSite;
|
||||
import org.mitre.openid.connect.repository.ApprovedSiteRepository;
|
||||
import org.mitre.openid.connect.repository.BlacklistedSiteRepository;
|
||||
import org.mitre.openid.connect.repository.WhitelistedSiteRepository;
|
||||
import org.mitre.openid.connect.service.MITREidDataService;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.springframework.format.annotation.DateTimeFormat.ISO;
|
||||
import org.springframework.format.datetime.DateFormatter;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Request;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
import com.nimbusds.jwt.JWTParser;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.Mockito.withSettings;
|
||||
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
@SuppressWarnings(value = {"rawtypes", "unchecked"})
|
||||
public class TestMITREidDataService_1_1 {
|
||||
|
||||
@Mock
|
||||
private OAuth2ClientRepository clientRepository;
|
||||
@Mock
|
||||
private ApprovedSiteRepository approvedSiteRepository;
|
||||
@Mock
|
||||
private WhitelistedSiteRepository wlSiteRepository;
|
||||
@Mock
|
||||
private BlacklistedSiteRepository blSiteRepository;
|
||||
@Mock
|
||||
private AuthenticationHolderRepository authHolderRepository;
|
||||
@Mock
|
||||
private OAuth2TokenRepository tokenRepository;
|
||||
@Mock
|
||||
private SystemScopeRepository sysScopeRepository;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<OAuth2RefreshTokenEntity> capturedRefreshTokens;
|
||||
@Captor
|
||||
private ArgumentCaptor<OAuth2AccessTokenEntity> capturedAccessTokens;
|
||||
@Captor
|
||||
private ArgumentCaptor<ClientDetailsEntity> capturedClients;
|
||||
@Captor
|
||||
private ArgumentCaptor<BlacklistedSite> capturedBlacklistedSites;
|
||||
@Captor
|
||||
private ArgumentCaptor<WhitelistedSite> capturedWhitelistedSites;
|
||||
@Captor
|
||||
private ArgumentCaptor<ApprovedSite> capturedApprovedSites;
|
||||
@Captor
|
||||
private ArgumentCaptor<AuthenticationHolderEntity> capturedAuthHolders;
|
||||
@Captor
|
||||
private ArgumentCaptor<SystemScope> capturedScope;
|
||||
|
||||
@InjectMocks
|
||||
private MITREidDataService_1_1 dataService;
|
||||
private DateFormatter formatter;
|
||||
|
||||
@Before
|
||||
public void prepare() {
|
||||
formatter = new DateFormatter();
|
||||
formatter.setIso(ISO.DATE_TIME);
|
||||
|
||||
Mockito.reset(clientRepository, approvedSiteRepository, authHolderRepository, tokenRepository, sysScopeRepository, wlSiteRepository, blSiteRepository);
|
||||
}
|
||||
|
||||
|
||||
private class refreshTokenIdComparator implements Comparator<OAuth2RefreshTokenEntity> {
|
||||
@Override
|
||||
public int compare(OAuth2RefreshTokenEntity entity1, OAuth2RefreshTokenEntity entity2) {
|
||||
return entity1.getId().compareTo(entity2.getId());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testImportRefreshTokens() throws IOException, ParseException {
|
||||
String expiration1 = "2014-09-10T22:49:44.090+0000";
|
||||
Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class);
|
||||
when(mockedClient1.getClientId()).thenReturn("mocked_client_1");
|
||||
|
||||
AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class);
|
||||
|
||||
OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity();
|
||||
token1.setId(1L);
|
||||
token1.setClient(mockedClient1);
|
||||
token1.setExpiration(expirationDate1);
|
||||
token1.setJwt(JWTParser.parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."));
|
||||
token1.setAuthenticationHolder(mockedAuthHolder1);
|
||||
|
||||
String expiration2 = "2015-01-07T18:31:50.079+0000";
|
||||
Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class);
|
||||
when(mockedClient2.getClientId()).thenReturn("mocked_client_2");
|
||||
|
||||
AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class);
|
||||
|
||||
OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity();
|
||||
token2.setId(2L);
|
||||
token2.setClient(mockedClient2);
|
||||
token2.setExpiration(expirationDate2);
|
||||
token2.setJwt(JWTParser.parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."));
|
||||
token2.setAuthenticationHolder(mockedAuthHolder2);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\","
|
||||
+ "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," +
|
||||
"{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\","
|
||||
+ "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
System.err.println(configJson);
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, OAuth2RefreshTokenEntity> fakeDb = new HashMap<>();
|
||||
when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
|
||||
Long id = 332L;
|
||||
@Override
|
||||
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0];
|
||||
if(_token.getId() == null) {
|
||||
_token.setId(id++);
|
||||
}
|
||||
fakeDb.put(_token.getId(), _token);
|
||||
return _token;
|
||||
}
|
||||
});
|
||||
when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
|
||||
@Override
|
||||
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeDb.get(_id);
|
||||
}
|
||||
});
|
||||
when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer<ClientDetailsEntity>() {
|
||||
@Override
|
||||
public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
String _clientId = (String) invocation.getArguments()[0];
|
||||
ClientDetailsEntity _client = mock(ClientDetailsEntity.class);
|
||||
when(_client.getClientId()).thenReturn(_clientId);
|
||||
return _client;
|
||||
}
|
||||
});
|
||||
when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
Long id = 131L;
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class);
|
||||
id++;
|
||||
return _auth;
|
||||
}
|
||||
});
|
||||
dataService.importData(reader);
|
||||
//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());
|
||||
|
||||
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(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> {
|
||||
@Override
|
||||
public int compare(OAuth2AccessTokenEntity entity1, OAuth2AccessTokenEntity entity2) {
|
||||
return entity1.getId().compareTo(entity2.getId());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportAccessTokens() throws IOException, ParseException {
|
||||
String expiration1 = "2014-09-10T22:49:44.090+0000";
|
||||
Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class);
|
||||
when(mockedClient1.getClientId()).thenReturn("mocked_client_1");
|
||||
|
||||
AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class);
|
||||
|
||||
OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity();
|
||||
token1.setId(1L);
|
||||
token1.setClient(mockedClient1);
|
||||
token1.setExpiration(expirationDate1);
|
||||
token1.setJwt(JWTParser.parse("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0"));
|
||||
token1.setAuthenticationHolder(mockedAuthHolder1);
|
||||
token1.setScope(ImmutableSet.of("id-token"));
|
||||
token1.setTokenType("Bearer");
|
||||
|
||||
String expiration2 = "2015-01-07T18:31:50.079+0000";
|
||||
Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class);
|
||||
when(mockedClient2.getClientId()).thenReturn("mocked_client_2");
|
||||
|
||||
AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class);
|
||||
|
||||
OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class);
|
||||
|
||||
OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity();
|
||||
token2.setId(2L);
|
||||
token2.setClient(mockedClient2);
|
||||
token2.setExpiration(expirationDate2);
|
||||
token2.setJwt(JWTParser.parse("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ"));
|
||||
token2.setAuthenticationHolder(mockedAuthHolder2);
|
||||
token2.setRefreshToken(mockRefreshToken2);
|
||||
token2.setScope(ImmutableSet.of("openid", "offline_access", "email", "profile"));
|
||||
token2.setTokenType("Bearer");
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\","
|
||||
+ "\"refreshTokenId\":null,\"idTokenId\":null,\"scope\":[\"id-token\"],\"type\":\"Bearer\","
|
||||
+ "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0\"}," +
|
||||
"{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\","
|
||||
+ "\"refreshTokenId\":1,\"idTokenId\":1,\"scope\":[\"openid\",\"offline_access\",\"email\",\"profile\"],\"type\":\"Bearer\","
|
||||
+ "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, OAuth2AccessTokenEntity> fakeDb = new HashMap<>();
|
||||
when(tokenRepository.saveAccessToken(isA(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
|
||||
Long id = 324L;
|
||||
@Override
|
||||
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
OAuth2AccessTokenEntity _token = (OAuth2AccessTokenEntity) invocation.getArguments()[0];
|
||||
if(_token.getId() == null) {
|
||||
_token.setId(id++);
|
||||
}
|
||||
fakeDb.put(_token.getId(), _token);
|
||||
return _token;
|
||||
}
|
||||
});
|
||||
when(tokenRepository.getAccessTokenById(anyLong())).thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
|
||||
@Override
|
||||
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeDb.get(_id);
|
||||
}
|
||||
});
|
||||
when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer<ClientDetailsEntity>() {
|
||||
@Override
|
||||
public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
String _clientId = (String) invocation.getArguments()[0];
|
||||
ClientDetailsEntity _client = mock(ClientDetailsEntity.class);
|
||||
when(_client.getClientId()).thenReturn(_clientId);
|
||||
return _client;
|
||||
}
|
||||
});
|
||||
when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
Long id = 133L;
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class);
|
||||
id++;
|
||||
return _auth;
|
||||
}
|
||||
});
|
||||
dataService.importData(reader);
|
||||
//2 times for token, 2 times to update client, 2 times to update authHolder, 1 times to update refresh token
|
||||
verify(tokenRepository, times(7)).saveAccessToken(capturedAccessTokens.capture());
|
||||
|
||||
List<OAuth2AccessTokenEntity> savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues();
|
||||
Collections.sort(savedAccessTokens, new accessTokenIdComparator());
|
||||
|
||||
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(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
|
||||
assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
|
||||
assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportClients() throws IOException {
|
||||
ClientDetailsEntity client1 = new ClientDetailsEntity();
|
||||
client1.setId(1L);
|
||||
client1.setAccessTokenValiditySeconds(3600);
|
||||
client1.setClientId("client1");
|
||||
client1.setClientSecret("clientsecret1");
|
||||
client1.setRedirectUris(ImmutableSet.of("http://foo.com/"));
|
||||
client1.setScope(ImmutableSet.of("foo", "bar", "baz", "dolphin"));
|
||||
client1.setGrantTypes(ImmutableSet.of("implicit", "authorization_code", "urn:ietf:params:oauth:grant_type:redelegate", "refresh_token"));
|
||||
client1.setAllowIntrospection(true);
|
||||
|
||||
ClientDetailsEntity client2 = new ClientDetailsEntity();
|
||||
client2.setId(2L);
|
||||
client2.setAccessTokenValiditySeconds(3600);
|
||||
client2.setClientId("client2");
|
||||
client2.setClientSecret("clientsecret2");
|
||||
client2.setRedirectUris(ImmutableSet.of("http://bar.baz.com/"));
|
||||
client2.setScope(ImmutableSet.of("foo", "dolphin", "electric-wombat"));
|
||||
client2.setGrantTypes(ImmutableSet.of("client_credentials", "urn:ietf:params:oauth:grant_type:redelegate"));
|
||||
client2.setAllowIntrospection(false);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"accessTokenValiditySeconds\":3600,\"clientId\":\"client1\",\"secret\":\"clientsecret1\","
|
||||
+ "\"redirectUris\":[\"http://foo.com/\"],"
|
||||
+ "\"scope\":[\"foo\",\"bar\",\"baz\",\"dolphin\"],"
|
||||
+ "\"grantTypes\":[\"implicit\",\"authorization_code\",\"urn:ietf:params:oauth:grant_type:redelegate\",\"refresh_token\"],"
|
||||
+ "\"allowIntrospection\":true}," +
|
||||
"{\"id\":2,\"accessTokenValiditySeconds\":3600,\"clientId\":\"client2\",\"secret\":\"clientsecret2\","
|
||||
+ "\"redirectUris\":[\"http://bar.baz.com/\"],"
|
||||
+ "\"scope\":[\"foo\",\"dolphin\",\"electric-wombat\"],"
|
||||
+ "\"grantTypes\":[\"client_credentials\",\"urn:ietf:params:oauth:grant_type:redelegate\"],"
|
||||
+ "\"allowIntrospection\":false}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(clientRepository, times(2)).saveClient(capturedClients.capture());
|
||||
|
||||
List<ClientDetailsEntity> savedClients = capturedClients.getAllValues();
|
||||
|
||||
assertThat(savedClients.size(), is(2));
|
||||
|
||||
assertThat(savedClients.get(0).getAccessTokenValiditySeconds(), equalTo(client1.getAccessTokenValiditySeconds()));
|
||||
assertThat(savedClients.get(0).getClientId(), equalTo(client1.getClientId()));
|
||||
assertThat(savedClients.get(0).getClientSecret(), equalTo(client1.getClientSecret()));
|
||||
assertThat(savedClients.get(0).getRedirectUris(), equalTo(client1.getRedirectUris()));
|
||||
assertThat(savedClients.get(0).getScope(), equalTo(client1.getScope()));
|
||||
assertThat(savedClients.get(0).getGrantTypes(), equalTo(client1.getGrantTypes()));
|
||||
assertThat(savedClients.get(0).isAllowIntrospection(), equalTo(client1.isAllowIntrospection()));
|
||||
|
||||
assertThat(savedClients.get(1).getAccessTokenValiditySeconds(), equalTo(client2.getAccessTokenValiditySeconds()));
|
||||
assertThat(savedClients.get(1).getClientId(), equalTo(client2.getClientId()));
|
||||
assertThat(savedClients.get(1).getClientSecret(), equalTo(client2.getClientSecret()));
|
||||
assertThat(savedClients.get(1).getRedirectUris(), equalTo(client2.getRedirectUris()));
|
||||
assertThat(savedClients.get(1).getScope(), equalTo(client2.getScope()));
|
||||
assertThat(savedClients.get(1).getGrantTypes(), equalTo(client2.getGrantTypes()));
|
||||
assertThat(savedClients.get(1).isAllowIntrospection(), equalTo(client2.isAllowIntrospection()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportBlacklistedSites() throws IOException {
|
||||
BlacklistedSite site1 = new BlacklistedSite();
|
||||
site1.setId(1L);
|
||||
site1.setUri("http://foo.com");
|
||||
|
||||
BlacklistedSite site2 = new BlacklistedSite();
|
||||
site2.setId(2L);
|
||||
site2.setUri("http://bar.com");
|
||||
|
||||
BlacklistedSite site3 = new BlacklistedSite();
|
||||
site3.setId(3L);
|
||||
site3.setUri("http://baz.com");
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [" +
|
||||
|
||||
"{\"id\":1,\"uri\":\"http://foo.com\"}," +
|
||||
"{\"id\":2,\"uri\":\"http://bar.com\"}," +
|
||||
"{\"id\":3,\"uri\":\"http://baz.com\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(blSiteRepository, times(3)).save(capturedBlacklistedSites.capture());
|
||||
|
||||
List<BlacklistedSite> savedSites = capturedBlacklistedSites.getAllValues();
|
||||
|
||||
assertThat(savedSites.size(), is(3));
|
||||
|
||||
assertThat(savedSites.get(0).getUri(), equalTo(site1.getUri()));
|
||||
assertThat(savedSites.get(1).getUri(), equalTo(site2.getUri()));
|
||||
assertThat(savedSites.get(2).getUri(), equalTo(site3.getUri()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportWhitelistedSites() throws IOException {
|
||||
WhitelistedSite site1 = new WhitelistedSite();
|
||||
site1.setId(1L);
|
||||
site1.setClientId("foo");
|
||||
|
||||
WhitelistedSite site2 = new WhitelistedSite();
|
||||
site2.setId(2L);
|
||||
site2.setClientId("bar");
|
||||
|
||||
WhitelistedSite site3 = new WhitelistedSite();
|
||||
site3.setId(3L);
|
||||
site3.setClientId("baz");
|
||||
//site3.setAllowedScopes(null);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"foo\"}," +
|
||||
"{\"id\":2,\"clientId\":\"bar\"}," +
|
||||
"{\"id\":3,\"clientId\":\"baz\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, WhitelistedSite> fakeDb = new HashMap<>();
|
||||
when(wlSiteRepository.save(isA(WhitelistedSite.class))).thenAnswer(new Answer<WhitelistedSite>() {
|
||||
Long id = 333L;
|
||||
@Override
|
||||
public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable {
|
||||
WhitelistedSite _site = (WhitelistedSite) invocation.getArguments()[0];
|
||||
if(_site.getId() == null) {
|
||||
_site.setId(id++);
|
||||
}
|
||||
fakeDb.put(_site.getId(), _site);
|
||||
return _site;
|
||||
}
|
||||
});
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(wlSiteRepository, times(3)).save(capturedWhitelistedSites.capture());
|
||||
|
||||
List<WhitelistedSite> savedSites = capturedWhitelistedSites.getAllValues();
|
||||
|
||||
assertThat(savedSites.size(), is(3));
|
||||
|
||||
assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId()));
|
||||
assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId()));
|
||||
assertThat(savedSites.get(2).getClientId(), equalTo(site3.getClientId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportGrants() throws IOException, ParseException {
|
||||
Date creationDate1 = formatter.parse("2014-09-10T22:49:44.090+0000", Locale.ENGLISH);
|
||||
Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+0000", Locale.ENGLISH);
|
||||
|
||||
OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class);
|
||||
|
||||
ApprovedSite site1 = new ApprovedSite();
|
||||
site1.setId(1L);
|
||||
site1.setClientId("foo");
|
||||
site1.setCreationDate(creationDate1);
|
||||
site1.setAccessDate(accessDate1);
|
||||
site1.setUserId("user1");
|
||||
site1.setAllowedScopes(ImmutableSet.of("openid", "phone"));
|
||||
|
||||
Date creationDate2 = formatter.parse("2014-09-11T18:49:44.090+0000", Locale.ENGLISH);
|
||||
Date accessDate2 = formatter.parse("2014-09-11T20:49:44.090+0000", Locale.ENGLISH);
|
||||
Date timeoutDate2 = formatter.parse("2014-10-01T20:49:44.090+0000", Locale.ENGLISH);
|
||||
|
||||
ApprovedSite site2 = new ApprovedSite();
|
||||
site2.setId(2L);
|
||||
site2.setClientId("bar");
|
||||
site2.setCreationDate(creationDate2);
|
||||
site2.setAccessDate(accessDate2);
|
||||
site2.setUserId("user2");
|
||||
site2.setAllowedScopes(ImmutableSet.of("openid", "offline_access", "email", "profile"));
|
||||
site2.setTimeoutDate(timeoutDate2);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"foo\",\"creationDate\":\"2014-09-10T22:49:44.090+0000\",\"accessDate\":\"2014-09-10T23:49:44.090+0000\","
|
||||
+ "\"userId\":\"user1\",\"whitelistedSiteId\":null,\"allowedScopes\":[\"openid\",\"phone\"], \"whitelistedSiteId\":1,"
|
||||
+ "\"approvedAccessTokens\":[1]}," +
|
||||
"{\"id\":2,\"clientId\":\"bar\",\"creationDate\":\"2014-09-11T18:49:44.090+0000\",\"accessDate\":\"2014-09-11T20:49:44.090+0000\","
|
||||
+ "\"timeoutDate\":\"2014-10-01T20:49:44.090+0000\",\"userId\":\"user2\","
|
||||
+ "\"allowedScopes\":[\"openid\",\"offline_access\",\"email\",\"profile\"]}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, ApprovedSite> fakeDb = new HashMap<>();
|
||||
when(approvedSiteRepository.save(isA(ApprovedSite.class))).thenAnswer(new Answer<ApprovedSite>() {
|
||||
Long id = 364L;
|
||||
@Override
|
||||
public ApprovedSite answer(InvocationOnMock invocation) throws Throwable {
|
||||
ApprovedSite _site = (ApprovedSite) invocation.getArguments()[0];
|
||||
if(_site.getId() == null) {
|
||||
_site.setId(id++);
|
||||
}
|
||||
fakeDb.put(_site.getId(), _site);
|
||||
return _site;
|
||||
}
|
||||
});
|
||||
when(approvedSiteRepository.getById(anyLong())).thenAnswer(new Answer<ApprovedSite>() {
|
||||
@Override
|
||||
public ApprovedSite answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeDb.get(_id);
|
||||
}
|
||||
});
|
||||
when(tokenRepository.getAccessTokenById(isNull(Long.class))).thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
|
||||
Long id = 245L;
|
||||
@Override
|
||||
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
OAuth2AccessTokenEntity _token = mock(OAuth2AccessTokenEntity.class);
|
||||
return _token;
|
||||
}
|
||||
});
|
||||
|
||||
dataService.importData(reader);
|
||||
//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());
|
||||
|
||||
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(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()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportAuthenticationHolders() throws IOException {
|
||||
OAuth2Request req1 = new OAuth2Request(new HashMap<String, String>(), "client1", new ArrayList<GrantedAuthority>(),
|
||||
true, new HashSet<String>(), new HashSet<String>(), "http://foo.com",
|
||||
new HashSet<String>(), null);
|
||||
Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable());
|
||||
OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1);
|
||||
|
||||
AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity();
|
||||
holder1.setId(1L);
|
||||
holder1.setAuthentication(auth1);
|
||||
|
||||
OAuth2Request req2 = new OAuth2Request(new HashMap<String, String>(), "client2", new ArrayList<GrantedAuthority>(),
|
||||
true, new HashSet<String>(), new HashSet<String>(), "http://bar.com",
|
||||
new HashSet<String>(), null);
|
||||
Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable());
|
||||
OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2);
|
||||
|
||||
AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity();
|
||||
holder2.setId(2L);
|
||||
holder2.setAuthentication(auth2);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client1\",\"redirectUri\":\"http://foo.com\"},"
|
||||
+ "\"userAuthentication\":null}}," +
|
||||
"{\"id\":2,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client2\",\"redirectUri\":\"http://bar.com\"},"
|
||||
+ "\"userAuthentication\":null}}" +
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, AuthenticationHolderEntity> fakeDb = new HashMap<>();
|
||||
when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
Long id = 243L;
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
AuthenticationHolderEntity _site = (AuthenticationHolderEntity) invocation.getArguments()[0];
|
||||
if(_site.getId() == null) {
|
||||
_site.setId(id++);
|
||||
}
|
||||
fakeDb.put(_site.getId(), _site);
|
||||
return _site;
|
||||
}
|
||||
});
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(authHolderRepository, times(2)).save(capturedAuthHolders.capture());
|
||||
|
||||
List<AuthenticationHolderEntity> savedAuthHolders = capturedAuthHolders.getAllValues();
|
||||
|
||||
assertThat(savedAuthHolders.size(), is(2));
|
||||
assertThat(savedAuthHolders.get(0).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder1.getAuthentication().getOAuth2Request().getClientId()));
|
||||
assertThat(savedAuthHolders.get(1).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder2.getAuthentication().getOAuth2Request().getClientId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportSystemScopes() throws IOException {
|
||||
SystemScope scope1 = new SystemScope();
|
||||
scope1.setId(1L);
|
||||
scope1.setValue("scope1");
|
||||
scope1.setDescription("Scope 1");
|
||||
scope1.setRestricted(true);
|
||||
scope1.setDefaultScope(false);
|
||||
scope1.setIcon("glass");
|
||||
|
||||
SystemScope scope2 = new SystemScope();
|
||||
scope2.setId(2L);
|
||||
scope2.setValue("scope2");
|
||||
scope2.setDescription("Scope 2");
|
||||
scope2.setRestricted(false);
|
||||
scope2.setDefaultScope(false);
|
||||
scope2.setIcon("ball");
|
||||
|
||||
SystemScope scope3 = new SystemScope();
|
||||
scope3.setId(3L);
|
||||
scope3.setValue("scope3");
|
||||
scope3.setDescription("Scope 3");
|
||||
scope3.setRestricted(false);
|
||||
scope3.setDefaultScope(true);
|
||||
scope3.setIcon("road");
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [" +
|
||||
|
||||
"{\"id\":1,\"description\":\"Scope 1\",\"icon\":\"glass\",\"value\":\"scope1\",\"allowDynReg\":false,\"defaultScope\":false}," +
|
||||
"{\"id\":2,\"description\":\"Scope 2\",\"icon\":\"ball\",\"value\":\"scope2\",\"allowDynReg\":true,\"defaultScope\":false}," +
|
||||
"{\"id\":3,\"description\":\"Scope 3\",\"icon\":\"road\",\"value\":\"scope3\",\"allowDynReg\":true,\"defaultScope\":true}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(sysScopeRepository, times(3)).save(capturedScope.capture());
|
||||
|
||||
List<SystemScope> savedScopes = capturedScope.getAllValues();
|
||||
|
||||
assertThat(savedScopes.size(), is(3));
|
||||
assertThat(savedScopes.get(0).getValue(), equalTo(scope1.getValue()));
|
||||
assertThat(savedScopes.get(0).getDescription(), equalTo(scope1.getDescription()));
|
||||
assertThat(savedScopes.get(0).getIcon(), equalTo(scope1.getIcon()));
|
||||
assertThat(savedScopes.get(0).isDefaultScope(), equalTo(scope1.isDefaultScope()));
|
||||
assertThat(savedScopes.get(0).isRestricted(), equalTo(scope1.isRestricted()));
|
||||
|
||||
assertThat(savedScopes.get(1).getValue(), equalTo(scope2.getValue()));
|
||||
assertThat(savedScopes.get(1).getDescription(), equalTo(scope2.getDescription()));
|
||||
assertThat(savedScopes.get(1).getIcon(), equalTo(scope2.getIcon()));
|
||||
assertThat(savedScopes.get(1).isDefaultScope(), equalTo(scope2.isDefaultScope()));
|
||||
assertThat(savedScopes.get(1).isRestricted(), equalTo(scope2.isRestricted()));
|
||||
|
||||
assertThat(savedScopes.get(2).getValue(), equalTo(scope3.getValue()));
|
||||
assertThat(savedScopes.get(2).getDescription(), equalTo(scope3.getDescription()));
|
||||
assertThat(savedScopes.get(2).getIcon(), equalTo(scope3.getIcon()));
|
||||
assertThat(savedScopes.get(2).isDefaultScope(), equalTo(scope3.isDefaultScope()));
|
||||
assertThat(savedScopes.get(2).isRestricted(), equalTo(scope3.isRestricted()));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException, ParseException {
|
||||
String expiration1 = "2014-09-10T22:49:44.090+0000";
|
||||
Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class);
|
||||
|
||||
OAuth2Request req1 = new OAuth2Request(new HashMap<String, String>(), "client1", new ArrayList<GrantedAuthority>(),
|
||||
true, new HashSet<String>(), new HashSet<String>(), "http://foo.com",
|
||||
new HashSet<String>(), null);
|
||||
Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable());
|
||||
OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1);
|
||||
|
||||
AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity();
|
||||
holder1.setId(1L);
|
||||
holder1.setAuthentication(auth1);
|
||||
|
||||
OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity();
|
||||
token1.setId(1L);
|
||||
token1.setClient(mockedClient1);
|
||||
token1.setExpiration(expirationDate1);
|
||||
token1.setJwt(JWTParser.parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."));
|
||||
token1.setAuthenticationHolder(holder1);
|
||||
|
||||
String expiration2 = "2015-01-07T18:31:50.079+0000";
|
||||
Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class);
|
||||
|
||||
OAuth2Request req2 = new OAuth2Request(new HashMap<String, String>(), "client2", new ArrayList<GrantedAuthority>(),
|
||||
true, new HashSet<String>(), new HashSet<String>(), "http://bar.com",
|
||||
new HashSet<String>(), null);
|
||||
Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable());
|
||||
OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2);
|
||||
|
||||
AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity();
|
||||
holder2.setId(2L);
|
||||
holder2.setAuthentication(auth2);
|
||||
|
||||
OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity();
|
||||
token2.setId(2L);
|
||||
token2.setClient(mockedClient2);
|
||||
token2.setExpiration(expirationDate2);
|
||||
token2.setJwt(JWTParser.parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."));
|
||||
token2.setAuthenticationHolder(holder2);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client1\",\"redirectUri\":\"http://foo.com\"},"
|
||||
+ "\"userAuthentication\":null}}," +
|
||||
"{\"id\":2,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client2\",\"redirectUri\":\"http://bar.com\"},"
|
||||
+ "\"userAuthentication\":null}}" +
|
||||
" ]," +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\","
|
||||
+ "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," +
|
||||
"{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\","
|
||||
+ "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
System.err.println(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
final Map<Long, OAuth2RefreshTokenEntity> fakeRefreshTokenTable = new HashMap<>();
|
||||
final Map<Long, AuthenticationHolderEntity> fakeAuthHolderTable = new HashMap<>();
|
||||
when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
|
||||
Long id = 343L;
|
||||
@Override
|
||||
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0];
|
||||
if(_token.getId() == null) {
|
||||
_token.setId(id++);
|
||||
}
|
||||
fakeRefreshTokenTable.put(_token.getId(), _token);
|
||||
return _token;
|
||||
}
|
||||
});
|
||||
when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
|
||||
@Override
|
||||
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeRefreshTokenTable.get(_id);
|
||||
}
|
||||
});
|
||||
when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer<ClientDetailsEntity>() {
|
||||
@Override
|
||||
public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
String _clientId = (String) invocation.getArguments()[0];
|
||||
ClientDetailsEntity _client = mock(ClientDetailsEntity.class);
|
||||
return _client;
|
||||
}
|
||||
});
|
||||
when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
Long id = 356L;
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
AuthenticationHolderEntity _holder = (AuthenticationHolderEntity) invocation.getArguments()[0];
|
||||
if(_holder.getId() == null) {
|
||||
_holder.setId(id++);
|
||||
}
|
||||
fakeAuthHolderTable.put(_holder.getId(), _holder);
|
||||
return _holder;
|
||||
}
|
||||
});
|
||||
when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeAuthHolderTable.get(_id);
|
||||
}
|
||||
});
|
||||
dataService.importData(reader);
|
||||
|
||||
List<OAuth2RefreshTokenEntity> savedRefreshTokens = new ArrayList(fakeRefreshTokenTable.values()); //capturedRefreshTokens.getAllValues();
|
||||
Collections.sort(savedRefreshTokens, new refreshTokenIdComparator());
|
||||
|
||||
assertThat(savedRefreshTokens.get(0).getAuthenticationHolder().getId(), equalTo(356L));
|
||||
assertThat(savedRefreshTokens.get(1).getAuthenticationHolder().getId(), equalTo(357L));
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void testExportDisabled() throws IOException {
|
||||
JsonWriter writer = new JsonWriter(new StringWriter());
|
||||
dataService.exportData(writer);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,947 +0,0 @@
|
|||
/*******************************************************************************
|
||||
* Copyright 2018 The MIT Internet Trust Consortium
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*******************************************************************************/
|
||||
package org.mitre.openid.connect.service.impl;
|
||||
|
||||
import static org.mockito.Matchers.anyLong;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Matchers.isA;
|
||||
import static org.mockito.Matchers.isNull;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.text.ParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mitre.oauth2.model.AuthenticationHolderEntity;
|
||||
import org.mitre.oauth2.model.ClientDetailsEntity;
|
||||
import org.mitre.oauth2.model.OAuth2AccessTokenEntity;
|
||||
import org.mitre.oauth2.model.OAuth2RefreshTokenEntity;
|
||||
import org.mitre.oauth2.model.SystemScope;
|
||||
import org.mitre.oauth2.repository.AuthenticationHolderRepository;
|
||||
import org.mitre.oauth2.repository.OAuth2ClientRepository;
|
||||
import org.mitre.oauth2.repository.OAuth2TokenRepository;
|
||||
import org.mitre.oauth2.repository.SystemScopeRepository;
|
||||
import org.mitre.openid.connect.model.ApprovedSite;
|
||||
import org.mitre.openid.connect.model.BlacklistedSite;
|
||||
import org.mitre.openid.connect.model.WhitelistedSite;
|
||||
import org.mitre.openid.connect.repository.ApprovedSiteRepository;
|
||||
import org.mitre.openid.connect.repository.BlacklistedSiteRepository;
|
||||
import org.mitre.openid.connect.repository.WhitelistedSiteRepository;
|
||||
import org.mitre.openid.connect.service.MITREidDataService;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.format.annotation.DateTimeFormat.ISO;
|
||||
import org.springframework.format.datetime.DateFormatter;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
||||
import org.springframework.security.oauth2.provider.OAuth2Request;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.nimbusds.jwt.JWTParser;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.Mockito.withSettings;
|
||||
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
@SuppressWarnings(value = {"rawtypes", "unchecked"})
|
||||
public class TestMITREidDataService_1_2 {
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(TestMITREidDataService_1_2.class);
|
||||
|
||||
@Mock
|
||||
private OAuth2ClientRepository clientRepository;
|
||||
@Mock
|
||||
private ApprovedSiteRepository approvedSiteRepository;
|
||||
@Mock
|
||||
private WhitelistedSiteRepository wlSiteRepository;
|
||||
@Mock
|
||||
private BlacklistedSiteRepository blSiteRepository;
|
||||
@Mock
|
||||
private AuthenticationHolderRepository authHolderRepository;
|
||||
@Mock
|
||||
private OAuth2TokenRepository tokenRepository;
|
||||
@Mock
|
||||
private SystemScopeRepository sysScopeRepository;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<OAuth2RefreshTokenEntity> capturedRefreshTokens;
|
||||
@Captor
|
||||
private ArgumentCaptor<OAuth2AccessTokenEntity> capturedAccessTokens;
|
||||
@Captor
|
||||
private ArgumentCaptor<ClientDetailsEntity> capturedClients;
|
||||
@Captor
|
||||
private ArgumentCaptor<BlacklistedSite> capturedBlacklistedSites;
|
||||
@Captor
|
||||
private ArgumentCaptor<WhitelistedSite> capturedWhitelistedSites;
|
||||
@Captor
|
||||
private ArgumentCaptor<ApprovedSite> capturedApprovedSites;
|
||||
@Captor
|
||||
private ArgumentCaptor<AuthenticationHolderEntity> capturedAuthHolders;
|
||||
@Captor
|
||||
private ArgumentCaptor<SystemScope> capturedScope;
|
||||
|
||||
@InjectMocks
|
||||
private MITREidDataService_1_2 dataService;
|
||||
private DateFormatter formatter;
|
||||
|
||||
@Before
|
||||
public void prepare() {
|
||||
formatter = new DateFormatter();
|
||||
formatter.setIso(ISO.DATE_TIME);
|
||||
|
||||
Mockito.reset(clientRepository, approvedSiteRepository, authHolderRepository, tokenRepository, sysScopeRepository, wlSiteRepository, blSiteRepository);
|
||||
}
|
||||
|
||||
private class refreshTokenIdComparator implements Comparator<OAuth2RefreshTokenEntity> {
|
||||
@Override
|
||||
public int compare(OAuth2RefreshTokenEntity entity1, OAuth2RefreshTokenEntity entity2) {
|
||||
return entity1.getId().compareTo(entity2.getId());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testImportRefreshTokens() throws IOException, ParseException {
|
||||
String expiration1 = "2014-09-10T22:49:44.090+0000";
|
||||
Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class);
|
||||
when(mockedClient1.getClientId()).thenReturn("mocked_client_1");
|
||||
|
||||
AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class);
|
||||
|
||||
OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity();
|
||||
token1.setId(1L);
|
||||
token1.setClient(mockedClient1);
|
||||
token1.setExpiration(expirationDate1);
|
||||
token1.setJwt(JWTParser.parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."));
|
||||
token1.setAuthenticationHolder(mockedAuthHolder1);
|
||||
|
||||
String expiration2 = "2015-01-07T18:31:50.079+0000";
|
||||
Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class);
|
||||
when(mockedClient2.getClientId()).thenReturn("mocked_client_2");
|
||||
|
||||
AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class);
|
||||
|
||||
OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity();
|
||||
token2.setId(2L);
|
||||
token2.setClient(mockedClient2);
|
||||
token2.setExpiration(expirationDate2);
|
||||
token2.setJwt(JWTParser.parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."));
|
||||
token2.setAuthenticationHolder(mockedAuthHolder2);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\","
|
||||
+ "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," +
|
||||
"{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\","
|
||||
+ "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
logger.debug(configJson);
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, OAuth2RefreshTokenEntity> fakeDb = new HashMap<>();
|
||||
when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
|
||||
Long id = 332L;
|
||||
@Override
|
||||
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0];
|
||||
if(_token.getId() == null) {
|
||||
_token.setId(id++);
|
||||
}
|
||||
fakeDb.put(_token.getId(), _token);
|
||||
return _token;
|
||||
}
|
||||
});
|
||||
when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
|
||||
@Override
|
||||
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeDb.get(_id);
|
||||
}
|
||||
});
|
||||
when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer<ClientDetailsEntity>() {
|
||||
@Override
|
||||
public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
String _clientId = (String) invocation.getArguments()[0];
|
||||
ClientDetailsEntity _client = mock(ClientDetailsEntity.class);
|
||||
when(_client.getClientId()).thenReturn(_clientId);
|
||||
return _client;
|
||||
}
|
||||
});
|
||||
when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
Long id = 131L;
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class);
|
||||
id++;
|
||||
return _auth;
|
||||
}
|
||||
});
|
||||
dataService.importData(reader);
|
||||
//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());
|
||||
|
||||
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(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> {
|
||||
@Override
|
||||
public int compare(OAuth2AccessTokenEntity entity1, OAuth2AccessTokenEntity entity2) {
|
||||
return entity1.getId().compareTo(entity2.getId());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportAccessTokens() throws IOException, ParseException {
|
||||
String expiration1 = "2014-09-10T22:49:44.090+0000";
|
||||
Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class);
|
||||
when(mockedClient1.getClientId()).thenReturn("mocked_client_1");
|
||||
|
||||
AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class);
|
||||
|
||||
OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity();
|
||||
token1.setId(1L);
|
||||
token1.setClient(mockedClient1);
|
||||
token1.setExpiration(expirationDate1);
|
||||
token1.setJwt(JWTParser.parse("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0"));
|
||||
token1.setAuthenticationHolder(mockedAuthHolder1);
|
||||
token1.setScope(ImmutableSet.of("id-token"));
|
||||
token1.setTokenType("Bearer");
|
||||
|
||||
String expiration2 = "2015-01-07T18:31:50.079+0000";
|
||||
Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class);
|
||||
when(mockedClient2.getClientId()).thenReturn("mocked_client_2");
|
||||
|
||||
AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class);
|
||||
|
||||
OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class);
|
||||
|
||||
OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity();
|
||||
token2.setId(2L);
|
||||
token2.setClient(mockedClient2);
|
||||
token2.setExpiration(expirationDate2);
|
||||
token2.setJwt(JWTParser.parse("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ"));
|
||||
token2.setAuthenticationHolder(mockedAuthHolder2);
|
||||
token2.setRefreshToken(mockRefreshToken2);
|
||||
token2.setScope(ImmutableSet.of("openid", "offline_access", "email", "profile"));
|
||||
token2.setTokenType("Bearer");
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\","
|
||||
+ "\"refreshTokenId\":null,\"idTokenId\":null,\"scope\":[\"id-token\"],\"type\":\"Bearer\","
|
||||
+ "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0\"}," +
|
||||
"{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\","
|
||||
+ "\"refreshTokenId\":1,\"idTokenId\":1,\"scope\":[\"openid\",\"offline_access\",\"email\",\"profile\"],\"type\":\"Bearer\","
|
||||
+ "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
|
||||
logger.debug(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, OAuth2AccessTokenEntity> fakeDb = new HashMap<>();
|
||||
when(tokenRepository.saveAccessToken(isA(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
|
||||
Long id = 324L;
|
||||
@Override
|
||||
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
OAuth2AccessTokenEntity _token = (OAuth2AccessTokenEntity) invocation.getArguments()[0];
|
||||
if(_token.getId() == null) {
|
||||
_token.setId(id++);
|
||||
}
|
||||
fakeDb.put(_token.getId(), _token);
|
||||
return _token;
|
||||
}
|
||||
});
|
||||
when(tokenRepository.getAccessTokenById(anyLong())).thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
|
||||
@Override
|
||||
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeDb.get(_id);
|
||||
}
|
||||
});
|
||||
when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer<ClientDetailsEntity>() {
|
||||
@Override
|
||||
public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
String _clientId = (String) invocation.getArguments()[0];
|
||||
ClientDetailsEntity _client = mock(ClientDetailsEntity.class);
|
||||
when(_client.getClientId()).thenReturn(_clientId);
|
||||
return _client;
|
||||
}
|
||||
});
|
||||
when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
Long id = 133L;
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class);
|
||||
id++;
|
||||
return _auth;
|
||||
}
|
||||
});
|
||||
dataService.importData(reader);
|
||||
//2 times for token, 2 times to update client, 2 times to update authHolder, 1 times to update refresh token
|
||||
verify(tokenRepository, times(7)).saveAccessToken(capturedAccessTokens.capture());
|
||||
|
||||
List<OAuth2AccessTokenEntity> savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues();
|
||||
Collections.sort(savedAccessTokens, new accessTokenIdComparator());
|
||||
|
||||
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(1).getClient().getClientId(), equalTo(token2.getClient().getClientId()));
|
||||
assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration()));
|
||||
assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportClients() throws IOException {
|
||||
ClientDetailsEntity client1 = new ClientDetailsEntity();
|
||||
client1.setId(1L);
|
||||
client1.setAccessTokenValiditySeconds(3600);
|
||||
client1.setClientId("client1");
|
||||
client1.setClientSecret("clientsecret1");
|
||||
client1.setRedirectUris(ImmutableSet.of("http://foo.com/"));
|
||||
client1.setScope(ImmutableSet.of("foo", "bar", "baz", "dolphin"));
|
||||
client1.setGrantTypes(ImmutableSet.of("implicit", "authorization_code", "urn:ietf:params:oauth:grant_type:redelegate", "refresh_token"));
|
||||
client1.setAllowIntrospection(true);
|
||||
|
||||
ClientDetailsEntity client2 = new ClientDetailsEntity();
|
||||
client2.setId(2L);
|
||||
client2.setAccessTokenValiditySeconds(3600);
|
||||
client2.setClientId("client2");
|
||||
client2.setClientSecret("clientsecret2");
|
||||
client2.setRedirectUris(ImmutableSet.of("http://bar.baz.com/"));
|
||||
client2.setScope(ImmutableSet.of("foo", "dolphin", "electric-wombat"));
|
||||
client2.setGrantTypes(ImmutableSet.of("client_credentials", "urn:ietf:params:oauth:grant_type:redelegate"));
|
||||
client2.setAllowIntrospection(false);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"accessTokenValiditySeconds\":3600,\"clientId\":\"client1\",\"secret\":\"clientsecret1\","
|
||||
+ "\"redirectUris\":[\"http://foo.com/\"],"
|
||||
+ "\"scope\":[\"foo\",\"bar\",\"baz\",\"dolphin\"],"
|
||||
+ "\"grantTypes\":[\"implicit\",\"authorization_code\",\"urn:ietf:params:oauth:grant_type:redelegate\",\"refresh_token\"],"
|
||||
+ "\"allowIntrospection\":true}," +
|
||||
"{\"id\":2,\"accessTokenValiditySeconds\":3600,\"clientId\":\"client2\",\"secret\":\"clientsecret2\","
|
||||
+ "\"redirectUris\":[\"http://bar.baz.com/\"],"
|
||||
+ "\"scope\":[\"foo\",\"dolphin\",\"electric-wombat\"],"
|
||||
+ "\"grantTypes\":[\"client_credentials\",\"urn:ietf:params:oauth:grant_type:redelegate\"],"
|
||||
+ "\"allowIntrospection\":false}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
logger.debug(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(clientRepository, times(2)).saveClient(capturedClients.capture());
|
||||
|
||||
List<ClientDetailsEntity> savedClients = capturedClients.getAllValues();
|
||||
|
||||
assertThat(savedClients.size(), is(2));
|
||||
|
||||
assertThat(savedClients.get(0).getAccessTokenValiditySeconds(), equalTo(client1.getAccessTokenValiditySeconds()));
|
||||
assertThat(savedClients.get(0).getClientId(), equalTo(client1.getClientId()));
|
||||
assertThat(savedClients.get(0).getClientSecret(), equalTo(client1.getClientSecret()));
|
||||
assertThat(savedClients.get(0).getRedirectUris(), equalTo(client1.getRedirectUris()));
|
||||
assertThat(savedClients.get(0).getScope(), equalTo(client1.getScope()));
|
||||
assertThat(savedClients.get(0).getGrantTypes(), equalTo(client1.getGrantTypes()));
|
||||
assertThat(savedClients.get(0).isAllowIntrospection(), equalTo(client1.isAllowIntrospection()));
|
||||
|
||||
assertThat(savedClients.get(1).getAccessTokenValiditySeconds(), equalTo(client2.getAccessTokenValiditySeconds()));
|
||||
assertThat(savedClients.get(1).getClientId(), equalTo(client2.getClientId()));
|
||||
assertThat(savedClients.get(1).getClientSecret(), equalTo(client2.getClientSecret()));
|
||||
assertThat(savedClients.get(1).getRedirectUris(), equalTo(client2.getRedirectUris()));
|
||||
assertThat(savedClients.get(1).getScope(), equalTo(client2.getScope()));
|
||||
assertThat(savedClients.get(1).getGrantTypes(), equalTo(client2.getGrantTypes()));
|
||||
assertThat(savedClients.get(1).isAllowIntrospection(), equalTo(client2.isAllowIntrospection()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportBlacklistedSites() throws IOException {
|
||||
BlacklistedSite site1 = new BlacklistedSite();
|
||||
site1.setId(1L);
|
||||
site1.setUri("http://foo.com");
|
||||
|
||||
BlacklistedSite site2 = new BlacklistedSite();
|
||||
site2.setId(2L);
|
||||
site2.setUri("http://bar.com");
|
||||
|
||||
BlacklistedSite site3 = new BlacklistedSite();
|
||||
site3.setId(3L);
|
||||
site3.setUri("http://baz.com");
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [" +
|
||||
|
||||
"{\"id\":1,\"uri\":\"http://foo.com\"}," +
|
||||
"{\"id\":2,\"uri\":\"http://bar.com\"}," +
|
||||
"{\"id\":3,\"uri\":\"http://baz.com\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
|
||||
logger.debug(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(blSiteRepository, times(3)).save(capturedBlacklistedSites.capture());
|
||||
|
||||
List<BlacklistedSite> savedSites = capturedBlacklistedSites.getAllValues();
|
||||
|
||||
assertThat(savedSites.size(), is(3));
|
||||
|
||||
assertThat(savedSites.get(0).getUri(), equalTo(site1.getUri()));
|
||||
assertThat(savedSites.get(1).getUri(), equalTo(site2.getUri()));
|
||||
assertThat(savedSites.get(2).getUri(), equalTo(site3.getUri()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportWhitelistedSites() throws IOException {
|
||||
WhitelistedSite site1 = new WhitelistedSite();
|
||||
site1.setId(1L);
|
||||
site1.setClientId("foo");
|
||||
|
||||
WhitelistedSite site2 = new WhitelistedSite();
|
||||
site2.setId(2L);
|
||||
site2.setClientId("bar");
|
||||
|
||||
WhitelistedSite site3 = new WhitelistedSite();
|
||||
site3.setId(3L);
|
||||
site3.setClientId("baz");
|
||||
//site3.setAllowedScopes(null);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"foo\"}," +
|
||||
"{\"id\":2,\"clientId\":\"bar\"}," +
|
||||
"{\"id\":3,\"clientId\":\"baz\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
logger.debug(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, WhitelistedSite> fakeDb = new HashMap<>();
|
||||
when(wlSiteRepository.save(isA(WhitelistedSite.class))).thenAnswer(new Answer<WhitelistedSite>() {
|
||||
Long id = 333L;
|
||||
@Override
|
||||
public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable {
|
||||
WhitelistedSite _site = (WhitelistedSite) invocation.getArguments()[0];
|
||||
if(_site.getId() == null) {
|
||||
_site.setId(id++);
|
||||
}
|
||||
fakeDb.put(_site.getId(), _site);
|
||||
return _site;
|
||||
}
|
||||
});
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(wlSiteRepository, times(3)).save(capturedWhitelistedSites.capture());
|
||||
|
||||
List<WhitelistedSite> savedSites = capturedWhitelistedSites.getAllValues();
|
||||
|
||||
assertThat(savedSites.size(), is(3));
|
||||
|
||||
assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId()));
|
||||
assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId()));
|
||||
assertThat(savedSites.get(2).getClientId(), equalTo(site3.getClientId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportGrants() throws IOException, ParseException {
|
||||
Date creationDate1 = formatter.parse("2014-09-10T22:49:44.090+0000", Locale.ENGLISH);
|
||||
Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+0000", Locale.ENGLISH);
|
||||
|
||||
OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class);
|
||||
|
||||
ApprovedSite site1 = new ApprovedSite();
|
||||
site1.setId(1L);
|
||||
site1.setClientId("foo");
|
||||
site1.setCreationDate(creationDate1);
|
||||
site1.setAccessDate(accessDate1);
|
||||
site1.setUserId("user1");
|
||||
site1.setAllowedScopes(ImmutableSet.of("openid", "phone"));
|
||||
|
||||
Date creationDate2 = formatter.parse("2014-09-11T18:49:44.090+0000", Locale.ENGLISH);
|
||||
Date accessDate2 = formatter.parse("2014-09-11T20:49:44.090+0000", Locale.ENGLISH);
|
||||
Date timeoutDate2 = formatter.parse("2014-10-01T20:49:44.090+0000", Locale.ENGLISH);
|
||||
|
||||
ApprovedSite site2 = new ApprovedSite();
|
||||
site2.setId(2L);
|
||||
site2.setClientId("bar");
|
||||
site2.setCreationDate(creationDate2);
|
||||
site2.setAccessDate(accessDate2);
|
||||
site2.setUserId("user2");
|
||||
site2.setAllowedScopes(ImmutableSet.of("openid", "offline_access", "email", "profile"));
|
||||
site2.setTimeoutDate(timeoutDate2);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"foo\",\"creationDate\":\"2014-09-10T22:49:44.090+0000\",\"accessDate\":\"2014-09-10T23:49:44.090+0000\","
|
||||
+ "\"userId\":\"user1\",\"whitelistedSiteId\":null,\"allowedScopes\":[\"openid\",\"phone\"], \"whitelistedSiteId\":1,"
|
||||
+ "\"approvedAccessTokens\":[1]}," +
|
||||
"{\"id\":2,\"clientId\":\"bar\",\"creationDate\":\"2014-09-11T18:49:44.090+0000\",\"accessDate\":\"2014-09-11T20:49:44.090+0000\","
|
||||
+ "\"timeoutDate\":\"2014-10-01T20:49:44.090+0000\",\"userId\":\"user2\","
|
||||
+ "\"allowedScopes\":[\"openid\",\"offline_access\",\"email\",\"profile\"]}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
logger.debug(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, ApprovedSite> fakeDb = new HashMap<>();
|
||||
when(approvedSiteRepository.save(isA(ApprovedSite.class))).thenAnswer(new Answer<ApprovedSite>() {
|
||||
Long id = 364L;
|
||||
@Override
|
||||
public ApprovedSite answer(InvocationOnMock invocation) throws Throwable {
|
||||
ApprovedSite _site = (ApprovedSite) invocation.getArguments()[0];
|
||||
if(_site.getId() == null) {
|
||||
_site.setId(id++);
|
||||
}
|
||||
fakeDb.put(_site.getId(), _site);
|
||||
return _site;
|
||||
}
|
||||
});
|
||||
when(approvedSiteRepository.getById(anyLong())).thenAnswer(new Answer<ApprovedSite>() {
|
||||
@Override
|
||||
public ApprovedSite answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeDb.get(_id);
|
||||
}
|
||||
});
|
||||
when(tokenRepository.getAccessTokenById(isNull(Long.class))).thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
|
||||
Long id = 245L;
|
||||
@Override
|
||||
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
OAuth2AccessTokenEntity _token = mock(OAuth2AccessTokenEntity.class);
|
||||
return _token;
|
||||
}
|
||||
});
|
||||
|
||||
dataService.importData(reader);
|
||||
//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());
|
||||
|
||||
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(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()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportAuthenticationHolders() throws IOException {
|
||||
OAuth2Request req1 = new OAuth2Request(new HashMap<String, String>(), "client1", new ArrayList<GrantedAuthority>(),
|
||||
true, new HashSet<String>(), new HashSet<String>(), "http://foo.com",
|
||||
new HashSet<String>(), null);
|
||||
Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable());
|
||||
OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1);
|
||||
|
||||
AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity();
|
||||
holder1.setId(1L);
|
||||
holder1.setAuthentication(auth1);
|
||||
|
||||
OAuth2Request req2 = new OAuth2Request(new HashMap<String, String>(), "client2", new ArrayList<GrantedAuthority>(),
|
||||
true, new HashSet<String>(), new HashSet<String>(), "http://bar.com",
|
||||
new HashSet<String>(), null);
|
||||
Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable());
|
||||
OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2);
|
||||
|
||||
AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity();
|
||||
holder2.setId(2L);
|
||||
holder2.setAuthentication(auth2);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"client1\",\"redirectUri\":\"http://foo.com\","
|
||||
+ "\"savedUserAuthentication\":null}," +
|
||||
"{\"id\":2,\"clientId\":\"client2\",\"redirectUri\":\"http://bar.com\","
|
||||
+ "\"savedUserAuthentication\":null}" +
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
logger.debug(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
final Map<Long, AuthenticationHolderEntity> fakeDb = new HashMap<>();
|
||||
when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
Long id = 243L;
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
AuthenticationHolderEntity _site = (AuthenticationHolderEntity) invocation.getArguments()[0];
|
||||
if(_site.getId() == null) {
|
||||
_site.setId(id++);
|
||||
}
|
||||
fakeDb.put(_site.getId(), _site);
|
||||
return _site;
|
||||
}
|
||||
});
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(authHolderRepository, times(2)).save(capturedAuthHolders.capture());
|
||||
|
||||
List<AuthenticationHolderEntity> savedAuthHolders = capturedAuthHolders.getAllValues();
|
||||
|
||||
assertThat(savedAuthHolders.size(), is(2));
|
||||
assertThat(savedAuthHolders.get(0).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder1.getAuthentication().getOAuth2Request().getClientId()));
|
||||
assertThat(savedAuthHolders.get(1).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder2.getAuthentication().getOAuth2Request().getClientId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testImportSystemScopes() throws IOException {
|
||||
SystemScope scope1 = new SystemScope();
|
||||
scope1.setId(1L);
|
||||
scope1.setValue("scope1");
|
||||
scope1.setDescription("Scope 1");
|
||||
scope1.setRestricted(true);
|
||||
scope1.setDefaultScope(false);
|
||||
scope1.setIcon("glass");
|
||||
|
||||
SystemScope scope2 = new SystemScope();
|
||||
scope2.setId(2L);
|
||||
scope2.setValue("scope2");
|
||||
scope2.setDescription("Scope 2");
|
||||
scope2.setRestricted(false);
|
||||
scope2.setDefaultScope(false);
|
||||
scope2.setIcon("ball");
|
||||
|
||||
SystemScope scope3 = new SystemScope();
|
||||
scope3.setId(3L);
|
||||
scope3.setValue("scope3");
|
||||
scope3.setDescription("Scope 3");
|
||||
scope3.setRestricted(false);
|
||||
scope3.setDefaultScope(true);
|
||||
scope3.setIcon("road");
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [" +
|
||||
|
||||
"{\"id\":1,\"description\":\"Scope 1\",\"icon\":\"glass\",\"value\":\"scope1\",\"restricted\":true,\"defaultScope\":false}," +
|
||||
"{\"id\":2,\"description\":\"Scope 2\",\"icon\":\"ball\",\"value\":\"scope2\",\"restricted\":false,\"defaultScope\":false}," +
|
||||
"{\"id\":3,\"description\":\"Scope 3\",\"icon\":\"road\",\"value\":\"scope3\",\"restricted\":false,\"defaultScope\":true}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
|
||||
logger.debug(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
|
||||
dataService.importData(reader);
|
||||
verify(sysScopeRepository, times(3)).save(capturedScope.capture());
|
||||
|
||||
List<SystemScope> savedScopes = capturedScope.getAllValues();
|
||||
|
||||
assertThat(savedScopes.size(), is(3));
|
||||
assertThat(savedScopes.get(0).getValue(), equalTo(scope1.getValue()));
|
||||
assertThat(savedScopes.get(0).getDescription(), equalTo(scope1.getDescription()));
|
||||
assertThat(savedScopes.get(0).getIcon(), equalTo(scope1.getIcon()));
|
||||
assertThat(savedScopes.get(0).isDefaultScope(), equalTo(scope1.isDefaultScope()));
|
||||
assertThat(savedScopes.get(0).isRestricted(), equalTo(scope1.isRestricted()));
|
||||
|
||||
assertThat(savedScopes.get(1).getValue(), equalTo(scope2.getValue()));
|
||||
assertThat(savedScopes.get(1).getDescription(), equalTo(scope2.getDescription()));
|
||||
assertThat(savedScopes.get(1).getIcon(), equalTo(scope2.getIcon()));
|
||||
assertThat(savedScopes.get(1).isDefaultScope(), equalTo(scope2.isDefaultScope()));
|
||||
assertThat(savedScopes.get(1).isRestricted(), equalTo(scope2.isRestricted()));
|
||||
|
||||
assertThat(savedScopes.get(2).getValue(), equalTo(scope3.getValue()));
|
||||
assertThat(savedScopes.get(2).getDescription(), equalTo(scope3.getDescription()));
|
||||
assertThat(savedScopes.get(2).getIcon(), equalTo(scope3.getIcon()));
|
||||
assertThat(savedScopes.get(2).isDefaultScope(), equalTo(scope3.isDefaultScope()));
|
||||
assertThat(savedScopes.get(2).isRestricted(), equalTo(scope3.isRestricted()));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException, ParseException {
|
||||
String expiration1 = "2014-09-10T22:49:44.090+0000";
|
||||
Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class);
|
||||
|
||||
OAuth2Request req1 = new OAuth2Request(new HashMap<String, String>(), "client1", new ArrayList<GrantedAuthority>(),
|
||||
true, new HashSet<String>(), new HashSet<String>(), "http://foo.com",
|
||||
new HashSet<String>(), null);
|
||||
Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable());
|
||||
OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1);
|
||||
|
||||
AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity();
|
||||
holder1.setId(1L);
|
||||
holder1.setAuthentication(auth1);
|
||||
|
||||
OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity();
|
||||
token1.setId(1L);
|
||||
token1.setClient(mockedClient1);
|
||||
token1.setExpiration(expirationDate1);
|
||||
token1.setJwt(JWTParser.parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."));
|
||||
token1.setAuthenticationHolder(holder1);
|
||||
|
||||
String expiration2 = "2015-01-07T18:31:50.079+0000";
|
||||
Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH);
|
||||
|
||||
ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class);
|
||||
|
||||
OAuth2Request req2 = new OAuth2Request(new HashMap<String, String>(), "client2", new ArrayList<GrantedAuthority>(),
|
||||
true, new HashSet<String>(), new HashSet<String>(), "http://bar.com",
|
||||
new HashSet<String>(), null);
|
||||
Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable());
|
||||
OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2);
|
||||
|
||||
AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity();
|
||||
holder2.setId(2L);
|
||||
holder2.setAuthentication(auth2);
|
||||
|
||||
OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity();
|
||||
token2.setId(2L);
|
||||
token2.setClient(mockedClient2);
|
||||
token2.setExpiration(expirationDate2);
|
||||
token2.setJwt(JWTParser.parse("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."));
|
||||
token2.setAuthenticationHolder(holder2);
|
||||
|
||||
String configJson = "{" +
|
||||
"\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " +
|
||||
"\"" + MITREidDataService.ACCESSTOKENS + "\": [], " +
|
||||
"\"" + MITREidDataService.CLIENTS + "\": [], " +
|
||||
"\"" + MITREidDataService.GRANTS + "\": [], " +
|
||||
"\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " +
|
||||
"\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"authentication\":{\"authorizationRequest\":{\"clientId\":\"client1\",\"redirectUri\":\"http://foo.com\"},"
|
||||
+ "\"userAuthentication\":null}}," +
|
||||
"{\"id\":2,\"authentication\":{\"authorizationRequest\":{\"clientId\":\"client2\",\"redirectUri\":\"http://bar.com\"},"
|
||||
+ "\"userAuthentication\":null}}" +
|
||||
" ]," +
|
||||
"\"" + MITREidDataService.REFRESHTOKENS + "\": [" +
|
||||
|
||||
"{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\","
|
||||
+ "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," +
|
||||
"{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\","
|
||||
+ "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" +
|
||||
|
||||
" ]" +
|
||||
"}";
|
||||
logger.debug(configJson);
|
||||
|
||||
JsonReader reader = new JsonReader(new StringReader(configJson));
|
||||
final Map<Long, OAuth2RefreshTokenEntity> fakeRefreshTokenTable = new HashMap<>();
|
||||
final Map<Long, AuthenticationHolderEntity> fakeAuthHolderTable = new HashMap<>();
|
||||
when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
|
||||
Long id = 343L;
|
||||
@Override
|
||||
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0];
|
||||
if(_token.getId() == null) {
|
||||
_token.setId(id++);
|
||||
}
|
||||
fakeRefreshTokenTable.put(_token.getId(), _token);
|
||||
return _token;
|
||||
}
|
||||
});
|
||||
when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
|
||||
@Override
|
||||
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeRefreshTokenTable.get(_id);
|
||||
}
|
||||
});
|
||||
when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer<ClientDetailsEntity>() {
|
||||
@Override
|
||||
public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
String _clientId = (String) invocation.getArguments()[0];
|
||||
ClientDetailsEntity _client = mock(ClientDetailsEntity.class);
|
||||
return _client;
|
||||
}
|
||||
});
|
||||
when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
Long id = 356L;
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
AuthenticationHolderEntity _holder = (AuthenticationHolderEntity) invocation.getArguments()[0];
|
||||
if(_holder.getId() == null) {
|
||||
_holder.setId(id++);
|
||||
}
|
||||
fakeAuthHolderTable.put(_holder.getId(), _holder);
|
||||
return _holder;
|
||||
}
|
||||
});
|
||||
when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer<AuthenticationHolderEntity>() {
|
||||
@Override
|
||||
public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable {
|
||||
Long _id = (Long) invocation.getArguments()[0];
|
||||
return fakeAuthHolderTable.get(_id);
|
||||
}
|
||||
});
|
||||
dataService.importData(reader);
|
||||
|
||||
List<OAuth2RefreshTokenEntity> savedRefreshTokens = new ArrayList(fakeRefreshTokenTable.values()); //capturedRefreshTokens.getAllValues();
|
||||
Collections.sort(savedRefreshTokens, new refreshTokenIdComparator());
|
||||
|
||||
assertThat(savedRefreshTokens.get(0).getAuthenticationHolder().getId(), equalTo(356L));
|
||||
assertThat(savedRefreshTokens.get(1).getAuthenticationHolder().getId(), equalTo(357L));
|
||||
}
|
||||
|
||||
private Set<String> jsonArrayToStringSet(JsonArray a) {
|
||||
Set<String> s = new HashSet<>();
|
||||
for (JsonElement jsonElement : a) {
|
||||
s.add(jsonElement.getAsString());
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
}
|
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue