formatting cleanup

pull/779/head
Justin Richer 2015-02-17 11:08:46 -05:00
parent e2349984b8
commit 685960358c
66 changed files with 5651 additions and 5628 deletions

View File

@ -32,21 +32,21 @@ import com.google.gson.JsonObject;
public class OAuth2AccessTokenImpl implements OAuth2AccessToken {
private JsonObject token;
private JsonObject introspectionResponse;
private String tokenString;
private Set<String> scopes = new HashSet<String>();
private Date expireDate;
public OAuth2AccessTokenImpl(JsonObject token, String tokenString) {
this.token = token;
public OAuth2AccessTokenImpl(JsonObject introspectionResponse, String tokenString) {
this.setIntrospectionResponse(introspectionResponse);
this.tokenString = tokenString;
if (token.get("scope") != null) {
scopes = Sets.newHashSet(Splitter.on(" ").split(token.get("scope").getAsString()));
if (introspectionResponse.get("scope") != null) {
scopes = Sets.newHashSet(Splitter.on(" ").split(introspectionResponse.get("scope").getAsString()));
}
if (token.get("exp") != null) {
expireDate = new Date(token.get("exp").getAsLong() * 1000L);
if (introspectionResponse.get("exp") != null) {
expireDate = new Date(introspectionResponse.get("exp").getAsLong() * 1000L);
}
}
@ -97,4 +97,20 @@ public class OAuth2AccessTokenImpl implements OAuth2AccessToken {
return tokenString;
}
/**
* @return the token
*/
public JsonObject getIntrospectionResponse() {
return introspectionResponse;
}
/**
* @param token the token to set
*/
public void setIntrospectionResponse(JsonObject token) {
this.introspectionResponse = token;
}
}

View File

@ -316,10 +316,10 @@ public class OIDCAuthenticationFilter extends AbstractAuthenticationProcessingFi
.useSystemProperties()
.setDefaultRequestConfig(
RequestConfig.custom()
.setSocketTimeout(httpSocketTimeout)
.build()
.setSocketTimeout(httpSocketTimeout)
.build()
)
.build();
.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
@ -490,7 +490,7 @@ public class OIDCAuthenticationFilter extends AbstractAuthenticationProcessingFi
throw new AuthenticationServiceException("Unsigned ID tokens can only be used if explicitly configured in client.");
}
if (tokenAlg != null && !tokenAlg.equals(JWSAlgorithm.NONE)) {
if (tokenAlg != null && !tokenAlg.equals(Algorithm.NONE)) {
throw new AuthenticationServiceException("Unsigned token received, expected signature with " + tokenAlg);
}
} else if (idToken instanceof SignedJWT) {
@ -498,8 +498,8 @@ public class OIDCAuthenticationFilter extends AbstractAuthenticationProcessingFi
SignedJWT signedIdToken = (SignedJWT)idToken;
if (tokenAlg.equals(JWSAlgorithm.HS256)
|| tokenAlg.equals(JWSAlgorithm.HS384)
|| tokenAlg.equals(JWSAlgorithm.HS512)) {
|| tokenAlg.equals(JWSAlgorithm.HS384)
|| tokenAlg.equals(JWSAlgorithm.HS512)) {
// generate one based on client secret
jwtValidator = symmetricCacheService.getSymmetricValidtor(clientConfig.getClient());

View File

@ -115,7 +115,7 @@ public class DefaultJwtSigningAndValidationService implements JwtSigningAndValid
*/
@Override
public String getDefaultSignerKeyId() {
return defaultSignerKeyId;
return defaultSignerKeyId;
}
/**

View File

@ -33,7 +33,7 @@ import org.springframework.security.oauth2.provider.OAuth2Authentication;
@Entity
@Table(name = "authentication_holder")
@NamedQueries ({
@NamedQuery(name = "AuthenticationHolderEntity.getAll", query = "select a from AuthenticationHolderEntity a"),
@NamedQuery(name = "AuthenticationHolderEntity.getAll", query = "select a from AuthenticationHolderEntity a"),
@NamedQuery(name = "AuthenticationHolderEntity.getByAuthentication", query = "select a from AuthenticationHolderEntity a where a.authentication = :authentication"),
@NamedQuery(name = "AuthenticationHolderEntity.getUnusedAuthenticationHolders", query = "select a from AuthenticationHolderEntity a where a.id not in (select t.authenticationHolder.id from OAuth2AccessTokenEntity t) and a.id not in (select r.authenticationHolder.id from OAuth2RefreshTokenEntity r)")
})

View File

@ -353,8 +353,8 @@ public class ClientDetailsEntity implements ClientDetails {
public boolean isSecretRequired() {
if (getTokenEndpointAuthMethod() != null &&
(getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_BASIC) ||
getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_POST) ||
getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT))) {
getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_POST) ||
getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT))) {
return true;
} else {
return false;

View File

@ -22,7 +22,7 @@ import org.mitre.oauth2.model.AuthenticationHolderEntity;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
public interface AuthenticationHolderRepository {
public List<AuthenticationHolderEntity> getAll();
public List<AuthenticationHolderEntity> getAll();
public AuthenticationHolderEntity getById(Long id);

View File

@ -16,33 +16,33 @@
*******************************************************************************/
package org.mitre.oauth2.service;
import java.util.Map;
import org.mitre.oauth2.model.OAuth2AccessTokenEntity;
import org.mitre.oauth2.model.OAuth2RefreshTokenEntity;
import org.mitre.openid.connect.model.UserInfo;
import java.util.Map;
/**
* Strategy interface for assembling a token introspection result.
*/
public interface IntrospectionResultAssembler {
/**
* Assemble a token introspection result from the given access token and user info.
*
* @param accessToken the access token
* @param userInfo the user info
* @return the token introspection result
*/
Map<String, Object> assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo);
/**
* Assemble a token introspection result from the given access token and user info.
*
* @param accessToken the access token
* @param userInfo the user info
* @return the token introspection result
*/
Map<String, Object> assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo);
/**
* Assemble a token introspection result from the given refresh token and user info.
*
* @param refreshToken the refresh token
* @param userInfo the user info
* @return the token introspection result
*/
Map<String, Object> assembleFrom(OAuth2RefreshTokenEntity refreshToken, UserInfo userInfo);
/**
* Assemble a token introspection result from the given refresh token and user info.
*
* @param refreshToken the refresh token
* @param userInfo the user info
* @return the token introspection result
*/
Map<String, Object> assembleFrom(OAuth2RefreshTokenEntity refreshToken, UserInfo userInfo);
}

View File

@ -37,6 +37,10 @@ import com.google.gson.JsonObject;
})
public class DefaultUserInfo implements UserInfo {
/**
*
*/
private static final long serialVersionUID = 6078310513185681918L;
private Long id;
private String sub;
private String preferredUsername;

View File

@ -31,32 +31,32 @@ public interface MITREidDataService {
* Data member for 1.X configurations
*/
public static final String MITREID_CONNECT_1_0 = "mitreid-connect-1.0";
public static final String MITREID_CONNECT_1_1 = "mitreid-connect-1.1";
public static final String MITREID_CONNECT_1_2 = "mitreid-connect-1.2";
public static final String MITREID_CONNECT_1_1 = "mitreid-connect-1.1";
public static final String MITREID_CONNECT_1_2 = "mitreid-connect-1.2";
// member names
public static final String REFRESHTOKENS = "refreshTokens";
public static final String ACCESSTOKENS = "accessTokens";
public static final String WHITELISTEDSITES = "whitelistedSites";
public static final String BLACKLISTEDSITES = "blacklistedSites";
public static final String AUTHENTICATIONHOLDERS = "authenticationHolders";
public static final String GRANTS = "grants";
public static final String CLIENTS = "clients";
public static final String SYSTEMSCOPES = "systemScopes";
// member names
public static final String REFRESHTOKENS = "refreshTokens";
public static final String ACCESSTOKENS = "accessTokens";
public static final String WHITELISTEDSITES = "whitelistedSites";
public static final String BLACKLISTEDSITES = "blacklistedSites";
public static final String AUTHENTICATIONHOLDERS = "authenticationHolders";
public static final String GRANTS = "grants";
public static final String CLIENTS = "clients";
public static final 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;
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;
void importData(JsonReader reader) throws IOException;
}

View File

@ -50,42 +50,42 @@ public class TestJWKSetKeyStore {
private String RSAkid = "rsa_1";
private JWK RSAjwk = new RSAKey(
new Base64URL("oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUW" +
"cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" +
"psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" +
"sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" +
"tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" +
"YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n
"cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" +
"psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" +
"sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" +
"tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" +
"YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n
new Base64URL("AQAB"), // e
new Base64URL("kLdtIj6GbDks_ApCSTYQtelcNttlKiOyPzMrXHeI-yk1F7-kpDxY4-WY5N" +
"WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" +
"3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" +
"qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" +
"t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" +
"VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d
KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA_OAEP, RSAkid, null, null, null);
"WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" +
"3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" +
"qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" +
"t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" +
"VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d
KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA_OAEP, RSAkid, null, null, null);
private String RSAkid_rsa2 = "rsa_2";
private JWK RSAjwk_rsa2 = new RSAKey(
new Base64URL("oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUW" +
"cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" +
"psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" +
"sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" +
"tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" +
"YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n
"cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" +
"psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" +
"sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" +
"tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" +
"YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n
new Base64URL("AQAB"), // e
new Base64URL("kLdtIj6GbDks_ApCSTYQtelcNttlKiOyPzMrXHeI-yk1F7-kpDxY4-WY5N" +
"WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" +
"3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" +
"qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" +
"t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" +
"VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d
KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA1_5, RSAkid_rsa2, null, null, null);
"WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" +
"3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" +
"qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" +
"t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" +
"VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d
KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA1_5, RSAkid_rsa2, null, null, null);
List<JWK> keys_list = new LinkedList<JWK>();
private JWKSet jwkSet;
private String ks_file = "ks.txt";
private String ks_file_badJWK = "ks_badJWK.txt";
List<JWK> keys_list = new LinkedList<JWK>();
private JWKSet jwkSet;
private String ks_file = "ks.txt";
private String ks_file_badJWK = "ks_badJWK.txt";
@Before
public void prepare() throws IOException {
@ -101,8 +101,8 @@ public class TestJWKSetKeyStore {
out.close();
}
@After
public void cleanup() throws IOException {
@After
public void cleanup() throws IOException {
File f1 = new File(ks_file);
if (f1.exists()) {
@ -112,7 +112,7 @@ public class TestJWKSetKeyStore {
if (f2.exists()) {
f2.delete();
}
}
}
/* Constructors with no valid Resource setup */
@Test
@ -126,7 +126,7 @@ public class TestJWKSetKeyStore {
boolean thrown = false;
try {
JWKSetKeyStore ks_null = new JWKSetKeyStore(null);
new JWKSetKeyStore(null);
} catch (IllegalArgumentException e) {
thrown = true;
}
@ -162,36 +162,36 @@ public class TestJWKSetKeyStore {
/* First, test with file without "read" permission */
boolean set = false;
boolean set = false;
if (file.exists()) {
set = file.setReadable(false);
}
if (file.exists()) {
set = file.setReadable(false);
}
// skip this part of the test on systems that don't allow the settable function, like Windows
if (set) {
// skip this part of the test on systems that don't allow the settable function, like Windows
if (set) {
Resource loc_noread = new FileSystemResource(file);
assertTrue(loc_noread.exists());
// assertTrue(!loc_noread.isReadable());
Resource loc_noread = new FileSystemResource(file);
assertTrue(loc_noread.exists());
// assertTrue(!loc_noread.isReadable());
boolean thrown = false;
try {
ks.setLocation(loc_noread);
} catch (IllegalArgumentException e) {
thrown = true;
}
assertTrue(thrown);
boolean thrown = false;
try {
ks.setLocation(loc_noread);
} catch (IllegalArgumentException e) {
thrown = true;
}
assertTrue(thrown);
/* Now, make cache file readable */
/* Now, make cache file readable */
if (file.exists()) {
file.setReadable(true);
}
if (file.exists()) {
file.setReadable(true);
}
}
}
Resource loc = new FileSystemResource(file);
Resource loc = new FileSystemResource(file);
assertTrue(loc.exists());
assertTrue(loc.isReadable());

View File

@ -78,37 +78,38 @@ public class TestDefaultJwtEncryptionAndDecryptionService {
"XFBoMYUZodetZdvTiFvSkQ";
private String RSAkid = "rsa321";
private JWK RSAjwk = new RSAKey(new Base64URL("oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUW" +
"cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" +
"psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" +
"sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" +
"tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" +
"YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n
private JWK RSAjwk = new RSAKey(
new Base64URL("oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUW" +
"cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" +
"psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" +
"sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" +
"tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" +
"YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n
new Base64URL("AQAB"), // e
new Base64URL("kLdtIj6GbDks_ApCSTYQtelcNttlKiOyPzMrXHeI-yk1F7-kpDxY4-WY5N" +
"WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" +
"3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" +
"qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" +
"t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" +
"VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d
KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA_OAEP, RSAkid, null, null, null);
"WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" +
"3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" +
"qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" +
"t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" +
"VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d
KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA_OAEP, RSAkid, null, null, null);
private String RSAkid_2 = "rsa3210";
private JWK RSAjwk_2 = new RSAKey(
new Base64URL("oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUW" +
"cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" +
"psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" +
"sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" +
"tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" +
"YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n
"cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" +
"psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" +
"sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" +
"tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" +
"YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n
new Base64URL("AQAB"), // e
new Base64URL("kLdtIj6GbDks_ApCSTYQtelcNttlKiOyPzMrXHeI-yk1F7-kpDxY4-WY5N" +
"WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" +
"3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" +
"qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" +
"t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" +
"VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d
KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA1_5, RSAkid_2, null, null, null);
"WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" +
"3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" +
"qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" +
"t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" +
"VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d
KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA1_5, RSAkid_2, null, null, null);
private String AESkid = "aes123";
private JWK AESjwk = new OctetSequenceKey( new Base64URL("GawgguFyGrWKav7AX4VKUg"),
@ -290,13 +291,13 @@ public class TestDefaultJwtEncryptionAndDecryptionService {
Map<String,JWK> keys2check = service_2.getAllPublicKeys();
assertEquals(
JSONObjectUtils.getString(RSAjwk.toPublicJWK().toJSONObject(), "e"),
JSONObjectUtils.getString(keys2check.get(RSAkid).toJSONObject(), "e")
);
JSONObjectUtils.getString(RSAjwk.toPublicJWK().toJSONObject(), "e"),
JSONObjectUtils.getString(keys2check.get(RSAkid).toJSONObject(), "e")
);
assertEquals(
JSONObjectUtils.getString(RSAjwk_2.toPublicJWK().toJSONObject(), "e"),
JSONObjectUtils.getString(keys2check.get(RSAkid_2).toJSONObject(), "e")
);
JSONObjectUtils.getString(RSAjwk_2.toPublicJWK().toJSONObject(), "e"),
JSONObjectUtils.getString(keys2check.get(RSAkid_2).toJSONObject(), "e")
);
assertTrue(service_3.getAllPublicKeys().isEmpty());
}

View File

@ -263,7 +263,7 @@ public class DiscoveryEndpoint {
Collection<JWSAlgorithm> serverSigningAlgs = signService.getAllSigningAlgsSupported();
Collection<JWSAlgorithm> clientSymmetricSigningAlgs = Lists.newArrayList(JWSAlgorithm.HS256, JWSAlgorithm.HS384, JWSAlgorithm.HS512);
Collection<JWSAlgorithm> clientSymmetricAndAsymmetricSigningAlgs = Lists.newArrayList(JWSAlgorithm.HS256, JWSAlgorithm.HS384, JWSAlgorithm.HS512, JWSAlgorithm.RS256, JWSAlgorithm.RS384, JWSAlgorithm.RS512);
Collection<Algorithm> clientSymmetricAndAsymmetricSigningAlgsWithNone = Lists.newArrayList(JWSAlgorithm.HS256, JWSAlgorithm.HS384, JWSAlgorithm.HS512, JWSAlgorithm.RS256, JWSAlgorithm.RS384, JWSAlgorithm.RS512, JWSAlgorithm.NONE);
Collection<Algorithm> clientSymmetricAndAsymmetricSigningAlgsWithNone = Lists.newArrayList(JWSAlgorithm.HS256, JWSAlgorithm.HS384, JWSAlgorithm.HS512, JWSAlgorithm.RS256, JWSAlgorithm.RS384, JWSAlgorithm.RS512, Algorithm.NONE);
Map<String, Object> m = new HashMap<String, Object>();
m.put("issuer", config.getIssuer());

View File

@ -38,11 +38,11 @@ public class JpaAuthenticationHolderRepository implements AuthenticationHolderRe
@PersistenceContext
private EntityManager manager;
@Override
public List<AuthenticationHolderEntity> getAll() {
@Override
public List<AuthenticationHolderEntity> getAll() {
TypedQuery<AuthenticationHolderEntity> query = manager.createNamedQuery("AuthenticationHolderEntity.getAll", AuthenticationHolderEntity.class);
return query.getResultList();
}
}
@Override
public AuthenticationHolderEntity getById(Long id) {

View File

@ -45,74 +45,74 @@ public class DefaultIntrospectionResultAssembler implements IntrospectionResultA
private static DateFormatter dateFormat = new DateFormatter(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"));
@Override
public Map<String, Object> assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo) {
@Override
public Map<String, Object> assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo) {
Map<String, Object> result = newLinkedHashMap();
OAuth2Authentication authentication = accessToken.getAuthenticationHolder().getAuthentication();
Map<String, Object> result = newLinkedHashMap();
OAuth2Authentication authentication = accessToken.getAuthenticationHolder().getAuthentication();
result.put("active", true);
result.put("active", true);
result.put("scope", Joiner.on(" ").join(accessToken.getScope()));
result.put("scope", Joiner.on(" ").join(accessToken.getScope()));
if (accessToken.getExpiration() != null) {
try {
if (accessToken.getExpiration() != null) {
try {
result.put("expires_at", dateFormat.valueToString(accessToken.getExpiration()));
result.put("exp", accessToken.getExpiration().getTime() / 1000L);
} catch (ParseException e) {
log.error("Parse exception in token introspection", e);
}
}
}
if (userInfo != null) {
// if we have a UserInfo, use that for the subject
result.put("sub", userInfo.getSub());
} else {
// otherwise, use the authentication's username
result.put("sub", authentication.getName());
}
if (userInfo != null) {
// if we have a UserInfo, use that for the subject
result.put("sub", userInfo.getSub());
} else {
// otherwise, use the authentication's username
result.put("sub", authentication.getName());
}
result.put("user_id", authentication.getName());
result.put("user_id", authentication.getName());
result.put("client_id", authentication.getOAuth2Request().getClientId());
result.put("client_id", authentication.getOAuth2Request().getClientId());
result.put("token_type", accessToken.getTokenType());
result.put("token_type", accessToken.getTokenType());
return result;
}
return result;
}
@Override
public Map<String, Object> assembleFrom(OAuth2RefreshTokenEntity refreshToken, UserInfo userInfo) {
@Override
public Map<String, Object> assembleFrom(OAuth2RefreshTokenEntity refreshToken, UserInfo userInfo) {
Map<String, Object> result = newLinkedHashMap();
OAuth2Authentication authentication = refreshToken.getAuthenticationHolder().getAuthentication();
Map<String, Object> result = newLinkedHashMap();
OAuth2Authentication authentication = refreshToken.getAuthenticationHolder().getAuthentication();
result.put("active", true);
result.put("active", true);
result.put("scope", Joiner.on(" ").join(authentication.getOAuth2Request().getScope()));
result.put("scope", Joiner.on(" ").join(authentication.getOAuth2Request().getScope()));
if (refreshToken.getExpiration() != null) {
try {
if (refreshToken.getExpiration() != null) {
try {
result.put("expires_at", dateFormat.valueToString(refreshToken.getExpiration()));
result.put("exp", refreshToken.getExpiration().getTime() / 1000L);
} catch (ParseException e) {
log.error("Parse exception in token introspection", e);
}
}
}
if (userInfo != null) {
// if we have a UserInfo, use that for the subject
result.put("sub", userInfo.getSub());
} else {
// otherwise, use the authentication's username
result.put("sub", authentication.getName());
}
if (userInfo != null) {
// if we have a UserInfo, use that for the subject
result.put("sub", userInfo.getSub());
} else {
// otherwise, use the authentication's username
result.put("sub", authentication.getName());
}
result.put("user_id", authentication.getName());
result.put("user_id", authentication.getName());
result.put("client_id", authentication.getOAuth2Request().getClientId());
result.put("client_id", authentication.getOAuth2Request().getClientId());
return result;
}
return result;
}
}

View File

@ -52,7 +52,6 @@ import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

View File

@ -16,8 +16,10 @@
*******************************************************************************/
package org.mitre.oauth2.web;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import java.security.Principal;
import java.util.Map;
import java.util.Set;
import org.mitre.oauth2.model.ClientDetailsEntity;
import org.mitre.oauth2.model.OAuth2AccessTokenEntity;
import org.mitre.oauth2.model.OAuth2RefreshTokenEntity;
@ -40,9 +42,8 @@ import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.security.Principal;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
@Controller
public class IntrospectionEndpoint {
@ -56,8 +57,8 @@ public class IntrospectionEndpoint {
@Autowired
private IntrospectionAuthorizer introspectionAuthorizer;
@Autowired
private IntrospectionResultAssembler introspectionResultAssembler;
@Autowired
private IntrospectionResultAssembler introspectionResultAssembler;
@Autowired
private UserInfoService userInfoService;
@ -86,8 +87,8 @@ public class IntrospectionEndpoint {
return JsonEntityView.VIEWNAME;
}
OAuth2AccessTokenEntity accessToken = null;
OAuth2RefreshTokenEntity refreshToken = null;
OAuth2AccessTokenEntity accessToken = null;
OAuth2RefreshTokenEntity refreshToken = null;
ClientDetailsEntity tokenClient;
Set<String> scopes;
UserInfo user;
@ -100,7 +101,7 @@ public class IntrospectionEndpoint {
tokenClient = accessToken.getClient();
scopes = accessToken.getScope();
user = userInfoService.getByUsernameAndClientId(accessToken.getAuthenticationHolder().getAuthentication().getName(), tokenClient.getClientId());
user = userInfoService.getByUsernameAndClientId(accessToken.getAuthenticationHolder().getAuthentication().getName(), tokenClient.getClientId());
} catch (InvalidTokenException e) {
logger.info("Verify failed; Invalid access token. Checking refresh token.");
@ -122,28 +123,28 @@ public class IntrospectionEndpoint {
}
}
// clientID is the principal name in the authentication
String clientId = p.getName();
ClientDetailsEntity authClient = clientService.loadClientByClientId(clientId);
// clientID is the principal name in the authentication
String clientId = p.getName();
ClientDetailsEntity authClient = clientService.loadClientByClientId(clientId);
if (authClient.isAllowIntrospection()) {
if (introspectionAuthorizer.isIntrospectionPermitted(authClient, tokenClient, scopes)) {
// if it's a valid token, we'll print out information on it
Map<String, Object> entity = accessToken != null
? introspectionResultAssembler.assembleFrom(accessToken, user)
: introspectionResultAssembler.assembleFrom(refreshToken, user);
model.addAttribute("entity", entity);
return JsonEntityView.VIEWNAME;
} else {
logger.error("Verify failed; client configuration or scope don't permit token introspection");
model.addAttribute("code", HttpStatus.FORBIDDEN);
return HttpCodeView.VIEWNAME;
}
} else {
logger.error("Verify failed; client " + clientId + " is not allowed to call introspection endpoint");
model.addAttribute("code", HttpStatus.FORBIDDEN);
return HttpCodeView.VIEWNAME;
}
if (authClient.isAllowIntrospection()) {
if (introspectionAuthorizer.isIntrospectionPermitted(authClient, tokenClient, scopes)) {
// if it's a valid token, we'll print out information on it
Map<String, Object> entity = accessToken != null
? introspectionResultAssembler.assembleFrom(accessToken, user)
: introspectionResultAssembler.assembleFrom(refreshToken, user);
model.addAttribute("entity", entity);
return JsonEntityView.VIEWNAME;
} else {
logger.error("Verify failed; client configuration or scope don't permit token introspection");
model.addAttribute("code", HttpStatus.FORBIDDEN);
return HttpCodeView.VIEWNAME;
}
} else {
logger.error("Verify failed; client " + clientId + " is not allowed to call introspection endpoint");
model.addAttribute("code", HttpStatus.FORBIDDEN);
return HttpCodeView.VIEWNAME;
}
}

View File

@ -19,8 +19,6 @@ package org.mitre.openid.connect.repository.impl;
import static org.mitre.util.jpa.JpaUtil.getSingleResult;
import static org.mitre.util.jpa.JpaUtil.saveOrUpdate;
import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

View File

@ -159,7 +159,7 @@ public class DefaultOIDCTokenService implements OIDCTokenService {
JWT idToken;
if (signingAlg.equals(JWSAlgorithm.NONE)) {
if (signingAlg.equals(Algorithm.NONE)) {
// unsigned ID token
idToken = new PlainJWT(idClaims);

View File

@ -16,9 +16,6 @@
*******************************************************************************/
package org.mitre.openid.connect.service.impl;
import com.google.common.io.BaseEncoding;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@ -29,10 +26,15 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.mitre.openid.connect.service.MITREidDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.io.BaseEncoding;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
/**
*
* @author arielak
@ -40,98 +42,98 @@ import org.slf4j.LoggerFactory;
public abstract class MITREidDataService_1_X implements MITREidDataService {
private static Logger logger = LoggerFactory.getLogger(MITREidDataService_1_X.class);
protected static <T> T base64UrlDecodeObject(String encoded, Class<T> type) {
if (encoded == null) {
return null;
} else {
T deserialized = null;
try {
byte[] decoded = BaseEncoding.base64Url().decode(encoded);
ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
ObjectInputStream ois = new ObjectInputStream(bais);
deserialized = type.cast(ois.readObject());
ois.close();
bais.close();
} catch (Exception ex) {
logger.error("Unable to decode object", ex);
}
return deserialized;
}
}
protected static <T> T base64UrlDecodeObject(String encoded, Class<T> type) {
if (encoded == null) {
return null;
} else {
T deserialized = null;
try {
byte[] decoded = BaseEncoding.base64Url().decode(encoded);
ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
ObjectInputStream ois = new ObjectInputStream(bais);
deserialized = type.cast(ois.readObject());
ois.close();
bais.close();
} catch (Exception ex) {
logger.error("Unable to decode object", ex);
}
return deserialized;
}
}
protected static String base64UrlEncodeObject(Serializable obj) {
if (obj == null) {
return null;
} else {
String encoded = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
encoded = BaseEncoding.base64Url().encode(baos.toByteArray());
oos.close();
baos.close();
} catch (IOException ex) {
logger.error("Unable to encode object", ex);
}
return encoded;
}
}
protected static Set readSet(JsonReader reader) throws IOException {
Set arraySet = null;
reader.beginArray();
switch (reader.peek()) {
case STRING:
arraySet = new HashSet<String>();
while (reader.hasNext()) {
arraySet.add(reader.nextString());
}
break;
case NUMBER:
arraySet = new HashSet<Long>();
while (reader.hasNext()) {
arraySet.add(reader.nextLong());
}
break;
default:
arraySet = new HashSet();
break;
}
reader.endArray();
return arraySet;
}
protected static String base64UrlEncodeObject(Serializable obj) {
if (obj == null) {
return null;
} else {
String encoded = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
encoded = BaseEncoding.base64Url().encode(baos.toByteArray());
oos.close();
baos.close();
} catch (IOException ex) {
logger.error("Unable to encode object", ex);
}
return encoded;
}
}
protected static Set readSet(JsonReader reader) throws IOException {
Set arraySet = null;
reader.beginArray();
switch (reader.peek()) {
case STRING:
arraySet = new HashSet<String>();
while (reader.hasNext()) {
arraySet.add(reader.nextString());
}
break;
case NUMBER:
arraySet = new HashSet<Long>();
while (reader.hasNext()) {
arraySet.add(reader.nextLong());
}
break;
default:
arraySet = new HashSet();
break;
}
reader.endArray();
return arraySet;
}
protected static Map readMap(JsonReader reader) throws IOException {
Map map = new HashMap<String, Object>();
reader.beginObject();
while(reader.hasNext()) {
String name = reader.nextName();
Object value = null;
switch(reader.peek()) {
case STRING:
value = reader.nextString();
break;
case BOOLEAN:
value = reader.nextBoolean();
break;
case NUMBER:
value = reader.nextLong();
break;
}
map.put(name, value);
}
reader.endObject();
return map;
}
protected static Map readMap(JsonReader reader) throws IOException {
Map map = new HashMap<String, Object>();
reader.beginObject();
while(reader.hasNext()) {
String name = reader.nextName();
Object value = null;
switch(reader.peek()) {
case STRING:
value = reader.nextString();
break;
case BOOLEAN:
value = reader.nextBoolean();
break;
case NUMBER:
value = reader.nextLong();
break;
}
map.put(name, value);
}
reader.endObject();
return map;
}
protected void writeNullSafeArray(JsonWriter writer, Set<String> items)
throws IOException {
if (items != null) {
writer.beginArray();
for (String s : items) {
writer.value(s);
}
writer.endArray();
for (String s : items) {
writer.value(s);
}
writer.endArray();
} else {
writer.nullValue();
}

View File

@ -20,6 +20,7 @@ import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -28,29 +29,29 @@ import org.slf4j.LoggerFactory;
* @author arielak
*/
public class DateUtil {
private static final Logger log = LoggerFactory.getLogger(DateUtil.class);
private static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
private static final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT);
private static final TimeZone utc = TimeZone.getTimeZone("UTC");
private static final Logger log = LoggerFactory.getLogger(DateUtil.class);
private static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
private static final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT);
private static final TimeZone utc = TimeZone.getTimeZone("UTC");
public static String toUTCString(Date date) {
if (date == null) {
return null;
}
sdf.setTimeZone(utc);
return sdf.format(date);
}
public static String toUTCString(Date date) {
if (date == null) {
return null;
}
sdf.setTimeZone(utc);
return sdf.format(date);
}
public static Date utcToDate(String s) {
if (s == null) {
return null;
}
Date d = null;
try {
d = sdf.parse(s);
} catch(ParseException ex) {
log.error("Unable to parse date string {}", s, ex);
}
return d;
}
public static Date utcToDate(String s) {
if (s == null) {
return null;
}
Date d = null;
try {
d = sdf.parse(s);
} catch(ParseException ex) {
log.error("Unable to parse date string {}", s, ex);
}
return d;
}
}

View File

@ -401,9 +401,9 @@ public class ClientDynamicRegistrationEndpoint {
// TODO: make this a pluggable service
Set<String> requestedGrantTypes = new HashSet<String>(newClient.getGrantTypes());
requestedGrantTypes.retainAll(
ImmutableSet.of("authorization_code", "implicit",
"password", "client_credentials", "refresh_token",
"urn:ietf:params:oauth:grant_type:redelegate"));
ImmutableSet.of("authorization_code", "implicit",
"password", "client_credentials", "refresh_token",
"urn:ietf:params:oauth:grant_type:redelegate"));
// don't allow "password" grant type for dynamic registration
if (newClient.getGrantTypes().contains("password")) {

View File

@ -60,13 +60,13 @@ public class DataAPI {
@Autowired
private ConfigurationPropertiesBean config;
@Autowired
@Autowired
private MITREidDataService_1_0 dataService_1_0;
@Autowired
@Autowired
private MITREidDataService_1_1 dataService_1_1;
@Autowired
@Autowired
private MITREidDataService_1_1 dataService_1_2;
@RequestMapping(method = RequestMethod.POST, consumes = "application/json")
@ -79,25 +79,25 @@ public class DataAPI {
while (reader.hasNext()) {
JsonToken tok = reader.peek();
switch (tok) {
case NAME:
String name = reader.nextName();
if (name.equals(MITREidDataService.MITREID_CONNECT_1_0)) {
dataService_1_0.importData(reader);
} else if (name.equals(MITREidDataService.MITREID_CONNECT_1_1)) {
dataService_1_1.importData(reader);
} else if (name.equals(MITREidDataService.MITREID_CONNECT_1_2)) {
dataService_1_2.importData(reader);
} else {
// consume the next bit silently for now
logger.debug("Skipping value for " + name); // TODO: write these out?
reader.skipValue();
}
break;
case END_OBJECT:
reader.endObject();
break;
case END_DOCUMENT:
break;
case NAME:
String name = reader.nextName();
if (name.equals(MITREidDataService.MITREID_CONNECT_1_0)) {
dataService_1_0.importData(reader);
} else if (name.equals(MITREidDataService.MITREID_CONNECT_1_1)) {
dataService_1_1.importData(reader);
} else if (name.equals(MITREidDataService.MITREID_CONNECT_1_2)) {
dataService_1_2.importData(reader);
} else {
// consume the next bit silently for now
logger.debug("Skipping value for " + name); // TODO: write these out?
reader.skipValue();
}
break;
case END_OBJECT:
reader.endObject();
break;
case END_DOCUMENT:
break;
}
}
@ -115,7 +115,7 @@ public class DataAPI {
try {
writer.beginObject();
writer.beginObject();
writer.name("exported-at");
writer.value(dateFormat.format(new Date()));

View File

@ -55,7 +55,6 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriUtils;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import com.google.gson.JsonSyntaxException;
@Controller

View File

@ -83,8 +83,7 @@ public class TestDefaultIntrospectionAuthorizer {
String tokenClient = "token";
Set<String> authScope = scope("scope1", "scope2");
Set<String> tokenScope = scope("scope1", "scope2", "scope3");
given(scopeService.scopesMatch(authScope, tokenScope))
.willReturn(false);
given(scopeService.scopesMatch(authScope, tokenScope)).willReturn(false);
// when
boolean permitted = introspectionPermitter.isIntrospectionPermitted(
@ -101,8 +100,7 @@ public class TestDefaultIntrospectionAuthorizer {
return client;
}
private ClientDetails clientWithIdAndScope(String clientId,
Set<String> scope) {
private ClientDetails clientWithIdAndScope(String clientId, Set<String> scope) {
ClientDetails client = clientWithId(clientId);
given(client.getScope()).willReturn(scope);
return client;

View File

@ -16,13 +16,13 @@
*******************************************************************************/
package org.mitre.oauth2.service.impl;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import org.mitre.oauth2.model.OAuth2AccessTokenEntity;
import org.mitre.oauth2.model.OAuth2RefreshTokenEntity;
import org.mitre.openid.connect.model.UserInfo;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import static com.google.common.collect.Sets.newHashSet;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@ -32,209 +32,210 @@ import java.util.Set;
import javax.swing.text.DateFormatter;
import static com.google.common.collect.Sets.newHashSet;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import org.junit.Test;
import org.mitre.oauth2.model.OAuth2AccessTokenEntity;
import org.mitre.oauth2.model.OAuth2RefreshTokenEntity;
import org.mitre.openid.connect.model.UserInfo;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import com.google.common.collect.ImmutableMap;
public class TestDefaultIntrospectionResultAssembler {
private DefaultIntrospectionResultAssembler assembler = new DefaultIntrospectionResultAssembler();
private DefaultIntrospectionResultAssembler assembler = new DefaultIntrospectionResultAssembler();
private static DateFormatter dateFormat = new DateFormatter(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"));
@Test
public void shouldAssembleExpectedResultForAccessToken() throws ParseException {
@Test
public void shouldAssembleExpectedResultForAccessToken() throws ParseException {
// given
OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), "Bearer",
authentication("name", request("clientId")));
// given
OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), "Bearer",
authentication("name", request("clientId")));
UserInfo userInfo = userInfo("sub");
UserInfo userInfo = userInfo("sub");
// when
Map<String, Object> result = assembler.assembleFrom(accessToken, userInfo);
// when
Map<String, Object> result = assembler.assembleFrom(accessToken, userInfo);
// then
Map<String, Object> expected = new ImmutableMap.Builder<String, Object>()
.put("sub", "sub")
.put("exp", 123L)
.put("expires_at", dateFormat.valueToString(new Date(123 * 1000L)))
.put("scope", "bar foo")
.put("active", Boolean.TRUE)
.put("user_id", "name")
.put("client_id", "clientId")
.put("token_type", "Bearer")
.build();
assertThat(result, is(equalTo(expected)));
}
// then
Map<String, Object> expected = new ImmutableMap.Builder<String, Object>()
.put("sub", "sub")
.put("exp", 123L)
.put("expires_at", dateFormat.valueToString(new Date(123 * 1000L)))
.put("scope", "bar foo")
.put("active", Boolean.TRUE)
.put("user_id", "name")
.put("client_id", "clientId")
.put("token_type", "Bearer")
.build();
assertThat(result, is(equalTo(expected)));
}
@Test
public void shouldAssembleExpectedResultForAccessTokenWithoutUserInfo() throws ParseException {
@Test
public void shouldAssembleExpectedResultForAccessTokenWithoutUserInfo() throws ParseException {
// given
OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), "Bearer",
authentication("name", request("clientId")));
// given
OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), "Bearer",
authentication("name", request("clientId")));
// when
Map<String, Object> result = assembler.assembleFrom(accessToken, null);
// when
Map<String, Object> result = assembler.assembleFrom(accessToken, null);
// then
Map<String, Object> expected = new ImmutableMap.Builder<String, Object>()
.put("sub", "name")
.put("exp", 123L)
.put("expires_at", dateFormat.valueToString(new Date(123 * 1000L)))
.put("scope", "bar foo")
.put("active", Boolean.TRUE)
.put("user_id", "name")
.put("client_id", "clientId")
.put("token_type", "Bearer")
.build();
assertThat(result, is(equalTo(expected)));
}
// then
Map<String, Object> expected = new ImmutableMap.Builder<String, Object>()
.put("sub", "name")
.put("exp", 123L)
.put("expires_at", dateFormat.valueToString(new Date(123 * 1000L)))
.put("scope", "bar foo")
.put("active", Boolean.TRUE)
.put("user_id", "name")
.put("client_id", "clientId")
.put("token_type", "Bearer")
.build();
assertThat(result, is(equalTo(expected)));
}
@Test
public void shouldAssembleExpectedResultForAccessTokenWithoutExpiry() {
@Test
public void shouldAssembleExpectedResultForAccessTokenWithoutExpiry() {
// given
OAuth2AccessTokenEntity accessToken = accessToken(null, scopes("foo", "bar"), "Bearer",
authentication("name", request("clientId")));
// given
OAuth2AccessTokenEntity accessToken = accessToken(null, scopes("foo", "bar"), "Bearer",
authentication("name", request("clientId")));
UserInfo userInfo = userInfo("sub");
UserInfo userInfo = userInfo("sub");
// when
Map<String, Object> result = assembler.assembleFrom(accessToken, userInfo);
// when
Map<String, Object> result = assembler.assembleFrom(accessToken, userInfo);
// then
Map<String, Object> expected = new ImmutableMap.Builder<String, Object>()
.put("sub", "sub")
.put("scope", "bar foo")
.put("active", Boolean.TRUE)
.put("user_id", "name")
.put("client_id", "clientId")
.put("token_type", "Bearer")
.build();
assertThat(result, is(equalTo(expected)));
}
// then
Map<String, Object> expected = new ImmutableMap.Builder<String, Object>()
.put("sub", "sub")
.put("scope", "bar foo")
.put("active", Boolean.TRUE)
.put("user_id", "name")
.put("client_id", "clientId")
.put("token_type", "Bearer")
.build();
assertThat(result, is(equalTo(expected)));
}
@Test
public void shouldAssembleExpectedResultForRefreshToken() throws ParseException {
@Test
public void shouldAssembleExpectedResultForRefreshToken() throws ParseException {
// given
OAuth2RefreshTokenEntity refreshToken = refreshToken(new Date(123 * 1000L),
authentication("name", request("clientId", scopes("foo", "bar"))));
// given
OAuth2RefreshTokenEntity refreshToken = refreshToken(new Date(123 * 1000L),
authentication("name", request("clientId", scopes("foo", "bar"))));
UserInfo userInfo = userInfo("sub");
UserInfo userInfo = userInfo("sub");
// when
Map<String, Object> result = assembler.assembleFrom(refreshToken, userInfo);
// when
Map<String, Object> result = assembler.assembleFrom(refreshToken, userInfo);
// then
Map<String, Object> expected = new ImmutableMap.Builder<String, Object>()
.put("sub", "sub")
.put("exp", 123L)
.put("expires_at", dateFormat.valueToString(new Date(123 * 1000L)))
.put("scope", "bar foo")
.put("active", Boolean.TRUE)
.put("user_id", "name")
.put("client_id", "clientId")
.build();
assertThat(result, is(equalTo(expected)));
}
// then
Map<String, Object> expected = new ImmutableMap.Builder<String, Object>()
.put("sub", "sub")
.put("exp", 123L)
.put("expires_at", dateFormat.valueToString(new Date(123 * 1000L)))
.put("scope", "bar foo")
.put("active", Boolean.TRUE)
.put("user_id", "name")
.put("client_id", "clientId")
.build();
assertThat(result, is(equalTo(expected)));
}
@Test
public void shouldAssembleExpectedResultForRefreshTokenWithoutUserInfo() throws ParseException {
@Test
public void shouldAssembleExpectedResultForRefreshTokenWithoutUserInfo() throws ParseException {
// given
OAuth2RefreshTokenEntity refreshToken = refreshToken(new Date(123 * 1000L),
authentication("name", request("clientId", scopes("foo", "bar"))));
// given
OAuth2RefreshTokenEntity refreshToken = refreshToken(new Date(123 * 1000L),
authentication("name", request("clientId", scopes("foo", "bar"))));
// when
Map<String, Object> result = assembler.assembleFrom(refreshToken, null);
// when
Map<String, Object> result = assembler.assembleFrom(refreshToken, null);
// then
Map<String, Object> expected = new ImmutableMap.Builder<String, Object>()
.put("sub", "name")
.put("exp", 123L)
.put("expires_at", dateFormat.valueToString(new Date(123 * 1000L)))
.put("scope", "bar foo")
.put("active", Boolean.TRUE)
.put("user_id", "name")
.put("client_id", "clientId")
.build();
assertThat(result, is(equalTo(expected)));
}
// then
Map<String, Object> expected = new ImmutableMap.Builder<String, Object>()
.put("sub", "name")
.put("exp", 123L)
.put("expires_at", dateFormat.valueToString(new Date(123 * 1000L)))
.put("scope", "bar foo")
.put("active", Boolean.TRUE)
.put("user_id", "name")
.put("client_id", "clientId")
.build();
assertThat(result, is(equalTo(expected)));
}
@Test
public void shouldAssembleExpectedResultForRefreshTokenWithoutExpiry() {
@Test
public void shouldAssembleExpectedResultForRefreshTokenWithoutExpiry() {
// given
OAuth2RefreshTokenEntity refreshToken = refreshToken(null,
authentication("name", request("clientId", scopes("foo", "bar"))));
// given
OAuth2RefreshTokenEntity refreshToken = refreshToken(null,
authentication("name", request("clientId", scopes("foo", "bar"))));
UserInfo userInfo = userInfo("sub");
UserInfo userInfo = userInfo("sub");
// when
Map<String, Object> result = assembler.assembleFrom(refreshToken, userInfo);
// when
Map<String, Object> result = assembler.assembleFrom(refreshToken, userInfo);
// then
Map<String, Object> expected = new ImmutableMap.Builder<String, Object>()
.put("sub", "sub")
.put("scope", "bar foo")
.put("active", Boolean.TRUE)
.put("user_id", "name")
.put("client_id", "clientId")
.build();
assertThat(result, is(equalTo(expected)));
}
// then
Map<String, Object> expected = new ImmutableMap.Builder<String, Object>()
.put("sub", "sub")
.put("scope", "bar foo")
.put("active", Boolean.TRUE)
.put("user_id", "name")
.put("client_id", "clientId")
.build();
assertThat(result, is(equalTo(expected)));
}
private UserInfo userInfo(String sub) {
UserInfo userInfo = mock(UserInfo.class);
given(userInfo.getSub()).willReturn(sub);
return userInfo;
}
private UserInfo userInfo(String sub) {
UserInfo userInfo = mock(UserInfo.class);
given(userInfo.getSub()).willReturn(sub);
return userInfo;
}
private OAuth2AccessTokenEntity accessToken(Date exp, Set<String> scopes, String tokenType, OAuth2Authentication authentication) {
OAuth2AccessTokenEntity accessToken = mock(OAuth2AccessTokenEntity.class, RETURNS_DEEP_STUBS);
given(accessToken.getExpiration()).willReturn(exp);
given(accessToken.getScope()).willReturn(scopes);
given(accessToken.getTokenType()).willReturn(tokenType);
given(accessToken.getAuthenticationHolder().getAuthentication()).willReturn(authentication);
return accessToken;
}
private OAuth2AccessTokenEntity accessToken(Date exp, Set<String> scopes, String tokenType, OAuth2Authentication authentication) {
OAuth2AccessTokenEntity accessToken = mock(OAuth2AccessTokenEntity.class, RETURNS_DEEP_STUBS);
given(accessToken.getExpiration()).willReturn(exp);
given(accessToken.getScope()).willReturn(scopes);
given(accessToken.getTokenType()).willReturn(tokenType);
given(accessToken.getAuthenticationHolder().getAuthentication()).willReturn(authentication);
return accessToken;
}
private OAuth2RefreshTokenEntity refreshToken(Date exp, OAuth2Authentication authentication) {
OAuth2RefreshTokenEntity refreshToken = mock(OAuth2RefreshTokenEntity.class, RETURNS_DEEP_STUBS);
given(refreshToken.getExpiration()).willReturn(exp);
given(refreshToken.getAuthenticationHolder().getAuthentication()).willReturn(authentication);
return refreshToken;
}
private OAuth2RefreshTokenEntity refreshToken(Date exp, OAuth2Authentication authentication) {
OAuth2RefreshTokenEntity refreshToken = mock(OAuth2RefreshTokenEntity.class, RETURNS_DEEP_STUBS);
given(refreshToken.getExpiration()).willReturn(exp);
given(refreshToken.getAuthenticationHolder().getAuthentication()).willReturn(authentication);
return refreshToken;
}
private OAuth2Authentication authentication(String name, OAuth2Request request) {
OAuth2Authentication authentication = mock(OAuth2Authentication.class);
given(authentication.getName()).willReturn(name);
given(authentication.getOAuth2Request()).willReturn(request);
return authentication;
}
private OAuth2Authentication authentication(String name, OAuth2Request request) {
OAuth2Authentication authentication = mock(OAuth2Authentication.class);
given(authentication.getName()).willReturn(name);
given(authentication.getOAuth2Request()).willReturn(request);
return authentication;
}
private OAuth2Request request(String clientId) {
return request(clientId, null);
}
private OAuth2Request request(String clientId) {
return request(clientId, null);
}
private OAuth2Request request(String clientId, Set<String> scopes) {
return new OAuth2Request(null, clientId, null, true, scopes, null, null, null, null);
}
private OAuth2Request request(String clientId, Set<String> scopes) {
return new OAuth2Request(null, clientId, null, true, scopes, null, null, null, null);
}
private Set<String> scopes(String... scopes) {
return newHashSet(scopes);
}
private Set<String> scopes(String... scopes) {
return newHashSet(scopes);
}
}

View File

@ -83,7 +83,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
public void prepare() {
Mockito.reset(clientRepository, tokenRepository, approvedSiteService, whitelistedSiteService, blacklistedSiteService, scopeService, statsService);
Mockito.when(clientRepository.saveClient(Mockito.any(ClientDetailsEntity.class))).thenAnswer(new Answer<ClientDetailsEntity>() {
Mockito.when(clientRepository.saveClient(Matchers.any(ClientDetailsEntity.class))).thenAnswer(new Answer<ClientDetailsEntity>() {
@Override
public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
@ -91,7 +91,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
}
});
Mockito.when(clientRepository.updateClient(Mockito.anyLong(), Mockito.any(ClientDetailsEntity.class))).thenAnswer(new Answer<ClientDetailsEntity>() {
Mockito.when(clientRepository.updateClient(Matchers.anyLong(), Matchers.any(ClientDetailsEntity.class))).thenAnswer(new Answer<ClientDetailsEntity>() {
@Override
public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
@ -99,7 +99,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService {
}
});
Mockito.when(scopeService.removeRestrictedScopes(Mockito.anySet())).thenAnswer(new Answer<Set<String>>() {
Mockito.when(scopeService.removeRestrictedScopes(Matchers.anySet())).thenAnswer(new Answer<Set<String>>() {
@Override
public Set<String> answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();

View File

@ -147,8 +147,8 @@ public class TestDefaultOAuth2ProviderTokenService {
Mockito.when(scopeService.removeRestrictedScopes(Matchers.anySet())).then(AdditionalAnswers.returnsFirstArg());
Mockito.when(tokenEnhancer.enhance(Matchers.any(OAuth2AccessTokenEntity.class), Matchers.any(OAuth2Authentication.class)))
.thenAnswer(new Answer<OAuth2AccessTokenEntity>(){
@Override
.thenAnswer(new Answer<OAuth2AccessTokenEntity>(){
@Override
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (OAuth2AccessTokenEntity) args[0];
@ -156,23 +156,23 @@ public class TestDefaultOAuth2ProviderTokenService {
});
Mockito.when(tokenRepository.saveAccessToken(Matchers.any(OAuth2AccessTokenEntity.class)))
.thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
@Override
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (OAuth2AccessTokenEntity) args[0];
}
.thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
@Override
public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (OAuth2AccessTokenEntity) args[0];
}
});
});
Mockito.when(tokenRepository.saveRefreshToken(Matchers.any(OAuth2RefreshTokenEntity.class)))
.thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
@Override
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (OAuth2RefreshTokenEntity) args[0];
}
});
.thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
@Override
public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (OAuth2RefreshTokenEntity) args[0];
}
});
}
@ -222,7 +222,7 @@ public class TestDefaultOAuth2ProviderTokenService {
Mockito.verify(clientDetailsService).loadClientByClientId(Matchers.anyString());
Mockito.verify(authenticationHolderRepository).save(Matchers.any(AuthenticationHolderEntity.class));
Mockito.verify(tokenEnhancer).enhance(Matchers.any(OAuth2AccessTokenEntity.class), Mockito.eq(authentication));
Mockito.verify(tokenEnhancer).enhance(Matchers.any(OAuth2AccessTokenEntity.class), Matchers.eq(authentication));
Mockito.verify(tokenRepository).saveAccessToken(Matchers.any(OAuth2AccessTokenEntity.class));
Mockito.verify(tokenRepository, Mockito.never()).saveRefreshToken(Matchers.any(OAuth2RefreshTokenEntity.class));

View File

@ -58,7 +58,7 @@ public class TestIdTokenHashUtils {
claims.setIssuer("www.example.com");
claims.setSubject("example_user");
claims.setClaim("alg", "HS256");
*/
*/
Mockito.when(mockToken256.getJwt()).thenReturn(JWTParser.parse("eyJhbGciOiJub25lIn0.eyJhbGciOiJIUzI1NiIsInN1YiI6ImV4YW1wbGVfdXNlciIsImlzcyI6Ind3dy5leGFtcGxlLmNvbSIsInR5cCI6IkpXVCJ9."));
/*
@ -85,12 +85,7 @@ public class TestIdTokenHashUtils {
@Test
public void getAccessTokenHash256() {
/*
* independently generate hash
ascii of token = eyJhbGciOiJub25lIn0.eyJhbGciOiJIUzI1NiIsInN1YiI6ImV4YW1wbGVfdXNlciIsImlzcyI6Ind3dy5leGFtcGxlLmNvbSIsInR5cCI6IkpXVCJ9.
base64url of hash = EP1gXNeESRH-n57baopfTQ
*/
String token = mockToken256.getJwt().serialize();
mockToken256.getJwt().serialize();
Base64URL expectedHash = new Base64URL("EP1gXNeESRH-n57baopfTQ");
Base64URL resultHash = IdTokenHashUtils.getAccessTokenHash(JWSAlgorithm.HS256, mockToken256);
@ -107,7 +102,7 @@ public class TestIdTokenHashUtils {
base64url of hash = BWfFK73PQI36M1rg9R6VjMyWOE0-XvBK
*/
String token = mockToken384.getJwt().serialize();
mockToken384.getJwt().serialize();
Base64URL expectedHash = new Base64URL("BWfFK73PQI36M1rg9R6VjMyWOE0-XvBK");
Base64URL resultHash = IdTokenHashUtils.getAccessTokenHash(JWSAlgorithm.ES384, mockToken384);
@ -124,7 +119,7 @@ public class TestIdTokenHashUtils {
base64url of hash = vGH3QMY-knpACkLgzdkTqu3C9jtvbf2Wk_RSu2vAx8k
*/
String token = mockToken512.getJwt().serialize();
mockToken512.getJwt().serialize();
Base64URL expectedHash = new Base64URL("vGH3QMY-knpACkLgzdkTqu3C9jtvbf2Wk_RSu2vAx8k");
Base64URL resultHash = IdTokenHashUtils.getAccessTokenHash(JWSAlgorithm.RS512, mockToken512);