Applied code cleanup

pull/477/head
Amanda Anganes 2013-07-12 16:58:41 -04:00
parent 3e23967b46
commit 15aea61fbe
160 changed files with 15273 additions and 9048 deletions

View File

@ -28,177 +28,177 @@ import com.google.gson.JsonParser;
public class IntrospectingTokenService implements ResourceServerTokenServices { public class IntrospectingTokenService implements ResourceServerTokenServices {
private String clientId; private String clientId;
private String clientSecret; private String clientSecret;
private String introspectionUrl; private String introspectionUrl;
// Inner class to store in the hash map // Inner class to store in the hash map
private class TokenCacheObject { OAuth2AccessToken token; OAuth2Authentication auth; private class TokenCacheObject { OAuth2AccessToken token; OAuth2Authentication auth;
private TokenCacheObject(OAuth2AccessToken token, OAuth2Authentication auth) { private TokenCacheObject(OAuth2AccessToken token, OAuth2Authentication auth) {
this.token = token; this.token = token;
this.auth = auth; this.auth = auth;
} }
} }
private Map<String, TokenCacheObject> authCache = new HashMap<String, TokenCacheObject>(); private Map<String, TokenCacheObject> authCache = new HashMap<String, TokenCacheObject>();
public String getIntrospectionUrl() { public String getIntrospectionUrl() {
return introspectionUrl; return introspectionUrl;
} }
public void setIntrospectionUrl(String introspectionUrl) { public void setIntrospectionUrl(String introspectionUrl) {
this.introspectionUrl = introspectionUrl; this.introspectionUrl = introspectionUrl;
} }
public String getClientId() { public String getClientId() {
return clientId; return clientId;
} }
public void setClientId(String clientId) { public void setClientId(String clientId) {
this.clientId = clientId; this.clientId = clientId;
} }
public String getClientSecret() { public String getClientSecret() {
return clientSecret; return clientSecret;
} }
public void setClientSecret(String clientSecret) { public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret; this.clientSecret = clientSecret;
} }
// Check if there is a token and authentication in the cache // Check if there is a token and authentication in the cache
// and check if it is not expired. // and check if it is not expired.
private TokenCacheObject checkCache(String key) { private TokenCacheObject checkCache(String key) {
if(authCache.containsKey(key)) { if(authCache.containsKey(key)) {
TokenCacheObject tco = authCache.get(key); TokenCacheObject tco = authCache.get(key);
if (tco.token.getExpiration().after(new Date())) { if (tco.token.getExpiration().after(new Date())) {
return tco; return tco;
} else { } else {
// if the token is expired, don't keep things around. // if the token is expired, don't keep things around.
authCache.remove(key); authCache.remove(key);
} }
} }
return null; return null;
} }
private OAuth2Request createStoredRequest(final JsonObject token) { private OAuth2Request createStoredRequest(final JsonObject token) {
clientId = token.get("client_id").getAsString(); clientId = token.get("client_id").getAsString();
Set<String> scopes = new HashSet<String>(); Set<String> scopes = new HashSet<String>();
for (JsonElement e : token.get("scope").getAsJsonArray()) { for (JsonElement e : token.get("scope").getAsJsonArray()) {
scopes.add(e.getAsString()); scopes.add(e.getAsString());
} }
Map<String, String> parameters = new HashMap<String, String>(); Map<String, String> parameters = new HashMap<String, String>();
parameters.put("client_id", clientId); parameters.put("client_id", clientId);
parameters.put("scope", OAuth2Utils.formatParameterList(scopes)); parameters.put("scope", OAuth2Utils.formatParameterList(scopes));
OAuth2Request storedRequest = new OAuth2Request(parameters, clientId, null, true, scopes, null, null, null); OAuth2Request storedRequest = new OAuth2Request(parameters, clientId, null, true, scopes, null, null, null);
return storedRequest; return storedRequest;
} }
// create a default authentication object with authority ROLE_API // create a default authentication object with authority ROLE_API
private Authentication createAuthentication(JsonObject token){ private Authentication createAuthentication(JsonObject token){
// TODO: make role/authority configurable somehow // TODO: make role/authority configurable somehow
return new PreAuthenticatedAuthenticationToken(token.get("subject").getAsString(), null, AuthorityUtils.createAuthorityList("ROLE_API")); return new PreAuthenticatedAuthenticationToken(token.get("subject").getAsString(), null, AuthorityUtils.createAuthorityList("ROLE_API"));
} }
private OAuth2AccessToken createAccessToken(final JsonObject token, final String tokenString){ private OAuth2AccessToken createAccessToken(final JsonObject token, final String tokenString){
OAuth2AccessToken accessToken = new OAuth2AccessTokenImpl(token, tokenString); OAuth2AccessToken accessToken = new OAuth2AccessTokenImpl(token, tokenString);
return accessToken; return accessToken;
} }
// Validate a token string against the introspection endpoint, // Validate a token string against the introspection endpoint,
// then parse it and store it in the local cache. Return true on // then parse it and store it in the local cache. Return true on
// sucess, false otherwise. // sucess, false otherwise.
private boolean parseToken(String accessToken) { private boolean parseToken(String accessToken) {
String validatedToken = null; String validatedToken = null;
// Use the SpringFramework RestTemplate to send the request to the endpoint // Use the SpringFramework RestTemplate to send the request to the endpoint
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
form.add("token",accessToken); form.add("token",accessToken);
form.add("client_id", this.clientId); form.add("client_id", this.clientId);
form.add("client_secret", this.clientSecret); form.add("client_secret", this.clientSecret);
try { try {
validatedToken = restTemplate.postForObject(introspectionUrl, form, String.class); validatedToken = restTemplate.postForObject(introspectionUrl, form, String.class);
} catch (RestClientException rce) { } catch (RestClientException rce) {
// TODO: LOG THIS!? // TODO: LOG THIS!?
LoggerFactory.getLogger(IntrospectingTokenService.class).error("validateToken", rce); LoggerFactory.getLogger(IntrospectingTokenService.class).error("validateToken", rce);
} }
if (validatedToken != null) { if (validatedToken != null) {
// parse the json // parse the json
JsonElement jsonRoot = new JsonParser().parse(validatedToken); JsonElement jsonRoot = new JsonParser().parse(validatedToken);
if (!jsonRoot.isJsonObject()) { if (!jsonRoot.isJsonObject()) {
return false; // didn't get a proper JSON object return false; // didn't get a proper JSON object
} }
JsonObject tokenResponse = jsonRoot.getAsJsonObject(); JsonObject tokenResponse = jsonRoot.getAsJsonObject();
if (tokenResponse.get("error") != null) { if (tokenResponse.get("error") != null) {
// report an error? // report an error?
return false; return false;
} }
if (!tokenResponse.get("valid").getAsBoolean()){ if (!tokenResponse.get("valid").getAsBoolean()){
// non-valid token // non-valid token
return false; return false;
} }
// create an OAuth2Authentication // create an OAuth2Authentication
OAuth2Authentication auth = new OAuth2Authentication(createStoredRequest(tokenResponse), createAuthentication(tokenResponse)); OAuth2Authentication auth = new OAuth2Authentication(createStoredRequest(tokenResponse), createAuthentication(tokenResponse));
// create an OAuth2AccessToken // create an OAuth2AccessToken
OAuth2AccessToken token = createAccessToken(tokenResponse, accessToken); OAuth2AccessToken token = createAccessToken(tokenResponse, accessToken);
if (token.getExpiration().after(new Date())){ if (token.getExpiration().after(new Date())){
// Store them in the cache // Store them in the cache
authCache.put(accessToken, new TokenCacheObject(token,auth)); authCache.put(accessToken, new TokenCacheObject(token,auth));
return true; return true;
} }
} }
// If we never put a token and an authentication in the cache... // If we never put a token and an authentication in the cache...
return false; return false;
} }
@Override @Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException { public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {
// First check if the in memory cache has an Authentication object, and that it is still valid // First check if the in memory cache has an Authentication object, and that it is still valid
// If Valid, return it // If Valid, return it
TokenCacheObject cacheAuth = checkCache(accessToken); TokenCacheObject cacheAuth = checkCache(accessToken);
if (cacheAuth != null) { if (cacheAuth != null) {
return cacheAuth.auth; return cacheAuth.auth;
} else { } else {
if (parseToken(accessToken)) { if (parseToken(accessToken)) {
cacheAuth = authCache.get(accessToken); cacheAuth = authCache.get(accessToken);
if (cacheAuth != null && (cacheAuth.token.getExpiration().after(new Date()))) { if (cacheAuth != null && (cacheAuth.token.getExpiration().after(new Date()))) {
return cacheAuth.auth; return cacheAuth.auth;
} else { } else {
return null; return null;
} }
} else { } else {
return null; return null;
} }
} }
} }
@Override @Override
public OAuth2AccessToken readAccessToken(String accessToken) { public OAuth2AccessToken readAccessToken(String accessToken) {
// First check if the in memory cache has a Token object, and that it is still valid // First check if the in memory cache has a Token object, and that it is still valid
// If Valid, return it // If Valid, return it
TokenCacheObject cacheAuth = checkCache(accessToken); TokenCacheObject cacheAuth = checkCache(accessToken);
if (cacheAuth != null) { if (cacheAuth != null) {
return cacheAuth.token; return cacheAuth.token;
} else { } else {
if (parseToken(accessToken)) { if (parseToken(accessToken)) {
cacheAuth = authCache.get(accessToken); cacheAuth = authCache.get(accessToken);
if (cacheAuth != null && (cacheAuth.token.getExpiration().after(new Date()))) { if (cacheAuth != null && (cacheAuth.token.getExpiration().after(new Date()))) {
return cacheAuth.token; return cacheAuth.token;
} else { } else {
return null; return null;
} }
} else { } else {
return null; return null;
} }
} }
} }
} }

View File

@ -20,73 +20,73 @@ import com.google.gson.JsonObject;
public class OAuth2AccessTokenImpl implements OAuth2AccessToken { public class OAuth2AccessTokenImpl implements OAuth2AccessToken {
private JsonObject token; private JsonObject token;
private String tokenString; private String tokenString;
private Set<String> scopes = null; private Set<String> scopes = null;
private Date expireDate; private Date expireDate;
public OAuth2AccessTokenImpl(JsonObject token, String tokenString) { public OAuth2AccessTokenImpl(JsonObject token, String tokenString) {
this.token = token; this.token = token;
this.tokenString = tokenString; this.tokenString = tokenString;
scopes = new HashSet<String>(); scopes = new HashSet<String>();
for (JsonElement e : token.get("scope").getAsJsonArray()) { for (JsonElement e : token.get("scope").getAsJsonArray()) {
scopes.add(e.getAsString()); scopes.add(e.getAsString());
} }
DateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); DateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try { try {
expireDate = dateFormater.parse(token.get("expires_at").getAsString()); expireDate = dateFormater.parse(token.get("expires_at").getAsString());
} catch (ParseException ex) { } catch (ParseException ex) {
Logger.getLogger(IntrospectingTokenService.class.getName()).log(Level.SEVERE, null, ex); Logger.getLogger(IntrospectingTokenService.class.getName()).log(Level.SEVERE, null, ex);
} }
} }
@Override @Override
public Map<String, Object> getAdditionalInformation() { public Map<String, Object> getAdditionalInformation() {
return null; return null;
} }
@Override @Override
public Set<String> getScope() { public Set<String> getScope() {
return scopes; return scopes;
} }
@Override @Override
public OAuth2RefreshToken getRefreshToken() { public OAuth2RefreshToken getRefreshToken() {
return null; return null;
} }
@Override @Override
public String getTokenType() { public String getTokenType() {
return BEARER_TYPE; return BEARER_TYPE;
} }
@Override @Override
public boolean isExpired() { public boolean isExpired() {
if (expireDate != null && expireDate.before(new Date())) { if (expireDate != null && expireDate.before(new Date())) {
return true; return true;
} }
return false; return false;
} }
@Override @Override
public Date getExpiration() { public Date getExpiration() {
return expireDate; return expireDate;
} }
@Override @Override
public int getExpiresIn() { public int getExpiresIn() {
if (expireDate != null) { if (expireDate != null) {
return (int)TimeUnit.MILLISECONDS.toSeconds(expireDate.getTime() - (new Date()).getTime()); return (int)TimeUnit.MILLISECONDS.toSeconds(expireDate.getTime() - (new Date()).getTime());
} }
return 0; return 0;
} }
@Override @Override
public String getValue() { public String getValue() {
return tokenString; return tokenString;
} }
} }

View File

@ -20,8 +20,6 @@ import java.math.BigInteger;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.text.ParseException; import java.text.ParseException;
import java.util.Date; import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -29,8 +27,6 @@ import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.DefaultHttpClient;
import org.mitre.jwt.signer.service.JwtSigningAndValidationService; import org.mitre.jwt.signer.service.JwtSigningAndValidationService;
import org.mitre.jwt.signer.service.impl.JWKSetSigningAndValidationServiceCacheService; import org.mitre.jwt.signer.service.impl.JWKSetSigningAndValidationServiceCacheService;
@ -232,7 +228,7 @@ public class OIDCAuthenticationFilter extends AbstractAuthenticationProcessingFi
*/ */
form.add("client_id", clientConfig.getClientId()); form.add("client_id", clientConfig.getClientId());
form.add("client_secret", clientConfig.getClientSecret()); form.add("client_secret", clientConfig.getClientSecret());
/**/ /**/
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
@ -303,99 +299,99 @@ public class OIDCAuthenticationFilter extends AbstractAuthenticationProcessingFi
} }
try { try {
SignedJWT idToken = SignedJWT.parse(idTokenValue); SignedJWT idToken = SignedJWT.parse(idTokenValue);
// validate our ID Token over a number of tests // validate our ID Token over a number of tests
ReadOnlyJWTClaimsSet idClaims = idToken.getJWTClaimsSet(); ReadOnlyJWTClaimsSet idClaims = idToken.getJWTClaimsSet();
// check the signature // check the signature
JwtSigningAndValidationService jwtValidator = validationServices.get(serverConfig.getJwksUri()); JwtSigningAndValidationService jwtValidator = validationServices.get(serverConfig.getJwksUri());
if (jwtValidator != null) { if (jwtValidator != null) {
if(!jwtValidator.validateSignature(idToken)) { if(!jwtValidator.validateSignature(idToken)) {
throw new AuthenticationServiceException("Signature validation failed"); throw new AuthenticationServiceException("Signature validation failed");
} }
} else { } else {
logger.info("No validation service found. Skipping signature validation"); logger.info("No validation service found. Skipping signature validation");
} }
// check the issuer // check the issuer
if (idClaims.getIssuer() == null) { if (idClaims.getIssuer() == null) {
throw new AuthenticationServiceException("Id Token Issuer is null"); throw new AuthenticationServiceException("Id Token Issuer is null");
} else if (!idClaims.getIssuer().equals(serverConfig.getIssuer())){ } else if (!idClaims.getIssuer().equals(serverConfig.getIssuer())){
throw new AuthenticationServiceException("Issuers do not match, expected " + serverConfig.getIssuer() + " got " + idClaims.getIssuer()); throw new AuthenticationServiceException("Issuers do not match, expected " + serverConfig.getIssuer() + " got " + idClaims.getIssuer());
} }
// check expiration // check expiration
if (idClaims.getExpirationTime() == null) { if (idClaims.getExpirationTime() == null) {
throw new AuthenticationServiceException("Id Token does not have required expiration claim"); throw new AuthenticationServiceException("Id Token does not have required expiration claim");
} else { } else {
// it's not null, see if it's expired // it's not null, see if it's expired
Date now = new Date(System.currentTimeMillis() - (timeSkewAllowance * 1000)); Date now = new Date(System.currentTimeMillis() - (timeSkewAllowance * 1000));
if (now.after(idClaims.getExpirationTime())) { if (now.after(idClaims.getExpirationTime())) {
throw new AuthenticationServiceException("Id Token is expired: " + idClaims.getExpirationTime()); throw new AuthenticationServiceException("Id Token is expired: " + idClaims.getExpirationTime());
} }
} }
// check not before // check not before
if (idClaims.getNotBeforeTime() != null) { if (idClaims.getNotBeforeTime() != null) {
Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000)); Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000));
if (now.before(idClaims.getNotBeforeTime())){ if (now.before(idClaims.getNotBeforeTime())){
throw new AuthenticationServiceException("Id Token not valid untill: " + idClaims.getNotBeforeTime()); throw new AuthenticationServiceException("Id Token not valid untill: " + idClaims.getNotBeforeTime());
} }
} }
// check issued at // check issued at
if (idClaims.getIssueTime() == null) { if (idClaims.getIssueTime() == null) {
throw new AuthenticationServiceException("Id Token does not have required issued-at claim"); throw new AuthenticationServiceException("Id Token does not have required issued-at claim");
} else { } else {
// since it's not null, see if it was issued in the future // since it's not null, see if it was issued in the future
Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000)); Date now = new Date(System.currentTimeMillis() + (timeSkewAllowance * 1000));
if (now.before(idClaims.getIssueTime())) { if (now.before(idClaims.getIssueTime())) {
throw new AuthenticationServiceException("Id Token was issued in the future: " + idClaims.getIssueTime()); throw new AuthenticationServiceException("Id Token was issued in the future: " + idClaims.getIssueTime());
} }
} }
// check audience // check audience
if (idClaims.getAudience() == null) { if (idClaims.getAudience() == null) {
throw new AuthenticationServiceException("Id token audience is null"); throw new AuthenticationServiceException("Id token audience is null");
} else if (!idClaims.getAudience().contains(clientConfig.getClientId())) { } else if (!idClaims.getAudience().contains(clientConfig.getClientId())) {
throw new AuthenticationServiceException("Audience does not match, expected " + clientConfig.getClientId() + " got " + idClaims.getAudience()); throw new AuthenticationServiceException("Audience does not match, expected " + clientConfig.getClientId() + " got " + idClaims.getAudience());
} }
// compare the nonce to our stored claim // compare the nonce to our stored claim
// FIXME: Nimbus claims as strings? // FIXME: Nimbus claims as strings?
String nonce = (String) idClaims.getCustomClaim("nonce"); String nonce = (String) idClaims.getCustomClaim("nonce");
if (StringUtils.isBlank(nonce)) { if (StringUtils.isBlank(nonce)) {
logger.error("ID token did not contain a nonce claim."); logger.error("ID token did not contain a nonce claim.");
throw new AuthenticationServiceException("ID token did not contain a nonce claim."); throw new AuthenticationServiceException("ID token did not contain a nonce claim.");
} }
String storedNonce = getStoredNonce(session); String storedNonce = getStoredNonce(session);
if (!nonce.equals(storedNonce)) { if (!nonce.equals(storedNonce)) {
logger.error("Possible replay attack detected! The comparison of the nonce in the returned " logger.error("Possible replay attack detected! The comparison of the nonce in the returned "
+ "ID Token to the session " + NONCE_SESSION_VARIABLE + " failed. Expected " + storedNonce + " got " + nonce + "."); + "ID Token to the session " + NONCE_SESSION_VARIABLE + " failed. Expected " + storedNonce + " got " + nonce + ".");
throw new AuthenticationServiceException( throw new AuthenticationServiceException(
"Possible replay attack detected! The comparison of the nonce in the returned " "Possible replay attack detected! The comparison of the nonce in the returned "
+ "ID Token to the session " + NONCE_SESSION_VARIABLE + " failed. Expected " + storedNonce + " got " + nonce + "."); + "ID Token to the session " + NONCE_SESSION_VARIABLE + " failed. Expected " + storedNonce + " got " + nonce + ".");
} }
// pull the subject (user id) out as a claim on the id_token // pull the subject (user id) out as a claim on the id_token
String userId = idClaims.getSubject(); String userId = idClaims.getSubject();
// construct an OIDCAuthenticationToken and return a Authentication object w/the userId and the idToken // construct an OIDCAuthenticationToken and return a Authentication object w/the userId and the idToken
OIDCAuthenticationToken token = new OIDCAuthenticationToken(userId, idClaims.getIssuer(), serverConfig, idTokenValue, accessTokenValue, refreshTokenValue); OIDCAuthenticationToken token = new OIDCAuthenticationToken(userId, idClaims.getIssuer(), serverConfig, idTokenValue, accessTokenValue, refreshTokenValue);
Authentication authentication = this.getAuthenticationManager().authenticate(token); Authentication authentication = this.getAuthenticationManager().authenticate(token);
return authentication; return authentication;
} catch (ParseException e) { } catch (ParseException e) {
throw new AuthenticationServiceException("Couldn't parse idToken: ", e); throw new AuthenticationServiceException("Couldn't parse idToken: ", e);
} }

View File

@ -35,7 +35,7 @@ import com.google.common.collect.Sets;
* *
*/ */
public class OIDCAuthenticationProvider implements public class OIDCAuthenticationProvider implements
AuthenticationProvider, InitializingBean { AuthenticationProvider, InitializingBean {
private UserInfoFetcher userInfoFetcher = new UserInfoFetcher(); private UserInfoFetcher userInfoFetcher = new UserInfoFetcher();

View File

@ -32,7 +32,7 @@ import com.google.common.collect.ImmutableMap;
*/ */
public class OIDCAuthenticationToken extends AbstractAuthenticationToken { public class OIDCAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = 22100073066377804L; private static final long serialVersionUID = 22100073066377804L;
private final Object principal; private final Object principal;
private final String idTokenValue; // string representation of the id token private final String idTokenValue; // string representation of the id token
@ -130,46 +130,46 @@ public class OIDCAuthenticationToken extends AbstractAuthenticationToken {
} }
/** /**
* @return the idTokenValue * @return the idTokenValue
*/ */
public String getIdTokenValue() { public String getIdTokenValue() {
return idTokenValue; return idTokenValue;
} }
/** /**
* @return the accessTokenValue * @return the accessTokenValue
*/ */
public String getAccessTokenValue() { public String getAccessTokenValue() {
return accessTokenValue; return accessTokenValue;
} }
/** /**
* @return the refreshTokenValue * @return the refreshTokenValue
*/ */
public String getRefreshTokenValue() { public String getRefreshTokenValue() {
return refreshTokenValue; return refreshTokenValue;
} }
/** /**
* @return the serverConfiguration * @return the serverConfiguration
*/ */
public ServerConfiguration getServerConfiguration() { public ServerConfiguration getServerConfiguration() {
return serverConfiguration; return serverConfiguration;
} }
/** /**
* @return the issuer * @return the issuer
*/ */
public String getIssuer() { public String getIssuer() {
return issuer; return issuer;
} }
/** /**
* @return the userInfo * @return the userInfo
*/ */
public UserInfo getUserInfo() { public UserInfo getUserInfo() {
return userInfo; return userInfo;
} }
} }

View File

@ -34,6 +34,6 @@ public class UserInfoFetcher {
return userInfo; return userInfo;
} }
} }

View File

@ -34,9 +34,9 @@ public class ClientKeyPublisher implements BeanDefinitionRegistryPostProcessor {
/** /**
* If either the jwkPublishUrl or x509PublishUrl fields are set on this bean, set up a listener on that URL to publish keys. * If either the jwkPublishUrl or x509PublishUrl fields are set on this bean, set up a listener on that URL to publish keys.
*/ */
@Override @Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (!Strings.isNullOrEmpty(getJwkPublishUrl())) { if (!Strings.isNullOrEmpty(getJwkPublishUrl())) {
// add a mapping to this class // add a mapping to this class
@ -62,20 +62,20 @@ public class ClientKeyPublisher implements BeanDefinitionRegistryPostProcessor {
} }
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry(org.springframework.beans.factory.support.BeanDefinitionRegistry) * @see org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry(org.springframework.beans.factory.support.BeanDefinitionRegistry)
*/ */
@Override @Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
this.registry = registry; this.registry = registry;
} }
/** /**
* Return a view to publish all keys in JWK format. Only used if jwkPublishUrl is set. * Return a view to publish all keys in JWK format. Only used if jwkPublishUrl is set.
* @return * @return
*/ */
public ModelAndView publishClientJwk() { public ModelAndView publishClientJwk() {
// map from key id to key // map from key id to key
@ -87,18 +87,18 @@ public class ClientKeyPublisher implements BeanDefinitionRegistryPostProcessor {
} }
/** /**
* @return the jwkPublishUrl * @return the jwkPublishUrl
*/ */
public String getJwkPublishUrl() { public String getJwkPublishUrl() {
return jwkPublishUrl; return jwkPublishUrl;
} }
/** /**
* @param jwkPublishUrl the jwkPublishUrl to set * @param jwkPublishUrl the jwkPublishUrl to set
*/ */
public void setJwkPublishUrl(String jwkPublishUrl) { public void setJwkPublishUrl(String jwkPublishUrl) {
this.jwkPublishUrl = jwkPublishUrl; this.jwkPublishUrl = jwkPublishUrl;
} }
/** /**
* @return the signingAndValidationService * @return the signingAndValidationService

View File

@ -21,70 +21,70 @@ public class ClientKeyPublisherMapping extends RequestMappingInfoHandlerMapping
private String x509PublishUrl; private String x509PublishUrl;
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.web.servlet.handler.AbstractHandlerMethodMapping#isHandler(java.lang.Class) * @see org.springframework.web.servlet.handler.AbstractHandlerMethodMapping#isHandler(java.lang.Class)
*/ */
@Override @Override
protected boolean isHandler(Class<?> beanType) { protected boolean isHandler(Class<?> beanType) {
return beanType.equals(ClientKeyPublisher.class); return beanType.equals(ClientKeyPublisher.class);
} }
/** /**
* Map the "jwkKeyPublish" method to our jwkPublishUrl. * Map the "jwkKeyPublish" method to our jwkPublishUrl.
* Map the "x509KeyPublish" method to our x509PublishUrl. * Map the "x509KeyPublish" method to our x509PublishUrl.
*/ */
@Override @Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) { protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
if (method.getName().equals("publishClientJwk") && getJwkPublishUrl() != null) { if (method.getName().equals("publishClientJwk") && getJwkPublishUrl() != null) {
return new RequestMappingInfo( return new RequestMappingInfo(
new PatternsRequestCondition(new String[] {getJwkPublishUrl()}, getUrlPathHelper(), getPathMatcher(), false, false), new PatternsRequestCondition(new String[] {getJwkPublishUrl()}, getUrlPathHelper(), getPathMatcher(), false, false),
null, null,
null, null,
null, null,
null, null,
null, null,
null); null);
} else if (method.getName().equals("publishClientx509") && getX509PublishUrl() != null) { } else if (method.getName().equals("publishClientx509") && getX509PublishUrl() != null) {
return new RequestMappingInfo( return new RequestMappingInfo(
new PatternsRequestCondition(new String[] {getX509PublishUrl()}, getUrlPathHelper(), getPathMatcher(), false, false), new PatternsRequestCondition(new String[] {getX509PublishUrl()}, getUrlPathHelper(), getPathMatcher(), false, false),
null, null,
null, null,
null, null,
null, null,
null, null,
null); null);
} else { } else {
return null; return null;
} }
} }
/** /**
* @return the jwkPublishUrl * @return the jwkPublishUrl
*/ */
public String getJwkPublishUrl() { public String getJwkPublishUrl() {
return jwkPublishUrl; return jwkPublishUrl;
} }
/** /**
* @param jwkPublishUrl the jwkPublishUrl to set * @param jwkPublishUrl the jwkPublishUrl to set
*/ */
public void setJwkPublishUrl(String jwkPublishUrl) { public void setJwkPublishUrl(String jwkPublishUrl) {
this.jwkPublishUrl = jwkPublishUrl; this.jwkPublishUrl = jwkPublishUrl;
} }
/** /**
* @return the x509PublishUrl * @return the x509PublishUrl
*/ */
public String getX509PublishUrl() { public String getX509PublishUrl() {
return x509PublishUrl; return x509PublishUrl;
} }
/** /**
* @param x509PublishUrl the x509PublishUrl to set * @param x509PublishUrl the x509PublishUrl to set
*/ */
public void setX509PublishUrl(String x509PublishUrl) { public void setX509PublishUrl(String x509PublishUrl) {
this.x509PublishUrl = x509PublishUrl; this.x509PublishUrl = x509PublishUrl;
} }
} }

View File

@ -46,74 +46,74 @@ public class JwkViewResolver implements ViewResolver, Ordered {
} }
/** /**
* @return the x509 * @return the x509
*/ */
public View getX509() { public View getX509() {
return x509; return x509;
} }
/** /**
* @param x509 the x509 to set * @param x509 the x509 to set
*/ */
public void setX509(View x509) { public void setX509(View x509) {
this.x509 = x509; this.x509 = x509;
} }
/** /**
* @return the jwk * @return the jwk
*/ */
public View getJwk() { public View getJwk() {
return jwk; return jwk;
} }
/** /**
* @param jwk the jwk to set * @param jwk the jwk to set
*/ */
public void setJwk(View jwk) { public void setJwk(View jwk) {
this.jwk = jwk; this.jwk = jwk;
} }
/** /**
* @return the order * @return the order
*/ */
@Override @Override
public int getOrder() { public int getOrder() {
return order; return order;
} }
/** /**
* @param order the order to set * @param order the order to set
*/ */
public void setOrder(int order) { public void setOrder(int order) {
this.order = order; this.order = order;
} }
/** /**
* @return the jwkViewName * @return the jwkViewName
*/ */
public String getJwkViewName() { public String getJwkViewName() {
return jwkViewName; return jwkViewName;
} }
/** /**
* @param jwkViewName the jwkViewName to set * @param jwkViewName the jwkViewName to set
*/ */
public void setJwkViewName(String jwkViewName) { public void setJwkViewName(String jwkViewName) {
this.jwkViewName = jwkViewName; this.jwkViewName = jwkViewName;
} }
/** /**
* @return the x509ViewName * @return the x509ViewName
*/ */
public String getX509ViewName() { public String getX509ViewName() {
return x509ViewName; return x509ViewName;
} }
/** /**
* @param x509ViewName the x509ViewName to set * @param x509ViewName the x509ViewName to set
*/ */
public void setX509ViewName(String x509ViewName) { public void setX509ViewName(String x509ViewName) {
this.x509ViewName = x509ViewName; this.x509ViewName = x509ViewName;
} }
} }

View File

@ -22,18 +22,18 @@ public class IssuerServiceResponse {
* @param loginHint * @param loginHint
* @param targetLinkUri * @param targetLinkUri
*/ */
public IssuerServiceResponse(String issuer, String loginHint, String targetLinkUri) { public IssuerServiceResponse(String issuer, String loginHint, String targetLinkUri) {
this.issuer = issuer; this.issuer = issuer;
this.loginHint = loginHint; this.loginHint = loginHint;
this.targetLinkUri = targetLinkUri; this.targetLinkUri = targetLinkUri;
} }
/** /**
* @param redirectUrl * @param redirectUrl
*/ */
public IssuerServiceResponse(String redirectUrl) { public IssuerServiceResponse(String redirectUrl) {
this.redirectUrl = redirectUrl; this.redirectUrl = redirectUrl;
} }
/** /**
* @return the issuer * @return the issuer
*/ */

View File

@ -20,6 +20,6 @@ public interface AuthRequestUrlBuilder {
* @param state * @param state
* @return * @return
*/ */
public String buildAuthRequestUrl(ServerConfiguration serverConfig, ClientDetails clientConfig, String redirectUri, String nonce, String state); public String buildAuthRequestUrl(ServerConfiguration serverConfig, ClientDetails clientConfig, String redirectUri, String nonce, String state);
} }

View File

@ -46,10 +46,10 @@ public class PlainAuthRequestUrlBuilder implements AuthRequestUrlBuilder {
return uriBuilder.build().toString(); return uriBuilder.build().toString();
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
throw new AuthenticationServiceException("Malformed Authorization Endpoint Uri", e); throw new AuthenticationServiceException("Malformed Authorization Endpoint Uri", e);
} }

View File

@ -4,11 +4,6 @@
package org.mitre.openid.connect.client.service.impl; package org.mitre.openid.connect.client.service.impl;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.security.NoSuchAlgorithmException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.http.client.utils.URIBuilder; import org.apache.http.client.utils.URIBuilder;
import org.mitre.jwt.signer.service.JwtSigningAndValidationService; import org.mitre.jwt.signer.service.JwtSigningAndValidationService;
@ -58,14 +53,14 @@ public class SignedAuthRequestUrlBuilder implements AuthRequestUrlBuilder {
signingAndValidationService.signJwt(jwt); signingAndValidationService.signJwt(jwt);
try { try {
URIBuilder uriBuilder = new URIBuilder(serverConfig.getAuthorizationEndpointUri()); URIBuilder uriBuilder = new URIBuilder(serverConfig.getAuthorizationEndpointUri());
uriBuilder.addParameter("request", jwt.serialize()); uriBuilder.addParameter("request", jwt.serialize());
// build out the URI // build out the URI
return uriBuilder.build().toString(); return uriBuilder.build().toString();
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
throw new AuthenticationServiceException("Malformed Authorization Endpoint Uri", e); throw new AuthenticationServiceException("Malformed Authorization Endpoint Uri", e);
} }
} }
/** /**

View File

@ -50,12 +50,12 @@ public class StaticClientConfigurationService implements ClientConfigurationServ
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/ */
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
if (clients == null || clients.isEmpty()) { if (clients == null || clients.isEmpty()) {
throw new IllegalArgumentException("Clients map cannot be null or empty"); throw new IllegalArgumentException("Clients map cannot be null or empty");
} }
} }
} }

View File

@ -45,12 +45,12 @@ public class StaticServerConfigurationService implements ServerConfigurationServ
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/ */
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
if (servers == null || servers.isEmpty()) { if (servers == null || servers.isEmpty()) {
throw new IllegalArgumentException("Servers map cannot be null or empty."); throw new IllegalArgumentException("Servers map cannot be null or empty.");
} }
} }
} }

View File

@ -46,13 +46,13 @@ public class StaticSingleIssuerService implements IssuerService, InitializingBea
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/ */
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
if (Strings.isNullOrEmpty(issuer)) { if (Strings.isNullOrEmpty(issuer)) {
throw new IllegalArgumentException("Issuer must not be null or empty."); throw new IllegalArgumentException("Issuer must not be null or empty.");
} }
} }
} }

View File

@ -40,15 +40,15 @@ public class ThirdPartyIssuerService implements IssuerService, InitializingBean
try { try {
// otherwise, need to forward to the account chooser // otherwise, need to forward to the account chooser
String redirectUri = request.getRequestURL().toString(); String redirectUri = request.getRequestURL().toString();
URIBuilder builder = new URIBuilder(accountChooserUrl); URIBuilder builder = new URIBuilder(accountChooserUrl);
builder.addParameter("redirect_uri", redirectUri); builder.addParameter("redirect_uri", redirectUri);
return new IssuerServiceResponse(builder.build().toString()); return new IssuerServiceResponse(builder.build().toString());
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
throw new AuthenticationServiceException("Account Chooser URL is not valid", e); throw new AuthenticationServiceException("Account Chooser URL is not valid", e);
} }
} }
@ -72,12 +72,12 @@ public class ThirdPartyIssuerService implements IssuerService, InitializingBean
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
*/ */
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
if (Strings.isNullOrEmpty(this.accountChooserUrl)) { if (Strings.isNullOrEmpty(this.accountChooserUrl)) {
throw new IllegalArgumentException("Account Chooser URL cannot be null or empty"); throw new IllegalArgumentException("Account Chooser URL cannot be null or empty");
} }
} }
} }

View File

@ -1,10 +1,5 @@
package org.mitre.openid.connect.client; package org.mitre.openid.connect.client;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/** /**
* Unit test for OIDCAuthenticationFilter * Unit test for OIDCAuthenticationFilter

View File

@ -5,7 +5,6 @@ package org.mitre.jose;
import javax.persistence.Basic; import javax.persistence.Basic;
import javax.persistence.Embeddable; import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.Transient; import javax.persistence.Transient;
import com.google.common.base.Strings; import com.google.common.base.Strings;
@ -30,8 +29,8 @@ public class JWEAlgorithmEmbed {
} }
public JWEAlgorithmEmbed(JWEAlgorithm algorithm) { public JWEAlgorithmEmbed(JWEAlgorithm algorithm) {
this.algorithm = algorithm; this.algorithm = algorithm;
} }
public static JWEAlgorithmEmbed getForAlgorithmName (String algorithmName) { public static JWEAlgorithmEmbed getForAlgorithmName (String algorithmName) {
JWEAlgorithmEmbed ent = new JWEAlgorithmEmbed(); JWEAlgorithmEmbed ent = new JWEAlgorithmEmbed();
@ -72,15 +71,15 @@ public class JWEAlgorithmEmbed {
/* (non-Javadoc) /* (non-Javadoc)
* @see java.lang.Object#toString() * @see java.lang.Object#toString()
*/ */
@Override @Override
public String toString() { public String toString() {
return "JWEAlgorithmEmbed [algorithm=" + algorithm + "]"; return "JWEAlgorithmEmbed [algorithm=" + algorithm + "]";
} }
/** /**
* @return the algorithm * @return the algorithm
*/ */
@Transient @Transient
public JWEAlgorithm getAlgorithm() { public JWEAlgorithm getAlgorithm() {
return algorithm; return algorithm;
} }

View File

@ -9,7 +9,6 @@ import javax.persistence.Transient;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import com.nimbusds.jose.EncryptionMethod; import com.nimbusds.jose.EncryptionMethod;
import com.nimbusds.jose.JWEAlgorithm;
/** /**
* @author jricher * @author jricher
@ -27,8 +26,8 @@ public class JWEEncryptionMethodEmbed {
} }
public JWEEncryptionMethodEmbed(EncryptionMethod algorithm) { public JWEEncryptionMethodEmbed(EncryptionMethod algorithm) {
this.algorithm = algorithm; this.algorithm = algorithm;
} }
public static JWEEncryptionMethodEmbed getForAlgorithmName (String algorithmName) { public static JWEEncryptionMethodEmbed getForAlgorithmName (String algorithmName) {
JWEEncryptionMethodEmbed ent = new JWEEncryptionMethodEmbed(); JWEEncryptionMethodEmbed ent = new JWEEncryptionMethodEmbed();
@ -69,15 +68,15 @@ public class JWEEncryptionMethodEmbed {
/* (non-Javadoc) /* (non-Javadoc)
* @see java.lang.Object#toString() * @see java.lang.Object#toString()
*/ */
@Override @Override
public String toString() { public String toString() {
return "JWEEncryptionMethodEmbed [algorithm=" + algorithm + "]"; return "JWEEncryptionMethodEmbed [algorithm=" + algorithm + "]";
} }
/** /**
* @return the algorithm * @return the algorithm
*/ */
@Transient @Transient
public EncryptionMethod getAlgorithm() { public EncryptionMethod getAlgorithm() {
return algorithm; return algorithm;
} }

View File

@ -5,8 +5,6 @@ package org.mitre.jose;
import javax.persistence.Basic; import javax.persistence.Basic;
import javax.persistence.Embeddable; import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Transient; import javax.persistence.Transient;
import com.google.common.base.Strings; import com.google.common.base.Strings;
@ -31,8 +29,8 @@ public class JWSAlgorithmEmbed {
} }
public JWSAlgorithmEmbed(JWSAlgorithm algorithm) { public JWSAlgorithmEmbed(JWSAlgorithm algorithm) {
this.algorithm = algorithm; this.algorithm = algorithm;
} }
public static JWSAlgorithmEmbed getForAlgorithmName (String algorithmName) { public static JWSAlgorithmEmbed getForAlgorithmName (String algorithmName) {
JWSAlgorithmEmbed ent = new JWSAlgorithmEmbed(); JWSAlgorithmEmbed ent = new JWSAlgorithmEmbed();
@ -88,10 +86,10 @@ public class JWSAlgorithmEmbed {
/* (non-Javadoc) /* (non-Javadoc)
* @see java.lang.Object#toString() * @see java.lang.Object#toString()
*/ */
@Override @Override
public String toString() { public String toString() {
return "JWSAlgorithmEmbed [algorithm=" + algorithm + "]"; return "JWSAlgorithmEmbed [algorithm=" + algorithm + "]";
} }

View File

@ -90,9 +90,9 @@ public class JWKSetKeyStore implements InitializingBean {
/** /**
* Get the list of keys in this keystore. This is a passthrough to the underlying JWK Set * Get the list of keys in this keystore. This is a passthrough to the underlying JWK Set
*/ */
public List<JWK> getKeys() { public List<JWK> getKeys() {
return jwkSet.getKeys(); return jwkSet.getKeys();
} }

View File

@ -16,7 +16,6 @@
package org.mitre.jwt.signer.service; package org.mitre.jwt.signer.service;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.Map; import java.util.Map;
import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSAlgorithm;
@ -55,7 +54,7 @@ public interface JwtSigningAndValidationService {
* Get the default signing algorithm for use when nothing else has been specified. * Get the default signing algorithm for use when nothing else has been specified.
* @return * @return
*/ */
public JWSAlgorithm getDefaultSigningAlgorithm(); public JWSAlgorithm getDefaultSigningAlgorithm();
/** /**
* Sign a jwt using the selected algorithm. The algorithm is selected using the String parameter values specified * Sign a jwt using the selected algorithm. The algorithm is selected using the String parameter values specified

View File

@ -70,10 +70,10 @@ public class DefaultJwtSigningAndValidationService implements JwtSigningAndValid
* @throws NoSuchAlgorithmException * @throws NoSuchAlgorithmException
* If there is no appropriate algorithm to tie the keys to. * If there is no appropriate algorithm to tie the keys to.
*/ */
public DefaultJwtSigningAndValidationService(Map<String, JWK> keys) throws NoSuchAlgorithmException, InvalidKeySpecException { public DefaultJwtSigningAndValidationService(Map<String, JWK> keys) throws NoSuchAlgorithmException, InvalidKeySpecException {
this.keys = keys; this.keys = keys;
buildSignersAndVerifiers(); buildSignersAndVerifiers();
} }
/** /**
* Build this service based on the given keystore. All keys must have a key * Build this service based on the given keystore. All keys must have a key
@ -87,17 +87,17 @@ public class DefaultJwtSigningAndValidationService implements JwtSigningAndValid
* @throws NoSuchAlgorithmException * @throws NoSuchAlgorithmException
* If there is no appropriate algorithm to tie the keys to. * If there is no appropriate algorithm to tie the keys to.
*/ */
public DefaultJwtSigningAndValidationService(JWKSetKeyStore keyStore) throws NoSuchAlgorithmException, InvalidKeySpecException { public DefaultJwtSigningAndValidationService(JWKSetKeyStore keyStore) throws NoSuchAlgorithmException, InvalidKeySpecException {
// convert all keys in the keystore to a map based on key id // convert all keys in the keystore to a map based on key id
for (JWK key : keyStore.getKeys()) { for (JWK key : keyStore.getKeys()) {
if (!Strings.isNullOrEmpty(key.getKeyID())) { if (!Strings.isNullOrEmpty(key.getKeyID())) {
this.keys.put(key.getKeyID(), key); this.keys.put(key.getKeyID(), key);
} else { } else {
throw new IllegalArgumentException("Tried to load a key from a keystore without a 'kid' field: " + key); throw new IllegalArgumentException("Tried to load a key from a keystore without a 'kid' field: " + key);
} }
} }
buildSignersAndVerifiers(); buildSignersAndVerifiers();
} }
/** /**
* @return the defaultSignerKeyId * @return the defaultSignerKeyId
@ -117,21 +117,21 @@ public class DefaultJwtSigningAndValidationService implements JwtSigningAndValid
* @return * @return
*/ */
@Override @Override
public JWSAlgorithm getDefaultSigningAlgorithm() { public JWSAlgorithm getDefaultSigningAlgorithm() {
return defaultAlgorithm; return defaultAlgorithm;
} }
public void setDefaultSigningAlgorithmName(String algName) { public void setDefaultSigningAlgorithmName(String algName) {
defaultAlgorithm = JWSAlgorithm.parse(algName); defaultAlgorithm = JWSAlgorithm.parse(algName);
} }
public String getDefaultSigningAlgorithmName() { public String getDefaultSigningAlgorithmName() {
if (defaultAlgorithm != null) { if (defaultAlgorithm != null) {
return defaultAlgorithm.getName(); return defaultAlgorithm.getName();
} else { } else {
return null; return null;
} }
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
@ -156,45 +156,45 @@ public class DefaultJwtSigningAndValidationService implements JwtSigningAndValid
* @throws InvalidKeySpecException If the keys in the JWKs are not valid * @throws InvalidKeySpecException If the keys in the JWKs are not valid
* @throws NoSuchAlgorithmException If there is no appropriate algorithm to tie the keys to. * @throws NoSuchAlgorithmException If there is no appropriate algorithm to tie the keys to.
*/ */
private void buildSignersAndVerifiers() throws NoSuchAlgorithmException, InvalidKeySpecException { private void buildSignersAndVerifiers() throws NoSuchAlgorithmException, InvalidKeySpecException {
for (Map.Entry<String, JWK> jwkEntry : keys.entrySet()) { for (Map.Entry<String, JWK> jwkEntry : keys.entrySet()) {
String id = jwkEntry.getKey(); String id = jwkEntry.getKey();
JWK jwk = jwkEntry.getValue(); JWK jwk = jwkEntry.getValue();
if (jwk instanceof RSAKey) { if (jwk instanceof RSAKey) {
// build RSA signers & verifiers // build RSA signers & verifiers
if (jwk.isPrivate()) { // only add the signer if there's a private key if (jwk.isPrivate()) { // only add the signer if there's a private key
RSASSASigner signer = new RSASSASigner(((RSAKey) jwk).toRSAPrivateKey()); RSASSASigner signer = new RSASSASigner(((RSAKey) jwk).toRSAPrivateKey());
signers.put(id, signer); signers.put(id, signer);
} }
RSASSAVerifier verifier = new RSASSAVerifier(((RSAKey) jwk).toRSAPublicKey()); RSASSAVerifier verifier = new RSASSAVerifier(((RSAKey) jwk).toRSAPublicKey());
verifiers.put(id, verifier); verifiers.put(id, verifier);
} else if (jwk instanceof ECKey) { } else if (jwk instanceof ECKey) {
// build EC signers & verifiers // build EC signers & verifiers
// TODO: add support for EC keys // TODO: add support for EC keys
logger.warn("EC Keys are not yet supported."); logger.warn("EC Keys are not yet supported.");
} else if (jwk instanceof OctetSequenceKey) { } else if (jwk instanceof OctetSequenceKey) {
// build HMAC signers & verifiers // build HMAC signers & verifiers
if (jwk.isPrivate()) { // technically redundant check because all HMAC keys are private if (jwk.isPrivate()) { // technically redundant check because all HMAC keys are private
MACSigner signer = new MACSigner(((OctetSequenceKey) jwk).toByteArray()); MACSigner signer = new MACSigner(((OctetSequenceKey) jwk).toByteArray());
signers.put(id, signer); signers.put(id, signer);
} }
MACVerifier verifier = new MACVerifier(((OctetSequenceKey) jwk).toByteArray()); MACVerifier verifier = new MACVerifier(((OctetSequenceKey) jwk).toByteArray());
verifiers.put(id, verifier); verifiers.put(id, verifier);
} else { } else {
logger.warn("Unknown key type: " + jwk); logger.warn("Unknown key type: " + jwk);
} }
} }
} }
/** /**
* Sign a jwt in place using the configured default signer. * Sign a jwt in place using the configured default signer.
@ -208,11 +208,11 @@ public class DefaultJwtSigningAndValidationService implements JwtSigningAndValid
JWSSigner signer = signers.get(getDefaultSignerKeyId()); JWSSigner signer = signers.get(getDefaultSignerKeyId());
try { try {
jwt.sign(signer); jwt.sign(signer);
} catch (JOSEException e) { } catch (JOSEException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -225,9 +225,9 @@ public class DefaultJwtSigningAndValidationService implements JwtSigningAndValid
return true; return true;
} }
} catch (JOSEException e) { } catch (JOSEException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
return false; return false;
} }
@ -238,12 +238,12 @@ public class DefaultJwtSigningAndValidationService implements JwtSigningAndValid
// pull all keys out of the verifiers if we know how // pull all keys out of the verifiers if we know how
for (String keyId : keys.keySet()) { for (String keyId : keys.keySet()) {
JWK key = keys.get(keyId); JWK key = keys.get(keyId);
JWK pub = key.toPublicJWK(); JWK pub = key.toPublicJWK();
if (pub != null) { if (pub != null) {
pubKeys.put(keyId, pub); pubKeys.put(keyId, pub);
} }
} }
return pubKeys; return pubKeys;
} }

View File

@ -3,12 +3,6 @@
*/ */
package org.mitre.jwt.signer.service.impl; package org.mitre.jwt.signer.service.impl;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPublicKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
@ -22,12 +16,7 @@ import org.springframework.web.client.RestTemplate;
import com.google.common.cache.Cache; import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader; import com.google.common.cache.CacheLoader;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.RSASSAVerifier;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.KeyType;
import com.nimbusds.jose.jwk.RSAKey;
/** /**
* *
@ -53,42 +42,42 @@ public class JWKSetSigningAndValidationServiceCacheService {
* @throws ExecutionException * @throws ExecutionException
* @see com.google.common.cache.Cache#get(java.lang.Object) * @see com.google.common.cache.Cache#get(java.lang.Object)
*/ */
public JwtSigningAndValidationService get(String key) { public JwtSigningAndValidationService get(String key) {
try { try {
return cache.get(key); return cache.get(key);
} catch (ExecutionException e) { } catch (ExecutionException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
/** /**
* @author jricher * @author jricher
* *
*/ */
private class JWKSetVerifierFetcher extends CacheLoader<String, JwtSigningAndValidationService> { private class JWKSetVerifierFetcher extends CacheLoader<String, JwtSigningAndValidationService> {
private HttpClient httpClient = new DefaultHttpClient(); private HttpClient httpClient = new DefaultHttpClient();
private HttpComponentsClientHttpRequestFactory httpFactory = new HttpComponentsClientHttpRequestFactory(httpClient); private HttpComponentsClientHttpRequestFactory httpFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
private RestTemplate restTemplate = new RestTemplate(httpFactory); private RestTemplate restTemplate = new RestTemplate(httpFactory);
/** /**
* Load the JWK Set and build the appropriate signing service. * Load the JWK Set and build the appropriate signing service.
*/ */
@Override @Override
public JwtSigningAndValidationService load(String key) throws Exception { public JwtSigningAndValidationService load(String key) throws Exception {
String jsonString = restTemplate.getForObject(key, String.class); String jsonString = restTemplate.getForObject(key, String.class);
JWKSet jwkSet = JWKSet.parse(jsonString); JWKSet jwkSet = JWKSet.parse(jsonString);
JWKSetKeyStore keyStore = new JWKSetKeyStore(jwkSet); JWKSetKeyStore keyStore = new JWKSetKeyStore(jwkSet);
JwtSigningAndValidationService service = new DefaultJwtSigningAndValidationService(keyStore); JwtSigningAndValidationService service = new DefaultJwtSigningAndValidationService(keyStore);
return service; return service;
} }
} }
} }

View File

@ -55,7 +55,7 @@ public class AuthorizationCodeEntity {
* @return the id * @return the id
*/ */
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() { public Long getId() {
return id; return id;
} }

View File

@ -84,7 +84,7 @@ public class ClientDetailsEntity implements ClientDetails {
private String policyUri; private String policyUri;
private String jwksUri; private String jwksUri;
/** Fields from OIDC Client Registration Specification **/ /** Fields from OIDC Client Registration Specification **/
private AppType applicationType; // application_type private AppType applicationType; // application_type
private String sectorIdentifierUri; // sector_identifier_uri private String sectorIdentifierUri; // sector_identifier_uri
private SubjectType subjectType; // subject_type private SubjectType subjectType; // subject_type
@ -162,8 +162,8 @@ public class ClientDetailsEntity implements ClientDetails {
private static final Map<String, AppType> lookup = new HashMap<String, AppType>(); private static final Map<String, AppType> lookup = new HashMap<String, AppType>();
static { static {
for (AppType a : AppType.values()) { for (AppType a : AppType.values()) {
lookup.put(a.getValue(), a); lookup.put(a.getValue(), a);
} }
} }
AppType(String value) { AppType(String value) {
@ -179,8 +179,8 @@ public class ClientDetailsEntity implements ClientDetails {
} }
} }
public enum SubjectType { public enum SubjectType {
PAIRWISE("pairwise"), PUBLIC("public"); PAIRWISE("pairwise"), PUBLIC("public");
private final String value; private final String value;
@ -188,8 +188,8 @@ public class ClientDetailsEntity implements ClientDetails {
private static final Map<String, SubjectType> lookup = new HashMap<String, SubjectType>(); private static final Map<String, SubjectType> lookup = new HashMap<String, SubjectType>();
static { static {
for (SubjectType u : SubjectType.values()) { for (SubjectType u : SubjectType.values()) {
lookup.put(u.getValue(), u); lookup.put(u.getValue(), u);
} }
} }
SubjectType(String value) { SubjectType(String value) {
@ -203,7 +203,7 @@ public class ClientDetailsEntity implements ClientDetails {
public static SubjectType getByValue(String value) { public static SubjectType getByValue(String value) {
return lookup.get(value); return lookup.get(value);
} }
} }
/** /**
* Create a blank ClientDetailsEntity * Create a blank ClientDetailsEntity
@ -230,32 +230,32 @@ public class ClientDetailsEntity implements ClientDetails {
} }
/** /**
* @return the clientDescription * @return the clientDescription
*/ */
@Basic @Basic
@Column(name="client_description") @Column(name="client_description")
public String getClientDescription() { public String getClientDescription() {
return clientDescription; return clientDescription;
} }
/** /**
* @param clientDescription Human-readable long description of the client (optional) * @param clientDescription Human-readable long description of the client (optional)
*/ */
public void setClientDescription(String clientDescription) { public void setClientDescription(String clientDescription) {
this.clientDescription = clientDescription; this.clientDescription = clientDescription;
} }
/** /**
* @return the allowRefresh * @return the allowRefresh
*/ */
@Transient @Transient
public boolean isAllowRefresh() { public boolean isAllowRefresh() {
if (grantTypes != null) { if (grantTypes != null) {
return getAuthorizedGrantTypes().contains("refresh_token"); return getAuthorizedGrantTypes().contains("refresh_token");
} else { } else {
return false; // if there are no grants, we can't be refreshing them, can we? return false; // if there are no grants, we can't be refreshing them, can we?
} }
} }
@Basic @Basic
@Column(name="reuse_refresh_tokens") @Column(name="reuse_refresh_tokens")
@ -304,142 +304,143 @@ public class ClientDetailsEntity implements ClientDetails {
/** /**
* @return the allowIntrospection * @return the allowIntrospection
*/ */
@Basic @Basic
@Column(name="allow_introspection") @Column(name="allow_introspection")
public boolean isAllowIntrospection() { public boolean isAllowIntrospection() {
return allowIntrospection; return allowIntrospection;
} }
/** /**
* @param allowIntrospection the allowIntrospection to set * @param allowIntrospection the allowIntrospection to set
*/ */
public void setAllowIntrospection(boolean allowIntrospection) { public void setAllowIntrospection(boolean allowIntrospection) {
this.allowIntrospection = allowIntrospection; this.allowIntrospection = allowIntrospection;
} }
/** /**
* *
*/ */
@Override @Override
@Transient @Transient
public boolean isSecretRequired() { public boolean isSecretRequired() {
// TODO: this should check the auth method field instead // TODO: this should check the auth method field instead
return getClientSecret() != null; return getClientSecret() != null;
} }
/** /**
* If the scope list is not null or empty, then this client has been scoped. * If the scope list is not null or empty, then this client has been scoped.
*/ */
@Override @Override
@Transient @Transient
public boolean isScoped() { public boolean isScoped() {
return getScope() != null && !getScope().isEmpty(); return getScope() != null && !getScope().isEmpty();
} }
/** /**
* @return the clientId * @return the clientId
*/ */
@Basic @Basic
@Override @Override
@Column(name="client_id") @Column(name="client_id")
public String getClientId() { public String getClientId() {
return clientId; return clientId;
} }
/** /**
* @param clientId The OAuth2 client_id, must be unique to this client * @param clientId The OAuth2 client_id, must be unique to this client
*/ */
public void setClientId(String clientId) { public void setClientId(String clientId) {
this.clientId = clientId; this.clientId = clientId;
} }
/** /**
* @return the clientSecret * @return the clientSecret
*/ */
@Basic @Basic
@Override @Override
@Column(name="client_secret") @Column(name="client_secret")
public String getClientSecret() { public String getClientSecret() {
return clientSecret; return clientSecret;
} }
/** /**
* @param clientSecret the OAuth2 client_secret (optional) * @param clientSecret the OAuth2 client_secret (optional)
*/ */
public void setClientSecret(String clientSecret) { public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret; this.clientSecret = clientSecret;
} }
/** /**
* @return the scope * @return the scope
*/ */
@ElementCollection(fetch = FetchType.EAGER) @ElementCollection(fetch = FetchType.EAGER)
@CollectionTable( @CollectionTable(
name="client_scope", name="client_scope",
joinColumns=@JoinColumn(name="owner_id") joinColumns=@JoinColumn(name="owner_id")
) )
@Override @Override
@Column(name="scope") @Column(name="scope")
public Set<String> getScope() { public Set<String> getScope() {
return scope; return scope;
} }
/** /**
* @param scope the set of scopes allowed to be issued to this client * @param scope the set of scopes allowed to be issued to this client
*/ */
public void setScope(Set<String> scope) { public void setScope(Set<String> scope) {
this.scope = scope; this.scope = scope;
} }
/** /**
* @return the authorizedGrantTypes * @return the authorizedGrantTypes
*/ */
@ElementCollection(fetch = FetchType.EAGER) @ElementCollection(fetch = FetchType.EAGER)
@CollectionTable( @CollectionTable(
name="client_grant_type", name="client_grant_type",
joinColumns=@JoinColumn(name="owner_id") joinColumns=@JoinColumn(name="owner_id")
) )
@Column(name="grant_type") @Column(name="grant_type")
public Set<String> getGrantTypes() { public Set<String> getGrantTypes() {
return grantTypes; return grantTypes;
} }
/** /**
* @param authorizedGrantTypes the OAuth2 grant types that this client is allowed to use * @param authorizedGrantTypes the OAuth2 grant types that this client is allowed to use
*/ */
public void setGrantTypes(Set<String> grantTypes) { public void setGrantTypes(Set<String> grantTypes) {
this.grantTypes = grantTypes; this.grantTypes = grantTypes;
} }
/**
* passthrough for SECOAUTH api
*/
public Set<String> getAuthorizedGrantTypes() {
return getGrantTypes();
}
/** /**
* @return the authorities * passthrough for SECOAUTH api
*/ */
@Override
public Set<String> getAuthorizedGrantTypes() {
return getGrantTypes();
}
/**
* @return the authorities
*/
@ElementCollection(fetch = FetchType.EAGER) @ElementCollection(fetch = FetchType.EAGER)
@CollectionTable( @CollectionTable(
name="client_authority", name="client_authority",
joinColumns=@JoinColumn(name="owner_id") joinColumns=@JoinColumn(name="owner_id")
) )
@Override @Override
@Column(name="authority") @Column(name="authority")
public Set<GrantedAuthority> getAuthorities() { public Set<GrantedAuthority> getAuthorities() {
return authorities; return authorities;
} }
/** /**
* @param authorities the Spring Security authorities this client is given * @param authorities the Spring Security authorities this client is given
*/ */
public void setAuthorities(Set<GrantedAuthority> authorities) { public void setAuthorities(Set<GrantedAuthority> authorities) {
this.authorities = authorities; this.authorities = authorities;
} }
@Override @Override
@Basic @Basic
@ -449,11 +450,11 @@ public class ClientDetailsEntity implements ClientDetails {
} }
/** /**
* @param accessTokenTimeout the accessTokenTimeout to set * @param accessTokenTimeout the accessTokenTimeout to set
*/ */
public void setAccessTokenValiditySeconds(Integer accessTokenValiditySeconds) { public void setAccessTokenValiditySeconds(Integer accessTokenValiditySeconds) {
this.accessTokenValiditySeconds = accessTokenValiditySeconds; this.accessTokenValiditySeconds = accessTokenValiditySeconds;
} }
@Override @Override
@Basic @Basic
@ -463,60 +464,61 @@ public class ClientDetailsEntity implements ClientDetails {
} }
/** /**
* @param refreshTokenTimeout Lifetime of refresh tokens, in seconds (optional - leave null for no timeout) * @param refreshTokenTimeout Lifetime of refresh tokens, in seconds (optional - leave null for no timeout)
*/ */
public void setRefreshTokenValiditySeconds(Integer refreshTokenValiditySeconds) { public void setRefreshTokenValiditySeconds(Integer refreshTokenValiditySeconds) {
this.refreshTokenValiditySeconds = refreshTokenValiditySeconds; this.refreshTokenValiditySeconds = refreshTokenValiditySeconds;
} }
/** /**
* @return the registeredRedirectUri * @return the registeredRedirectUri
*/ */
@ElementCollection(fetch = FetchType.EAGER) @ElementCollection(fetch = FetchType.EAGER)
@CollectionTable( @CollectionTable(
name="client_redirect_uri", name="client_redirect_uri",
joinColumns=@JoinColumn(name="owner_id") joinColumns=@JoinColumn(name="owner_id")
) )
@Column(name="redirect_uri") @Column(name="redirect_uri")
public Set<String> getRedirectUris() { public Set<String> getRedirectUris() {
return redirectUris; return redirectUris;
} }
/** /**
* @param registeredRedirectUri the registeredRedirectUri to set * @param registeredRedirectUri the registeredRedirectUri to set
*/ */
public void setRedirectUris(Set<String> redirectUris) { public void setRedirectUris(Set<String> redirectUris) {
this.redirectUris = redirectUris; this.redirectUris = redirectUris;
} }
/**
* Pass-through method to fulfill the ClientDetails interface with a bad name
*/
@Override
@Transient
public Set<String> getRegisteredRedirectUri() {
return getRedirectUris();
}
/** /**
* @return the resourceIds * Pass-through method to fulfill the ClientDetails interface with a bad name
*/ */
@Override
@Transient
public Set<String> getRegisteredRedirectUri() {
return getRedirectUris();
}
/**
* @return the resourceIds
*/
@Override
@ElementCollection(fetch = FetchType.EAGER) @ElementCollection(fetch = FetchType.EAGER)
@CollectionTable( @CollectionTable(
name="client_resource", name="client_resource",
joinColumns=@JoinColumn(name="owner_id") joinColumns=@JoinColumn(name="owner_id")
) )
@Column(name="resource_id") @Column(name="resource_id")
public Set<String> getResourceIds() { public Set<String> getResourceIds() {
return resourceIds; return resourceIds;
} }
/** /**
* @param resourceIds the resourceIds to set * @param resourceIds the resourceIds to set
*/ */
public void setResourceIds(Set<String> resourceIds) { public void setResourceIds(Set<String> resourceIds) {
this.resourceIds = resourceIds; this.resourceIds = resourceIds;
} }
/** /**
@ -580,7 +582,7 @@ public class ClientDetailsEntity implements ClientDetails {
@CollectionTable( @CollectionTable(
name="client_contact", name="client_contact",
joinColumns=@JoinColumn(name="owner_id") joinColumns=@JoinColumn(name="owner_id")
) )
@Column(name="contact") @Column(name="contact")
public Set<String> getContacts() { public Set<String> getContacts() {
return contacts; return contacts;
@ -611,36 +613,36 @@ public class ClientDetailsEntity implements ClientDetails {
} }
/** /**
* @return the clientUrl * @return the clientUrl
*/ */
@Basic @Basic
@Column(name="client_uri") @Column(name="client_uri")
public String getClientUri() { public String getClientUri() {
return clientUri; return clientUri;
} }
/** /**
* @param clientUrl the clientUrl to set * @param clientUrl the clientUrl to set
*/ */
public void setClientUri(String clientUri) { public void setClientUri(String clientUri) {
this.clientUri = clientUri; this.clientUri = clientUri;
} }
/** /**
* @return the tosUrl * @return the tosUrl
*/ */
@Basic @Basic
@Column(name="tos_uri") @Column(name="tos_uri")
public String getTosUri() { public String getTosUri() {
return tosUri; return tosUri;
} }
/** /**
* @param tosUrl the tosUrl to set * @param tosUrl the tosUrl to set
*/ */
public void setTosUri(String tosUri) { public void setTosUri(String tosUri) {
this.tosUri = tosUri; this.tosUri = tosUri;
} }
@Basic @Basic
@Column(name="jwks_uri") @Column(name="jwks_uri")
@ -773,7 +775,7 @@ public class ClientDetailsEntity implements ClientDetails {
@CollectionTable( @CollectionTable(
name="client_response_type", name="client_response_type",
joinColumns=@JoinColumn(name="response_type") joinColumns=@JoinColumn(name="response_type")
) )
@Column(name="response_type") @Column(name="response_type")
public Set<String> getResponseTypes() { public Set<String> getResponseTypes() {
return responseTypes; return responseTypes;
@ -793,7 +795,7 @@ public class ClientDetailsEntity implements ClientDetails {
@CollectionTable( @CollectionTable(
name="client_default_acr_value", name="client_default_acr_value",
joinColumns=@JoinColumn(name="owner_id") joinColumns=@JoinColumn(name="owner_id")
) )
@Column(name="default_acr_value") @Column(name="default_acr_value")
public Set<String> getDefaultACRvalues() { public Set<String> getDefaultACRvalues() {
return defaultACRvalues; return defaultACRvalues;
@ -845,7 +847,7 @@ public class ClientDetailsEntity implements ClientDetails {
@CollectionTable( @CollectionTable(
name="client_request_uri", name="client_request_uri",
joinColumns=@JoinColumn(name="owner_id") joinColumns=@JoinColumn(name="owner_id")
) )
@Column(name="request_uri") @Column(name="request_uri")
public Set<String> getRequestUris() { public Set<String> getRequestUris() {
return requestUris; return requestUris;
@ -863,15 +865,15 @@ public class ClientDetailsEntity implements ClientDetails {
*/ */
@Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.TIMESTAMP)
@Column(name="created_at") @Column(name="created_at")
public Date getCreatedAt() { public Date getCreatedAt() {
return createdAt; return createdAt;
} }
/** /**
* @param createdAt the createdAt to set * @param createdAt the createdAt to set
*/ */
public void setCreatedAt(Date createdAt) { public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt; this.createdAt = createdAt;
} }
} }

View File

@ -116,6 +116,7 @@ public class OAuth2AccessTokenEntity implements OAuth2AccessToken {
/** /**
* Get all additional information to be sent to the serializer. Inserts a copy of the IdToken (in JWT String form). * Get all additional information to be sent to the serializer. Inserts a copy of the IdToken (in JWT String form).
*/ */
@Override
@Transient @Transient
public Map<String, Object> getAdditionalInformation() { public Map<String, Object> getAdditionalInformation() {
Map<String, Object> map = new HashMap<String, Object>(); //super.getAdditionalInformation(); Map<String, Object> map = new HashMap<String, Object>(); //super.getAdditionalInformation();
@ -127,109 +128,115 @@ public class OAuth2AccessTokenEntity implements OAuth2AccessToken {
/** /**
* The authentication in place when this token was created. * The authentication in place when this token was created.
* @return the authentication * @return the authentication
*/ */
@ManyToOne @ManyToOne
@JoinColumn(name = "auth_holder_id") @JoinColumn(name = "auth_holder_id")
public AuthenticationHolderEntity getAuthenticationHolder() { public AuthenticationHolderEntity getAuthenticationHolder() {
return authenticationHolder; return authenticationHolder;
} }
/** /**
* @param authentication the authentication to set * @param authentication the authentication to set
*/ */
public void setAuthenticationHolder(AuthenticationHolderEntity authenticationHolder) { public void setAuthenticationHolder(AuthenticationHolderEntity authenticationHolder) {
this.authenticationHolder = authenticationHolder; this.authenticationHolder = authenticationHolder;
} }
/** /**
* @return the client * @return the client
*/ */
@ManyToOne @ManyToOne
@JoinColumn(name = "client_id") @JoinColumn(name = "client_id")
public ClientDetailsEntity getClient() { public ClientDetailsEntity getClient() {
return client; return client;
} }
/** /**
* @param client the client to set * @param client the client to set
*/ */
public void setClient(ClientDetailsEntity client) { public void setClient(ClientDetailsEntity client) {
this.client = client; this.client = client;
} }
/** /**
* Get the string-encoded value of this access token. * Get the string-encoded value of this access token.
*/ */
@Basic @Override
@Column(name="token_value") @Basic
public String getValue() { @Column(name="token_value")
public String getValue() {
return jwtValue.serialize(); return jwtValue.serialize();
} }
/** /**
* Set the "value" of this Access Token * Set the "value" of this Access Token
* *
* @param value the JWT string * @param value the JWT string
* @throws ParseException if "value" is not a properly formatted JWT string * @throws ParseException if "value" is not a properly formatted JWT string
*/ */
public void setValue(String value) throws ParseException { public void setValue(String value) throws ParseException {
setJwt(JWTParser.parse(value)); setJwt(JWTParser.parse(value));
} }
@Basic @Override
@Temporal(javax.persistence.TemporalType.TIMESTAMP) @Basic
public Date getExpiration() { @Temporal(javax.persistence.TemporalType.TIMESTAMP)
return expiration; public Date getExpiration() {
} return expiration;
}
public void setExpiration(Date expiration) { public void setExpiration(Date expiration) {
this.expiration = expiration; this.expiration = expiration;
} }
@Basic @Override
@Column(name="token_type") @Basic
public String getTokenType() { @Column(name="token_type")
return tokenType; public String getTokenType() {
} return tokenType;
}
public void setTokenType(String tokenType) { public void setTokenType(String tokenType) {
this.tokenType = tokenType; this.tokenType = tokenType;
} }
@ManyToOne @Override
@JoinColumn(name="refresh_token_id") @ManyToOne
public OAuth2RefreshTokenEntity getRefreshToken() { @JoinColumn(name="refresh_token_id")
return refreshToken; public OAuth2RefreshTokenEntity getRefreshToken() {
} return refreshToken;
}
public void setRefreshToken(OAuth2RefreshTokenEntity refreshToken) { public void setRefreshToken(OAuth2RefreshTokenEntity refreshToken) {
this.refreshToken = refreshToken; this.refreshToken = refreshToken;
} }
public void setRefreshToken(OAuth2RefreshToken refreshToken) { public void setRefreshToken(OAuth2RefreshToken refreshToken) {
if (!(refreshToken instanceof OAuth2RefreshTokenEntity)) { if (!(refreshToken instanceof OAuth2RefreshTokenEntity)) {
// TODO: make a copy constructor instead.... // TODO: make a copy constructor instead....
throw new IllegalArgumentException("Not a storable refresh token entity!"); throw new IllegalArgumentException("Not a storable refresh token entity!");
} }
// force a pass through to the entity version // force a pass through to the entity version
setRefreshToken((OAuth2RefreshTokenEntity)refreshToken); setRefreshToken((OAuth2RefreshTokenEntity)refreshToken);
} }
@ElementCollection(fetch=FetchType.EAGER) @Override
@CollectionTable( @ElementCollection(fetch=FetchType.EAGER)
joinColumns=@JoinColumn(name="owner_id"), @CollectionTable(
name="token_scope" joinColumns=@JoinColumn(name="owner_id"),
) name="token_scope"
public Set<String> getScope() { )
return scope; public Set<String> getScope() {
} return scope;
}
public void setScope(Set<String> scope) { public void setScope(Set<String> scope) {
this.scope = scope; this.scope = scope;
} }
@Transient @Override
@Transient
public boolean isExpired() { public boolean isExpired() {
return getExpiration() == null ? false : System.currentTimeMillis() > getExpiration().getTime(); return getExpiration() == null ? false : System.currentTimeMillis() > getExpiration().getTime();
} }
@ -237,8 +244,8 @@ public class OAuth2AccessTokenEntity implements OAuth2AccessToken {
/** /**
* @return the idToken * @return the idToken
*/ */
@OneToOne(cascade=CascadeType.ALL) // one-to-one mapping for now @OneToOne(cascade=CascadeType.ALL) // one-to-one mapping for now
@JoinColumn(name = "id_token_id") @JoinColumn(name = "id_token_id")
public OAuth2AccessTokenEntity getIdToken() { public OAuth2AccessTokenEntity getIdToken() {
return idToken; return idToken;
} }

View File

@ -39,9 +39,7 @@ import javax.persistence.Transient;
import org.springframework.security.oauth2.common.OAuth2RefreshToken; import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWT;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.JWTParser; import com.nimbusds.jwt.JWTParser;
import com.nimbusds.jwt.PlainJWT;
/** /**
* @author jricher * @author jricher
@ -96,92 +94,93 @@ public class OAuth2RefreshTokenEntity implements OAuth2RefreshToken {
* The authentication in place when the original access token was * The authentication in place when the original access token was
* created * created
* *
* @return the authentication * @return the authentication
*/ */
@ManyToOne @ManyToOne
@JoinColumn(name = "auth_holder_id") @JoinColumn(name = "auth_holder_id")
public AuthenticationHolderEntity getAuthenticationHolder() { public AuthenticationHolderEntity getAuthenticationHolder() {
return authenticationHolder; return authenticationHolder;
} }
/** /**
* @param authentication the authentication to set * @param authentication the authentication to set
*/ */
public void setAuthenticationHolder(AuthenticationHolderEntity authenticationHolder) { public void setAuthenticationHolder(AuthenticationHolderEntity authenticationHolder) {
this.authenticationHolder = authenticationHolder; this.authenticationHolder = authenticationHolder;
} }
/** /**
* Get the JWT-encoded value of this token * Get the JWT-encoded value of this token
*/ */
@Basic @Override
@Column(name="token_value") @Basic
public String getValue() { @Column(name="token_value")
return jwt.serialize(); public String getValue() {
} return jwt.serialize();
}
/** /**
* Set the value of this token as a string. Parses the string into a JWT. * Set the value of this token as a string. Parses the string into a JWT.
* @param value * @param value
* @throws ParseException if the value is not a valid JWT string * @throws ParseException if the value is not a valid JWT string
*/ */
public void setValue(String value) throws ParseException { public void setValue(String value) throws ParseException {
setJwt(JWTParser.parse(value)); setJwt(JWTParser.parse(value));
} }
@Basic @Basic
@Temporal(javax.persistence.TemporalType.TIMESTAMP) @Temporal(javax.persistence.TemporalType.TIMESTAMP)
public Date getExpiration() { public Date getExpiration() {
return expiration; return expiration;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken#setExpiration(java.util.Date) * @see org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken#setExpiration(java.util.Date)
*/ */
public void setExpiration(Date expiration) { public void setExpiration(Date expiration) {
this.expiration = expiration; this.expiration = expiration;
} }
/** /**
* Has this token expired? * Has this token expired?
* @return true if it has a timeout set and the timeout has passed * @return true if it has a timeout set and the timeout has passed
*/ */
@Transient @Transient
public boolean isExpired() { public boolean isExpired() {
return getExpiration() == null ? false : System.currentTimeMillis() > getExpiration().getTime(); return getExpiration() == null ? false : System.currentTimeMillis() > getExpiration().getTime();
} }
/** /**
* @return the client * @return the client
*/ */
@ManyToOne(fetch = FetchType.EAGER) @ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "client_id") @JoinColumn(name = "client_id")
public ClientDetailsEntity getClient() { public ClientDetailsEntity getClient() {
return client; return client;
} }
/** /**
* @param client the client to set * @param client the client to set
*/ */
public void setClient(ClientDetailsEntity client) { public void setClient(ClientDetailsEntity client) {
this.client = client; this.client = client;
} }
/** /**
* Get the JWT object directly * Get the JWT object directly
* @return the jwt * @return the jwt
*/ */
@Transient @Transient
public JWT getJwt() { public JWT getJwt() {
return jwt; return jwt;
} }
/** /**
* @param jwt the jwt to set * @param jwt the jwt to set
*/ */
public void setJwt(JWT jwt) { public void setJwt(JWT jwt) {
this.jwt = jwt; this.jwt = jwt;
} }
} }

View File

@ -43,9 +43,9 @@ public class SystemScope {
* Make a system scope with the given scope value * Make a system scope with the given scope value
* @param value * @param value
*/ */
public SystemScope(String value) { public SystemScope(String value) {
this.value = value; this.value = value;
} }
/** /**
* @return the id * @return the id
*/ */
@ -136,70 +136,70 @@ public class SystemScope {
/* (non-Javadoc) /* (non-Javadoc)
* @see java.lang.Object#hashCode() * @see java.lang.Object#hashCode()
*/ */
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + (allowDynReg ? 1231 : 1237); result = prime * result + (allowDynReg ? 1231 : 1237);
result = prime * result + (defaultScope ? 1231 : 1237); result = prime * result + (defaultScope ? 1231 : 1237);
result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((icon == null) ? 0 : icon.hashCode()); result = prime * result + ((icon == null) ? 0 : icon.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode());
return result; return result;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object) * @see java.lang.Object#equals(java.lang.Object)
*/ */
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (getClass() != obj.getClass()) { if (getClass() != obj.getClass()) {
return false; return false;
} }
SystemScope other = (SystemScope) obj; SystemScope other = (SystemScope) obj;
if (allowDynReg != other.allowDynReg) { if (allowDynReg != other.allowDynReg) {
return false; return false;
} }
if (defaultScope != other.defaultScope) { if (defaultScope != other.defaultScope) {
return false; return false;
} }
if (description == null) { if (description == null) {
if (other.description != null) { if (other.description != null) {
return false; return false;
} }
} else if (!description.equals(other.description)) { } else if (!description.equals(other.description)) {
return false; return false;
} }
if (icon == null) { if (icon == null) {
if (other.icon != null) { if (other.icon != null) {
return false; return false;
} }
} else if (!icon.equals(other.icon)) { } else if (!icon.equals(other.icon)) {
return false; return false;
} }
if (id == null) { if (id == null) {
if (other.id != null) { if (other.id != null) {
return false; return false;
} }
} else if (!id.equals(other.id)) { } else if (!id.equals(other.id)) {
return false; return false;
} }
if (value == null) { if (value == null) {
if (other.value != null) { if (other.value != null) {
return false; return false;
} }
} else if (!value.equals(other.value)) { } else if (!value.equals(other.value)) {
return false; return false;
} }
return true; return true;
} }

View File

@ -55,8 +55,8 @@ public interface OAuth2TokenRepository {
public OAuth2AccessTokenEntity getByAuthentication(OAuth2Authentication auth); public OAuth2AccessTokenEntity getByAuthentication(OAuth2Authentication auth);
/** /**
* @return * @return
*/ */
public OAuth2AccessTokenEntity getAccessTokenForIdToken(OAuth2AccessTokenEntity idToken); public OAuth2AccessTokenEntity getAccessTokenForIdToken(OAuth2AccessTokenEntity idToken);
} }

View File

@ -27,6 +27,7 @@ public interface ClientDetailsEntityService extends ClientDetailsService {
public ClientDetailsEntity getClientById(Long id); public ClientDetailsEntity getClientById(Long id);
@Override
public ClientDetailsEntity loadClientByClientId(String clientId) throws OAuth2Exception; public ClientDetailsEntity loadClientByClientId(String clientId) throws OAuth2Exception;
public void deleteClient(ClientDetailsEntity client); public void deleteClient(ClientDetailsEntity client);

View File

@ -26,6 +26,7 @@ import org.springframework.security.oauth2.provider.token.ResourceServerTokenSer
public interface OAuth2TokenEntityService extends AuthorizationServerTokenServices, ResourceServerTokenServices { public interface OAuth2TokenEntityService extends AuthorizationServerTokenServices, ResourceServerTokenServices {
@Override
public OAuth2AccessTokenEntity readAccessToken(String accessTokenValue); public OAuth2AccessTokenEntity readAccessToken(String accessTokenValue);
public OAuth2RefreshTokenEntity getRefreshToken(String refreshTokenValue); public OAuth2RefreshTokenEntity getRefreshToken(String refreshTokenValue);
@ -44,14 +45,15 @@ public interface OAuth2TokenEntityService extends AuthorizationServerTokenServic
public OAuth2RefreshTokenEntity saveRefreshToken(OAuth2RefreshTokenEntity refreshToken); public OAuth2RefreshTokenEntity saveRefreshToken(OAuth2RefreshTokenEntity refreshToken);
@Override
public OAuth2AccessTokenEntity getAccessToken(OAuth2Authentication authentication); public OAuth2AccessTokenEntity getAccessToken(OAuth2Authentication authentication);
public OAuth2AccessTokenEntity getAccessTokenById(Long id); public OAuth2AccessTokenEntity getAccessTokenById(Long id);
/** /**
* @param incomingToken * @param incomingToken
* @return * @return
*/ */
public OAuth2AccessTokenEntity getAccessTokenForIdToken(OAuth2AccessTokenEntity idToken); public OAuth2AccessTokenEntity getAccessTokenForIdToken(OAuth2AccessTokenEntity idToken);
} }

View File

@ -17,7 +17,6 @@ package org.mitre.oauth2.service.impl;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
@ -44,32 +43,32 @@ public class DefaultClientUserDetailsService implements UserDetailsService {
private ClientDetailsService clientDetailsService; private ClientDetailsService clientDetailsService;
@Override @Override
public UserDetails loadUserByUsername(String clientId) throws UsernameNotFoundException, DataAccessException { public UserDetails loadUserByUsername(String clientId) throws UsernameNotFoundException, DataAccessException {
ClientDetails client = clientDetailsService.loadClientByClientId(clientId); ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
if (client != null) { if (client != null) {
String password = client.getClientSecret(); String password = client.getClientSecret();
boolean enabled = true; boolean enabled = true;
boolean accountNonExpired = true; boolean accountNonExpired = true;
boolean credentialsNonExpired = true; boolean credentialsNonExpired = true;
boolean accountNonLocked = true; boolean accountNonLocked = true;
Collection<GrantedAuthority> authorities = client.getAuthorities(); Collection<GrantedAuthority> authorities = client.getAuthorities();
if (authorities == null || authorities.isEmpty()) { if (authorities == null || authorities.isEmpty()) {
// automatically inject ROLE_CLIENT if none exists ... // automatically inject ROLE_CLIENT if none exists ...
// TODO: this should probably happen on the client service side instead to keep it in the real data model // TODO: this should probably happen on the client service side instead to keep it in the real data model
authorities = new ArrayList<GrantedAuthority>(); authorities = new ArrayList<GrantedAuthority>();
GrantedAuthority roleClient = new SimpleGrantedAuthority("ROLE_CLIENT"); GrantedAuthority roleClient = new SimpleGrantedAuthority("ROLE_CLIENT");
authorities.add(roleClient); authorities.add(roleClient);
} }
return new User(clientId, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); return new User(clientId, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
} else { } else {
throw new UsernameNotFoundException("Client not found: " + clientId); throw new UsernameNotFoundException("Client not found: " + clientId);
} }
} }
public ClientDetailsService getClientDetailsService() { public ClientDetailsService getClientDetailsService() {
return clientDetailsService; return clientDetailsService;

View File

@ -125,19 +125,19 @@ public class Address {
} }
/** /**
* @return the id * @return the id
*/ */
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy=GenerationType.IDENTITY)
public Long getId() { public Long getId() {
return id; return id;
} }
/** /**
* @param id the id to set * @param id the id to set
*/ */
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
} }

View File

@ -52,9 +52,9 @@ import com.google.common.collect.Sets;
public class ApprovedSite { public class ApprovedSite {
// unique id // unique id
private Long id; private Long id;
// which user made the approval // which user made the approval
private String userId; private String userId;
// which OAuth2 client is this tied to // which OAuth2 client is this tied to
@ -84,132 +84,132 @@ public class ApprovedSite {
*/ */
public ApprovedSite() { public ApprovedSite() {
} }
/** /**
* @return the id * @return the id
*/ */
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() { public Long getId() {
return id; return id;
} }
/** /**
* @param id the id to set * @param id the id to set
*/ */
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
/** /**
* @return the userInfo * @return the userInfo
*/ */
@Basic @Basic
@Column(name="user_id") @Column(name="user_id")
public String getUserId() { public String getUserId() {
return userId; return userId;
} }
/** /**
* @param userInfo the userInfo to set * @param userInfo the userInfo to set
*/ */
public void setUserId(String userId) { public void setUserId(String userId) {
this.userId = userId; this.userId = userId;
} }
/** /**
* @return the clientId * @return the clientId
*/ */
@Basic @Basic
@Column(name="client_id") @Column(name="client_id")
public String getClientId() { public String getClientId() {
return clientId; return clientId;
} }
/** /**
* @param clientId the clientId to set * @param clientId the clientId to set
*/ */
public void setClientId(String clientId) { public void setClientId(String clientId) {
this.clientId = clientId; this.clientId = clientId;
} }
/** /**
* @return the creationDate * @return the creationDate
*/ */
@Basic @Basic
@Temporal(javax.persistence.TemporalType.TIMESTAMP) @Temporal(javax.persistence.TemporalType.TIMESTAMP)
@Column(name="creation_date") @Column(name="creation_date")
public Date getCreationDate() { public Date getCreationDate() {
return creationDate; return creationDate;
} }
/** /**
* @param creationDate the creationDate to set * @param creationDate the creationDate to set
*/ */
public void setCreationDate(Date creationDate) { public void setCreationDate(Date creationDate) {
this.creationDate = creationDate; this.creationDate = creationDate;
} }
/** /**
* @return the accessDate * @return the accessDate
*/ */
@Basic @Basic
@Temporal(javax.persistence.TemporalType.TIMESTAMP) @Temporal(javax.persistence.TemporalType.TIMESTAMP)
@Column(name="access_date") @Column(name="access_date")
public Date getAccessDate() { public Date getAccessDate() {
return accessDate; return accessDate;
} }
/** /**
* @param accessDate the accessDate to set * @param accessDate the accessDate to set
*/ */
public void setAccessDate(Date accessDate) { public void setAccessDate(Date accessDate) {
this.accessDate = accessDate; this.accessDate = accessDate;
} }
/** /**
* @return the allowedScopes * @return the allowedScopes
*/ */
@ElementCollection(fetch = FetchType.EAGER) @ElementCollection(fetch = FetchType.EAGER)
@CollectionTable( @CollectionTable(
name="approved_site_scope", name="approved_site_scope",
joinColumns=@JoinColumn(name="owner_id") joinColumns=@JoinColumn(name="owner_id")
) )
@Column(name="scope") @Column(name="scope")
public Set<String> getAllowedScopes() { public Set<String> getAllowedScopes() {
return allowedScopes; return allowedScopes;
} }
/** /**
* @param allowedScopes the allowedScopes to set * @param allowedScopes the allowedScopes to set
*/ */
public void setAllowedScopes(Set<String> allowedScopes) { public void setAllowedScopes(Set<String> allowedScopes) {
this.allowedScopes = allowedScopes; this.allowedScopes = allowedScopes;
} }
/** /**
* @return the timeoutDate * @return the timeoutDate
*/ */
@Basic @Basic
@Temporal(javax.persistence.TemporalType.TIMESTAMP) @Temporal(javax.persistence.TemporalType.TIMESTAMP)
@Column(name="timeout_date") @Column(name="timeout_date")
public Date getTimeoutDate() { public Date getTimeoutDate() {
return timeoutDate; return timeoutDate;
} }
/** /**
* @param timeoutDate the timeoutDate to set * @param timeoutDate the timeoutDate to set
*/ */
public void setTimeoutDate(Date timeoutDate) { public void setTimeoutDate(Date timeoutDate) {
this.timeoutDate = timeoutDate; this.timeoutDate = timeoutDate;
} }
/** /**
* Does this AP entry correspond to a WS? * Does this AP entry correspond to a WS?
* @return * @return
*/ */
@Transient @Transient
public Boolean getIsWhitelisted() { public Boolean getIsWhitelisted() {
return (whitelistedSite != null); return (whitelistedSite != null);
} }
@ -227,10 +227,10 @@ public class ApprovedSite {
/** /**
* Has this approval expired? * Has this approval expired?
* @return * @return
*/ */
@Transient @Transient
public boolean isExpired() { public boolean isExpired() {
if (getTimeoutDate() != null) { if (getTimeoutDate() != null) {
Date now = new Date(); Date now = new Date();
if (now.after(getTimeoutDate())) { if (now.after(getTimeoutDate())) {
@ -241,7 +241,7 @@ public class ApprovedSite {
} else { } else {
return false; return false;
} }
} }
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="approved_site_id") @JoinColumn(name="approved_site_id")

View File

@ -24,41 +24,41 @@ import javax.persistence.Table;
}) })
public class BlacklistedSite { public class BlacklistedSite {
// unique id // unique id
private Long id; private Long id;
// URI pattern to black list // URI pattern to black list
private String uri; private String uri;
public BlacklistedSite() { public BlacklistedSite() {
} }
/** /**
* @return the id * @return the id
*/ */
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() { public Long getId() {
return id; return id;
} }
/** /**
* @param id the id to set * @param id the id to set
*/ */
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
@Basic @Basic
@Column(name="uri") @Column(name="uri")
public String getUri() { public String getUri() {
return uri; return uri;
} }
public void setUri(String uri) { public void setUri(String uri) {
this.uri = uri; this.uri = uri;
} }
} }

View File

@ -356,21 +356,23 @@ public class DefaultUserInfo implements UserInfo {
} }
/** /**
* @return the birthdate * @return the birthdate
*/ */
@Override
@Basic @Basic
@Column(name="birthdate") @Column(name="birthdate")
public String getBirthdate() { public String getBirthdate() {
return birthdate; return birthdate;
} }
/** /**
* @param birthdate the birthdate to set * @param birthdate the birthdate to set
*/ */
public void setBirthdate(String birthdate) { @Override
this.birthdate = birthdate; public void setBirthdate(String birthdate) {
} this.birthdate = birthdate;
}
/** /**
* Parse a JsonObject into a UserInfo. * Parse a JsonObject into a UserInfo.
* @param o * @param o
* @return * @return

View File

@ -43,44 +43,44 @@ public class Event {
private Date timestamp; private Date timestamp;
/** /**
* @return the id * @return the id
*/ */
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy=GenerationType.IDENTITY)
public Long getId() { public Long getId() {
return id; return id;
} }
/** /**
* @param id the id to set * @param id the id to set
*/ */
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
/** /**
* @return the type * @return the type
*/ */
public EventType getType() { public EventType getType() {
return type; return type;
} }
/** /**
* @param type the type to set * @param type the type to set
*/ */
public void setType(EventType type) { public void setType(EventType type) {
this.type = type; this.type = type;
} }
/** /**
* @return the timestamp * @return the timestamp
*/ */
@Basic @Basic
@Temporal(javax.persistence.TemporalType.TIMESTAMP) @Temporal(javax.persistence.TemporalType.TIMESTAMP)
public Date getTimestamp() { public Date getTimestamp() {
return timestamp; return timestamp;
} }
/** /**
* @param timestamp the timestamp to set * @param timestamp the timestamp to set
*/ */
public void setTimestamp(Date timestamp) { public void setTimestamp(Date timestamp) {
this.timestamp = timestamp; this.timestamp = timestamp;
} }
} }

View File

@ -86,7 +86,7 @@ public class Nonce {
* @return the useDate * @return the useDate
*/ */
@Basic @Basic
@Temporal(javax.persistence.TemporalType.TIMESTAMP) @Temporal(javax.persistence.TemporalType.TIMESTAMP)
@Column(name="use_date") @Column(name="use_date")
public Date getUseDate() { public Date getUseDate() {
return useDate; return useDate;
@ -103,7 +103,7 @@ public class Nonce {
* @return the expireDate * @return the expireDate
*/ */
@Basic @Basic
@Temporal(javax.persistence.TemporalType.TIMESTAMP) @Temporal(javax.persistence.TemporalType.TIMESTAMP)
@Column(name="expire_date") @Column(name="expire_date")
public Date getExpireDate() { public Date getExpireDate() {
return expireDate; return expireDate;

View File

@ -47,9 +47,9 @@ import javax.persistence.Table;
public class WhitelistedSite { public class WhitelistedSite {
// unique id // unique id
private Long id; private Long id;
// Reference to the admin user who created this entry // Reference to the admin user who created this entry
private String creatorUserId; private String creatorUserId;
// which OAuth2 client is this tied to // which OAuth2 client is this tied to
@ -70,7 +70,7 @@ public class WhitelistedSite {
* @return the id * @return the id
*/ */
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() { public Long getId() {
return id; return id;
} }
@ -103,9 +103,9 @@ public class WhitelistedSite {
*/ */
@ElementCollection(fetch = FetchType.EAGER) @ElementCollection(fetch = FetchType.EAGER)
@CollectionTable( @CollectionTable(
name="whitelisted_site_scope", name="whitelisted_site_scope",
joinColumns=@JoinColumn(name="owner_id") joinColumns=@JoinColumn(name="owner_id")
) )
@Column(name="scope") @Column(name="scope")
public Set<String> getAllowedScopes() { public Set<String> getAllowedScopes() {
return allowedScopes; return allowedScopes;

View File

@ -1,6 +1,7 @@
package org.mitre.openid.connect.repository; package org.mitre.openid.connect.repository;
import java.util.Collection; import java.util.Collection;
import org.mitre.openid.connect.model.Nonce; import org.mitre.openid.connect.model.Nonce;
/** /**

View File

@ -77,10 +77,10 @@ public interface WhitelistedSiteRepository {
/** /**
* Persist changes to a whitelistedSite. The ID of oldWhitelistedSite is retained. * Persist changes to a whitelistedSite. The ID of oldWhitelistedSite is retained.
* @param oldWhitelistedSite * @param oldWhitelistedSite
* @param whitelistedSite * @param whitelistedSite
* @return * @return
*/ */
public WhitelistedSite update(WhitelistedSite oldWhitelistedSite, WhitelistedSite whitelistedSite); public WhitelistedSite update(WhitelistedSite oldWhitelistedSite, WhitelistedSite whitelistedSite);
} }

View File

@ -14,9 +14,9 @@ public interface StatsService {
/** /**
* Calculate summary statistics * Calculate summary statistics
* approvalCount: total approved sites * approvalCount: total approved sites
* userCount: unique users * userCount: unique users
* clientCount: unique clients * clientCount: unique clients
* *
* @return * @return
*/ */
public Map<String, Integer> calculateSummaryStats(); public Map<String, Integer> calculateSummaryStats();

View File

@ -27,26 +27,26 @@ import org.springframework.dao.IncorrectResultSizeDataAccessException;
* Time: 2:13 PM * Time: 2:13 PM
*/ */
public class JpaUtil { public class JpaUtil {
public static <T> T getSingleResult(List<T> list) { public static <T> T getSingleResult(List<T> list) {
switch(list.size()) { switch(list.size()) {
case 0: case 0:
return null; return null;
case 1: case 1:
return list.get(0); return list.get(0);
default: default:
throw new IncorrectResultSizeDataAccessException(1); throw new IncorrectResultSizeDataAccessException(1);
} }
} }
public static <T, I> T saveOrUpdate(I id, EntityManager entityManager, T entity) { public static <T, I> T saveOrUpdate(I id, EntityManager entityManager, T entity) {
if (id == null) { if (id == null) {
entityManager.persist(entity); entityManager.persist(entity);
entityManager.flush(); entityManager.flush();
return entity; return entity;
} else { } else {
T tmp = entityManager.merge(entity); T tmp = entityManager.merge(entity);
entityManager.flush(); entityManager.flush();
return tmp; return tmp;
} }
} }
} }

View File

@ -18,13 +18,13 @@ package org.mitre.oauth2.exception;
public class DuplicateClientIdException extends RuntimeException { public class DuplicateClientIdException extends RuntimeException {
public DuplicateClientIdException(String clientId) { public DuplicateClientIdException(String clientId) {
super("Duplicate client id: " + clientId); super("Duplicate client id: " + clientId);
} }
/** /**
* *
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
} }

View File

@ -46,6 +46,7 @@ public class JpaOAuth2ClientRepository implements OAuth2ClientRepository {
this.manager = manager; this.manager = manager;
} }
@Override
public ClientDetailsEntity getById(Long id) { public ClientDetailsEntity getById(Long id) {
return manager.find(ClientDetailsEntity.class, id); return manager.find(ClientDetailsEntity.class, id);
} }
@ -82,17 +83,17 @@ public class JpaOAuth2ClientRepository implements OAuth2ClientRepository {
} }
@Override @Override
public ClientDetailsEntity updateClient(Long id, ClientDetailsEntity client) { public ClientDetailsEntity updateClient(Long id, ClientDetailsEntity client) {
// sanity check // sanity check
client.setId(id); client.setId(id);
return JpaUtil.saveOrUpdate(id, manager, client); return JpaUtil.saveOrUpdate(id, manager, client);
} }
@Override @Override
public Collection<ClientDetailsEntity> getAllClients() { public Collection<ClientDetailsEntity> getAllClients() {
TypedQuery<ClientDetailsEntity> query = manager.createNamedQuery("ClientDetailsEntity.findAll", ClientDetailsEntity.class); TypedQuery<ClientDetailsEntity> query = manager.createNamedQuery("ClientDetailsEntity.findAll", ClientDetailsEntity.class);
return query.getResultList(); return query.getResultList();
} }
} }

View File

@ -67,14 +67,14 @@ public class JpaOAuth2TokenRepository implements OAuth2TokenRepository {
@Override @Override
@Transactional @Transactional
public void clearAccessTokensForRefreshToken(OAuth2RefreshTokenEntity refreshToken) { public void clearAccessTokensForRefreshToken(OAuth2RefreshTokenEntity refreshToken) {
TypedQuery<OAuth2AccessTokenEntity> query = manager.createNamedQuery("OAuth2AccessTokenEntity.getByRefreshToken", OAuth2AccessTokenEntity.class); TypedQuery<OAuth2AccessTokenEntity> query = manager.createNamedQuery("OAuth2AccessTokenEntity.getByRefreshToken", OAuth2AccessTokenEntity.class);
query.setParameter("refreshToken", refreshToken); query.setParameter("refreshToken", refreshToken);
List<OAuth2AccessTokenEntity> accessTokens = query.getResultList(); List<OAuth2AccessTokenEntity> accessTokens = query.getResultList();
for (OAuth2AccessTokenEntity accessToken : accessTokens) { for (OAuth2AccessTokenEntity accessToken : accessTokens) {
removeAccessToken(accessToken); removeAccessToken(accessToken);
} }
} }
@Override @Override
public OAuth2RefreshTokenEntity getRefreshTokenByValue(String refreshTokenValue) { public OAuth2RefreshTokenEntity getRefreshTokenByValue(String refreshTokenValue) {
@ -96,91 +96,91 @@ public class JpaOAuth2TokenRepository implements OAuth2TokenRepository {
@Override @Override
@Transactional @Transactional
public void removeRefreshToken(OAuth2RefreshTokenEntity refreshToken) { public void removeRefreshToken(OAuth2RefreshTokenEntity refreshToken) {
OAuth2RefreshTokenEntity found = getRefreshTokenByValue(refreshToken.getValue()); OAuth2RefreshTokenEntity found = getRefreshTokenByValue(refreshToken.getValue());
if (found != null) { if (found != null) {
manager.remove(found); manager.remove(found);
} else { } else {
throw new IllegalArgumentException("Refresh token not found: " + refreshToken); throw new IllegalArgumentException("Refresh token not found: " + refreshToken);
} }
} }
@Override @Override
@Transactional @Transactional
public void clearTokensForClient(ClientDetailsEntity client) { public void clearTokensForClient(ClientDetailsEntity client) {
TypedQuery<OAuth2AccessTokenEntity> queryA = manager.createNamedQuery("OAuth2AccessTokenEntity.getByClient", OAuth2AccessTokenEntity.class); TypedQuery<OAuth2AccessTokenEntity> queryA = manager.createNamedQuery("OAuth2AccessTokenEntity.getByClient", OAuth2AccessTokenEntity.class);
queryA.setParameter("client", client); queryA.setParameter("client", client);
List<OAuth2AccessTokenEntity> accessTokens = queryA.getResultList(); List<OAuth2AccessTokenEntity> accessTokens = queryA.getResultList();
for (OAuth2AccessTokenEntity accessToken : accessTokens) { for (OAuth2AccessTokenEntity accessToken : accessTokens) {
removeAccessToken(accessToken); removeAccessToken(accessToken);
} }
TypedQuery<OAuth2RefreshTokenEntity> queryR = manager.createNamedQuery("OAuth2RefreshTokenEntity.getByClient", OAuth2RefreshTokenEntity.class); TypedQuery<OAuth2RefreshTokenEntity> queryR = manager.createNamedQuery("OAuth2RefreshTokenEntity.getByClient", OAuth2RefreshTokenEntity.class);
queryR.setParameter("client", client); queryR.setParameter("client", client);
List<OAuth2RefreshTokenEntity> refreshTokens = queryR.getResultList(); List<OAuth2RefreshTokenEntity> refreshTokens = queryR.getResultList();
for (OAuth2RefreshTokenEntity refreshToken : refreshTokens) { for (OAuth2RefreshTokenEntity refreshToken : refreshTokens) {
removeRefreshToken(refreshToken); removeRefreshToken(refreshToken);
} }
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.repository.OAuth2TokenRepository#getAccessTokensForClient(org.mitre.oauth2.model.ClientDetailsEntity) * @see org.mitre.oauth2.repository.OAuth2TokenRepository#getAccessTokensForClient(org.mitre.oauth2.model.ClientDetailsEntity)
*/ */
@Override @Override
public List<OAuth2AccessTokenEntity> getAccessTokensForClient(ClientDetailsEntity client) { public List<OAuth2AccessTokenEntity> getAccessTokensForClient(ClientDetailsEntity client) {
TypedQuery<OAuth2AccessTokenEntity> queryA = manager.createNamedQuery("OAuth2AccessTokenEntity.getByClient", OAuth2AccessTokenEntity.class); TypedQuery<OAuth2AccessTokenEntity> queryA = manager.createNamedQuery("OAuth2AccessTokenEntity.getByClient", OAuth2AccessTokenEntity.class);
queryA.setParameter("client", client); queryA.setParameter("client", client);
List<OAuth2AccessTokenEntity> accessTokens = queryA.getResultList(); List<OAuth2AccessTokenEntity> accessTokens = queryA.getResultList();
return accessTokens; return accessTokens;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.repository.OAuth2TokenRepository#getRefreshTokensForClient(org.mitre.oauth2.model.ClientDetailsEntity) * @see org.mitre.oauth2.repository.OAuth2TokenRepository#getRefreshTokensForClient(org.mitre.oauth2.model.ClientDetailsEntity)
*/ */
@Override @Override
public List<OAuth2RefreshTokenEntity> getRefreshTokensForClient(ClientDetailsEntity client) { public List<OAuth2RefreshTokenEntity> getRefreshTokensForClient(ClientDetailsEntity client) {
TypedQuery<OAuth2RefreshTokenEntity> queryR = manager.createNamedQuery("OAuth2RefreshTokenEntity.getByClient", OAuth2RefreshTokenEntity.class); TypedQuery<OAuth2RefreshTokenEntity> queryR = manager.createNamedQuery("OAuth2RefreshTokenEntity.getByClient", OAuth2RefreshTokenEntity.class);
queryR.setParameter("client", client); queryR.setParameter("client", client);
List<OAuth2RefreshTokenEntity> refreshTokens = queryR.getResultList(); List<OAuth2RefreshTokenEntity> refreshTokens = queryR.getResultList();
return refreshTokens; return refreshTokens;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.repository.OAuth2TokenRepository#getExpiredAccessTokens() * @see org.mitre.oauth2.repository.OAuth2TokenRepository#getExpiredAccessTokens()
*/ */
@Override @Override
public List<OAuth2AccessTokenEntity> getExpiredAccessTokens() { public List<OAuth2AccessTokenEntity> getExpiredAccessTokens() {
TypedQuery<OAuth2AccessTokenEntity> queryA = manager.createNamedQuery("OAuth2AccessTokenEntity.getExpired", OAuth2AccessTokenEntity.class); TypedQuery<OAuth2AccessTokenEntity> queryA = manager.createNamedQuery("OAuth2AccessTokenEntity.getExpired", OAuth2AccessTokenEntity.class);
List<OAuth2AccessTokenEntity> accessTokens = queryA.getResultList(); List<OAuth2AccessTokenEntity> accessTokens = queryA.getResultList();
return accessTokens; return accessTokens;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.repository.OAuth2TokenRepository#getExpiredRefreshTokens() * @see org.mitre.oauth2.repository.OAuth2TokenRepository#getExpiredRefreshTokens()
*/ */
@Override @Override
public List<OAuth2RefreshTokenEntity> getExpiredRefreshTokens() { public List<OAuth2RefreshTokenEntity> getExpiredRefreshTokens() {
TypedQuery<OAuth2RefreshTokenEntity> queryR = manager.createNamedQuery("OAuth2RefreshTokenEntity.getExpired", OAuth2RefreshTokenEntity.class); TypedQuery<OAuth2RefreshTokenEntity> queryR = manager.createNamedQuery("OAuth2RefreshTokenEntity.getExpired", OAuth2RefreshTokenEntity.class);
List<OAuth2RefreshTokenEntity> refreshTokens = queryR.getResultList(); List<OAuth2RefreshTokenEntity> refreshTokens = queryR.getResultList();
return refreshTokens; return refreshTokens;
} }
@Override @Override
public OAuth2AccessTokenEntity getByAuthentication(OAuth2Authentication auth) { public OAuth2AccessTokenEntity getByAuthentication(OAuth2Authentication auth) {
TypedQuery<OAuth2AccessTokenEntity> queryA = manager.createNamedQuery("OAuth2AccessTokenEntity.getByAuthentication", OAuth2AccessTokenEntity.class); TypedQuery<OAuth2AccessTokenEntity> queryA = manager.createNamedQuery("OAuth2AccessTokenEntity.getByAuthentication", OAuth2AccessTokenEntity.class);
queryA.setParameter("authentication", auth); queryA.setParameter("authentication", auth);
List<OAuth2AccessTokenEntity> accessTokens = queryA.getResultList(); List<OAuth2AccessTokenEntity> accessTokens = queryA.getResultList();
return JpaUtil.getSingleResult(accessTokens); return JpaUtil.getSingleResult(accessTokens);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.repository.OAuth2TokenRepository#getAccessTokenForIdToken(org.mitre.oauth2.model.OAuth2AccessTokenEntity) * @see org.mitre.oauth2.repository.OAuth2TokenRepository#getAccessTokenForIdToken(org.mitre.oauth2.model.OAuth2AccessTokenEntity)
*/ */
@Override @Override
public OAuth2AccessTokenEntity getAccessTokenForIdToken(OAuth2AccessTokenEntity idToken) { public OAuth2AccessTokenEntity getAccessTokenForIdToken(OAuth2AccessTokenEntity idToken) {
TypedQuery<OAuth2AccessTokenEntity> queryA = manager.createNamedQuery("OAuth2AccessTokenEntity.getByIdToken", OAuth2AccessTokenEntity.class); TypedQuery<OAuth2AccessTokenEntity> queryA = manager.createNamedQuery("OAuth2AccessTokenEntity.getByIdToken", OAuth2AccessTokenEntity.class);
queryA.setParameter("idToken", idToken); queryA.setParameter("idToken", idToken);
List<OAuth2AccessTokenEntity> accessTokens = queryA.getResultList(); List<OAuth2AccessTokenEntity> accessTokens = queryA.getResultList();
return JpaUtil.getSingleResult(accessTokens); return JpaUtil.getSingleResult(accessTokens);
} }
} }

View File

@ -3,6 +3,9 @@
*/ */
package org.mitre.oauth2.repository.impl; package org.mitre.oauth2.repository.impl;
import static org.mitre.util.jpa.JpaUtil.getSingleResult;
import static org.mitre.util.jpa.JpaUtil.saveOrUpdate;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
@ -15,9 +18,6 @@ import org.mitre.oauth2.repository.SystemScopeRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import static org.mitre.util.jpa.JpaUtil.getSingleResult;
import static org.mitre.util.jpa.JpaUtil.saveOrUpdate;
/** /**
* @author jricher * @author jricher
* *

View File

@ -76,31 +76,32 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt
if (blacklistedSiteService.isBlacklisted(uri)) { if (blacklistedSiteService.isBlacklisted(uri)) {
throw new IllegalArgumentException("Client URI is blacklisted: " + uri); throw new IllegalArgumentException("Client URI is blacklisted: " + uri);
} }
} }
} }
// assign a random clientid if it's empty // assign a random clientid if it's empty
// NOTE: don't assign a random client secret without asking, since public clients have no secret // NOTE: don't assign a random client secret without asking, since public clients have no secret
if (Strings.isNullOrEmpty(client.getClientId())) { if (Strings.isNullOrEmpty(client.getClientId())) {
client = generateClientId(client); client = generateClientId(client);
} }
// if the client is flagged to allow for refresh tokens, make sure it's got the right granted scopes // if the client is flagged to allow for refresh tokens, make sure it's got the right granted scopes
if (client.isAllowRefresh()) { if (client.isAllowRefresh()) {
client.getScope().add("offline_access"); client.getScope().add("offline_access");
} else { } else {
client.getScope().remove("offline_access"); client.getScope().remove("offline_access");
} }
// timestamp this to right now // timestamp this to right now
client.setCreatedAt(new Date()); client.setCreatedAt(new Date());
return clientRepository.saveClient(client); return clientRepository.saveClient(client);
} }
/** /**
* Get the client by its internal ID * Get the client by its internal ID
*/ */
@Override
public ClientDetailsEntity getClientById(Long id) { public ClientDetailsEntity getClientById(Long id) {
ClientDetailsEntity client = clientRepository.getById(id); ClientDetailsEntity client = clientRepository.getById(id);
@ -129,7 +130,7 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt
* Delete a client and all its associated tokens * Delete a client and all its associated tokens
*/ */
@Override @Override
public void deleteClient(ClientDetailsEntity client) throws InvalidClientException { public void deleteClient(ClientDetailsEntity client) throws InvalidClientException {
if (clientRepository.getById(client.getId()) == null) { if (clientRepository.getById(client.getId()) == null) {
throw new InvalidClientException("Client with id " + client.getClientId() + " was not found"); throw new InvalidClientException("Client with id " + client.getClientId() + " was not found");
@ -144,7 +145,7 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt
// clear out any whitelisted sites for this client // clear out any whitelisted sites for this client
WhitelistedSite whitelistedSite = whitelistedSiteService.getByClientId(client.getClientId()); WhitelistedSite whitelistedSite = whitelistedSiteService.getByClientId(client.getClientId());
if (whitelistedSite != null) { if (whitelistedSite != null) {
whitelistedSiteService.remove(whitelistedSite); whitelistedSiteService.remove(whitelistedSite);
} }
// take care of the client itself // take care of the client itself
@ -157,51 +158,51 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt
* id from oldClient is retained. * id from oldClient is retained.
*/ */
@Override @Override
public ClientDetailsEntity updateClient(ClientDetailsEntity oldClient, ClientDetailsEntity newClient) throws IllegalArgumentException { public ClientDetailsEntity updateClient(ClientDetailsEntity oldClient, ClientDetailsEntity newClient) throws IllegalArgumentException {
if (oldClient != null && newClient != null) { if (oldClient != null && newClient != null) {
for (String uri : newClient.getRegisteredRedirectUri()) { for (String uri : newClient.getRegisteredRedirectUri()) {
if (blacklistedSiteService.isBlacklisted(uri)) { if (blacklistedSiteService.isBlacklisted(uri)) {
throw new IllegalArgumentException("Client URI is blacklisted: " + uri); throw new IllegalArgumentException("Client URI is blacklisted: " + uri);
} }
} }
// if the client is flagged to allow for refresh tokens, make sure it's got the right scope // if the client is flagged to allow for refresh tokens, make sure it's got the right scope
if (newClient.isAllowRefresh()) { if (newClient.isAllowRefresh()) {
newClient.getScope().add("offline_access"); newClient.getScope().add("offline_access");
} else { } else {
newClient.getScope().remove("offline_access"); newClient.getScope().remove("offline_access");
} }
return clientRepository.updateClient(oldClient.getId(), newClient); return clientRepository.updateClient(oldClient.getId(), newClient);
} }
throw new IllegalArgumentException("Neither old client or new client can be null!"); throw new IllegalArgumentException("Neither old client or new client can be null!");
} }
/** /**
* Get all clients in the system * Get all clients in the system
*/ */
@Override @Override
public Collection<ClientDetailsEntity> getAllClients() { public Collection<ClientDetailsEntity> getAllClients() {
return clientRepository.getAllClients(); return clientRepository.getAllClients();
} }
/** /**
* Generates a clientId for the given client and sets it to the client's clientId field. Returns the client that was passed in, now with id set. * Generates a clientId for the given client and sets it to the client's clientId field. Returns the client that was passed in, now with id set.
*/ */
@Override @Override
public ClientDetailsEntity generateClientId(ClientDetailsEntity client) { public ClientDetailsEntity generateClientId(ClientDetailsEntity client) {
client.setClientId(UUID.randomUUID().toString()); client.setClientId(UUID.randomUUID().toString());
return client; return client;
} }
/** /**
* Generates a new clientSecret for the given client and sets it to the client's clientSecret field. Returns the client that was passed in, now with secret set. * Generates a new clientSecret for the given client and sets it to the client's clientSecret field. Returns the client that was passed in, now with secret set.
*/ */
@Override @Override
public ClientDetailsEntity generateClientSecret(ClientDetailsEntity client) { public ClientDetailsEntity generateClientSecret(ClientDetailsEntity client) {
client.setClientSecret(Base64.encodeBase64URLSafeString(new BigInteger(512, new SecureRandom()).toByteArray()).replace("=", "")); client.setClientSecret(Base64.encodeBase64URLSafeString(new BigInteger(512, new SecureRandom()).toByteArray()).replace("=", ""));
return client; return client;
} }
} }

View File

@ -78,7 +78,7 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
private ApprovedSiteService approvedSiteService; private ApprovedSiteService approvedSiteService;
@Override @Override
public OAuth2AccessTokenEntity createAccessToken(OAuth2Authentication authentication) throws AuthenticationException, InvalidClientException { public OAuth2AccessTokenEntity createAccessToken(OAuth2Authentication authentication) throws AuthenticationException, InvalidClientException {
if (authentication != null && authentication.getOAuth2Request() != null) { if (authentication != null && authentication.getOAuth2Request() != null) {
// look up our client // look up our client
OAuth2Request clientAuth = authentication.getOAuth2Request(); OAuth2Request clientAuth = authentication.getOAuth2Request();
@ -91,70 +91,70 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();//accessTokenFactory.createNewAccessToken(); OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();//accessTokenFactory.createNewAccessToken();
// attach the client // attach the client
token.setClient(client); token.setClient(client);
// inherit the scope from the auth, but make a new set so it is // inherit the scope from the auth, but make a new set so it is
//not unmodifiable. Unmodifiables don't play nicely with Eclipselink, which //not unmodifiable. Unmodifiables don't play nicely with Eclipselink, which
//wants to use the clone operation. //wants to use the clone operation.
Set<String> scopes = Sets.newHashSet(clientAuth.getScope()); Set<String> scopes = Sets.newHashSet(clientAuth.getScope());
token.setScope(scopes); token.setScope(scopes);
// make it expire if necessary // make it expire if necessary
if (client.getAccessTokenValiditySeconds() != null && client.getAccessTokenValiditySeconds() > 0) { if (client.getAccessTokenValiditySeconds() != null && client.getAccessTokenValiditySeconds() > 0) {
Date expiration = new Date(System.currentTimeMillis() + (client.getAccessTokenValiditySeconds() * 1000L)); Date expiration = new Date(System.currentTimeMillis() + (client.getAccessTokenValiditySeconds() * 1000L));
token.setExpiration(expiration); token.setExpiration(expiration);
} }
// attach the authorization so that we can look it up later // attach the authorization so that we can look it up later
AuthenticationHolderEntity authHolder = new AuthenticationHolderEntity(); AuthenticationHolderEntity authHolder = new AuthenticationHolderEntity();
authHolder.setAuthentication(authentication); authHolder.setAuthentication(authentication);
authHolder = authenticationHolderRepository.save(authHolder); authHolder = authenticationHolderRepository.save(authHolder);
token.setAuthenticationHolder(authHolder); token.setAuthenticationHolder(authHolder);
// attach a refresh token, if this client is allowed to request them and the user gets the offline scope // attach a refresh token, if this client is allowed to request them and the user gets the offline scope
// TODO: tie this to some kind of scope service // TODO: tie this to some kind of scope service
if (client.isAllowRefresh() && scopes.contains("offline_access")) { if (client.isAllowRefresh() && scopes.contains("offline_access")) {
OAuth2RefreshTokenEntity refreshToken = new OAuth2RefreshTokenEntity(); //refreshTokenFactory.createNewRefreshToken(); OAuth2RefreshTokenEntity refreshToken = new OAuth2RefreshTokenEntity(); //refreshTokenFactory.createNewRefreshToken();
JWTClaimsSet refreshClaims = new JWTClaimsSet(); JWTClaimsSet refreshClaims = new JWTClaimsSet();
// make it expire if necessary // make it expire if necessary
if (client.getRefreshTokenValiditySeconds() != null) { if (client.getRefreshTokenValiditySeconds() != null) {
Date expiration = new Date(System.currentTimeMillis() + (client.getRefreshTokenValiditySeconds() * 1000L)); Date expiration = new Date(System.currentTimeMillis() + (client.getRefreshTokenValiditySeconds() * 1000L));
refreshToken.setExpiration(expiration); refreshToken.setExpiration(expiration);
refreshClaims.setExpirationTime(expiration); refreshClaims.setExpirationTime(expiration);
} }
// set a random identifier // set a random identifier
refreshClaims.setJWTID(UUID.randomUUID().toString()); refreshClaims.setJWTID(UUID.randomUUID().toString());
// TODO: add issuer fields, signature to JWT // TODO: add issuer fields, signature to JWT
PlainJWT refreshJwt = new PlainJWT(refreshClaims); PlainJWT refreshJwt = new PlainJWT(refreshClaims);
refreshToken.setJwt(refreshJwt); refreshToken.setJwt(refreshJwt);
//Add the authentication //Add the authentication
refreshToken.setAuthenticationHolder(authHolder); refreshToken.setAuthenticationHolder(authHolder);
refreshToken.setClient(client); refreshToken.setClient(client);
// save the token first so that we can set it to a member of the access token (NOTE: is this step necessary?) // save the token first so that we can set it to a member of the access token (NOTE: is this step necessary?)
tokenRepository.saveRefreshToken(refreshToken); tokenRepository.saveRefreshToken(refreshToken);
token.setRefreshToken(refreshToken); token.setRefreshToken(refreshToken);
} }
tokenEnhancer.enhance(token, authentication); tokenEnhancer.enhance(token, authentication);
tokenRepository.saveAccessToken(token); tokenRepository.saveAccessToken(token);
//Add approved site reference, if any //Add approved site reference, if any
OAuth2Request originalAuthRequest = authHolder.getAuthentication().getOAuth2Request(); OAuth2Request originalAuthRequest = authHolder.getAuthentication().getOAuth2Request();
if (originalAuthRequest.getExtensions() != null && originalAuthRequest.getExtensions().containsKey("approved_site")) { if (originalAuthRequest.getExtensions() != null && originalAuthRequest.getExtensions().containsKey("approved_site")) {
Long apId = (Long) originalAuthRequest.getExtensions().get("approved_site"); Long apId = (Long) originalAuthRequest.getExtensions().get("approved_site");
ApprovedSite ap = approvedSiteService.getById(apId); ApprovedSite ap = approvedSiteService.getById(apId);
@ -165,18 +165,18 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
} }
if (token.getRefreshToken() != null) { if (token.getRefreshToken() != null) {
tokenRepository.saveRefreshToken(token.getRefreshToken()); // make sure we save any changes that might have been enhanced tokenRepository.saveRefreshToken(token.getRefreshToken()); // make sure we save any changes that might have been enhanced
} }
return token; return token;
} }
throw new AuthenticationCredentialsNotFoundException("No authentication credentials found"); throw new AuthenticationCredentialsNotFoundException("No authentication credentials found");
} }
@Override @Override
public OAuth2AccessTokenEntity refreshAccessToken(String refreshTokenValue, TokenRequest authRequest) throws AuthenticationException { public OAuth2AccessTokenEntity refreshAccessToken(String refreshTokenValue, TokenRequest authRequest) throws AuthenticationException {
OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenByValue(refreshTokenValue); OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenByValue(refreshTokenValue);
@ -226,27 +226,27 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
token.setScope(refreshScopes); token.setScope(refreshScopes);
} }
token.setClient(client); token.setClient(client);
if (client.getAccessTokenValiditySeconds() != null) { if (client.getAccessTokenValiditySeconds() != null) {
Date expiration = new Date(System.currentTimeMillis() + (client.getAccessTokenValiditySeconds() * 1000L)); Date expiration = new Date(System.currentTimeMillis() + (client.getAccessTokenValiditySeconds() * 1000L));
token.setExpiration(expiration); token.setExpiration(expiration);
} }
token.setRefreshToken(refreshToken); token.setRefreshToken(refreshToken);
token.setAuthenticationHolder(authHolder); token.setAuthenticationHolder(authHolder);
tokenEnhancer.enhance(token, authHolder.getAuthentication()); tokenEnhancer.enhance(token, authHolder.getAuthentication());
tokenRepository.saveAccessToken(token); tokenRepository.saveAccessToken(token);
return token; return token;
} }
@Override @Override
public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException { public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException {
OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenByValue(accessTokenValue); OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenByValue(accessTokenValue);
@ -260,15 +260,15 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
throw new InvalidTokenException("Expired access token: " + accessTokenValue); throw new InvalidTokenException("Expired access token: " + accessTokenValue);
} }
return accessToken.getAuthenticationHolder().getAuthentication(); return accessToken.getAuthenticationHolder().getAuthentication();
} }
/** /**
* Get an access token from its token value. * Get an access token from its token value.
*/ */
@Override @Override
public OAuth2AccessTokenEntity readAccessToken(String accessTokenValue) throws AuthenticationException { public OAuth2AccessTokenEntity readAccessToken(String accessTokenValue) throws AuthenticationException {
OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenByValue(accessTokenValue); OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenByValue(accessTokenValue);
if (accessToken == null) { if (accessToken == null) {
throw new InvalidTokenException("Access token for value " + accessTokenValue + " was not found"); throw new InvalidTokenException("Access token for value " + accessTokenValue + " was not found");
@ -276,7 +276,7 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
else { else {
return accessToken; return accessToken;
} }
} }
/** /**
* Get an access token by its authentication object. * Get an access token by its authentication object.
@ -293,7 +293,7 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
* Get a refresh token by its token value. * Get a refresh token by its token value.
*/ */
@Override @Override
public OAuth2RefreshTokenEntity getRefreshToken(String refreshTokenValue) throws AuthenticationException { public OAuth2RefreshTokenEntity getRefreshToken(String refreshTokenValue) throws AuthenticationException {
OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenByValue(refreshTokenValue); OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenByValue(refreshTokenValue);
if (refreshToken == null) { if (refreshToken == null) {
throw new InvalidTokenException("Refresh token for value " + refreshTokenValue + " was not found"); throw new InvalidTokenException("Refresh token for value " + refreshTokenValue + " was not found");
@ -301,61 +301,61 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
else { else {
return refreshToken; return refreshToken;
} }
} }
/** /**
* Revoke a refresh token and all access tokens issued to it. * Revoke a refresh token and all access tokens issued to it.
*/ */
@Override @Override
public void revokeRefreshToken(OAuth2RefreshTokenEntity refreshToken) { public void revokeRefreshToken(OAuth2RefreshTokenEntity refreshToken) {
tokenRepository.clearAccessTokensForRefreshToken(refreshToken); tokenRepository.clearAccessTokensForRefreshToken(refreshToken);
tokenRepository.removeRefreshToken(refreshToken); tokenRepository.removeRefreshToken(refreshToken);
} }
/** /**
* Revoke an access token. * Revoke an access token.
*/ */
@Override @Override
public void revokeAccessToken(OAuth2AccessTokenEntity accessToken) { public void revokeAccessToken(OAuth2AccessTokenEntity accessToken) {
tokenRepository.removeAccessToken(accessToken); tokenRepository.removeAccessToken(accessToken);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.service.OAuth2TokenEntityService#getAccessTokensForClient(org.mitre.oauth2.model.ClientDetailsEntity) * @see org.mitre.oauth2.service.OAuth2TokenEntityService#getAccessTokensForClient(org.mitre.oauth2.model.ClientDetailsEntity)
*/ */
@Override @Override
public List<OAuth2AccessTokenEntity> getAccessTokensForClient(ClientDetailsEntity client) { public List<OAuth2AccessTokenEntity> getAccessTokensForClient(ClientDetailsEntity client) {
return tokenRepository.getAccessTokensForClient(client); return tokenRepository.getAccessTokensForClient(client);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.service.OAuth2TokenEntityService#getRefreshTokensForClient(org.mitre.oauth2.model.ClientDetailsEntity) * @see org.mitre.oauth2.service.OAuth2TokenEntityService#getRefreshTokensForClient(org.mitre.oauth2.model.ClientDetailsEntity)
*/ */
@Override @Override
public List<OAuth2RefreshTokenEntity> getRefreshTokensForClient(ClientDetailsEntity client) { public List<OAuth2RefreshTokenEntity> getRefreshTokensForClient(ClientDetailsEntity client) {
return tokenRepository.getRefreshTokensForClient(client); return tokenRepository.getRefreshTokensForClient(client);
} }
@Override @Override
@Scheduled(fixedRate = 5 * 60 * 1000) // schedule this task every five minutes @Scheduled(fixedRate = 5 * 60 * 1000) // schedule this task every five minutes
public void clearExpiredTokens() { public void clearExpiredTokens() {
logger.info("Cleaning out all expired tokens"); logger.info("Cleaning out all expired tokens");
List<OAuth2AccessTokenEntity> accessTokens = tokenRepository.getExpiredAccessTokens(); List<OAuth2AccessTokenEntity> accessTokens = tokenRepository.getExpiredAccessTokens();
logger.info("Found " + accessTokens.size() + " expired access tokens"); logger.info("Found " + accessTokens.size() + " expired access tokens");
for (OAuth2AccessTokenEntity oAuth2AccessTokenEntity : accessTokens) { for (OAuth2AccessTokenEntity oAuth2AccessTokenEntity : accessTokens) {
revokeAccessToken(oAuth2AccessTokenEntity); revokeAccessToken(oAuth2AccessTokenEntity);
} }
List<OAuth2RefreshTokenEntity> refreshTokens = tokenRepository.getExpiredRefreshTokens(); List<OAuth2RefreshTokenEntity> refreshTokens = tokenRepository.getExpiredRefreshTokens();
logger.info("Found " + refreshTokens.size() + " expired refresh tokens"); logger.info("Found " + refreshTokens.size() + " expired refresh tokens");
for (OAuth2RefreshTokenEntity oAuth2RefreshTokenEntity : refreshTokens) { for (OAuth2RefreshTokenEntity oAuth2RefreshTokenEntity : refreshTokens) {
revokeRefreshToken(oAuth2RefreshTokenEntity); revokeRefreshToken(oAuth2RefreshTokenEntity);
} }
} }
/** /**
* Get a builder object for this class (for tests) * Get a builder object for this class (for tests)
* @return * @return
*/ */
@ -394,20 +394,20 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.service.OAuth2TokenEntityService#saveAccessToken(org.mitre.oauth2.model.OAuth2AccessTokenEntity) * @see org.mitre.oauth2.service.OAuth2TokenEntityService#saveAccessToken(org.mitre.oauth2.model.OAuth2AccessTokenEntity)
*/ */
@Override @Override
public OAuth2AccessTokenEntity saveAccessToken(OAuth2AccessTokenEntity accessToken) { public OAuth2AccessTokenEntity saveAccessToken(OAuth2AccessTokenEntity accessToken) {
return tokenRepository.saveAccessToken(accessToken); return tokenRepository.saveAccessToken(accessToken);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.service.OAuth2TokenEntityService#saveRefreshToken(org.mitre.oauth2.model.OAuth2RefreshTokenEntity) * @see org.mitre.oauth2.service.OAuth2TokenEntityService#saveRefreshToken(org.mitre.oauth2.model.OAuth2RefreshTokenEntity)
*/ */
@Override @Override
public OAuth2RefreshTokenEntity saveRefreshToken(OAuth2RefreshTokenEntity refreshToken) { public OAuth2RefreshTokenEntity saveRefreshToken(OAuth2RefreshTokenEntity refreshToken) {
return tokenRepository.saveRefreshToken(refreshToken); return tokenRepository.saveRefreshToken(refreshToken);
} }
/** /**
* @return the tokenEnhancer * @return the tokenEnhancer
@ -424,12 +424,12 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.service.OAuth2TokenEntityService#getAccessTokenForIdToken(org.mitre.oauth2.model.OAuth2AccessTokenEntity) * @see org.mitre.oauth2.service.OAuth2TokenEntityService#getAccessTokenForIdToken(org.mitre.oauth2.model.OAuth2AccessTokenEntity)
*/ */
@Override @Override
public OAuth2AccessTokenEntity getAccessTokenForIdToken(OAuth2AccessTokenEntity idToken) { public OAuth2AccessTokenEntity getAccessTokenForIdToken(OAuth2AccessTokenEntity idToken) {
return tokenRepository.getAccessTokenForIdToken(idToken); return tokenRepository.getAccessTokenForIdToken(idToken);
} }
@Override @Override
public OAuth2AccessTokenEntity getAccessTokenById(Long id) { public OAuth2AccessTokenEntity getAccessTokenById(Long id) {

View File

@ -32,128 +32,128 @@ public class DefaultSystemScopeService implements SystemScopeService {
private Predicate<SystemScope> isDefault = new Predicate<SystemScope>() { private Predicate<SystemScope> isDefault = new Predicate<SystemScope>() {
@Override @Override
public boolean apply(@Nullable SystemScope input) { public boolean apply(@Nullable SystemScope input) {
return (input != null && input.isDefaultScope()); return (input != null && input.isDefaultScope());
} }
}; };
private Predicate<SystemScope> isDynReg = new Predicate<SystemScope>() { private Predicate<SystemScope> isDynReg = new Predicate<SystemScope>() {
@Override @Override
public boolean apply(@Nullable SystemScope input) { public boolean apply(@Nullable SystemScope input) {
return (input != null && input.isAllowDynReg()); return (input != null && input.isAllowDynReg());
} }
}; };
private Function<String, SystemScope> stringToSystemScope = new Function<String, SystemScope>() { private Function<String, SystemScope> stringToSystemScope = new Function<String, SystemScope>() {
@Override @Override
public SystemScope apply(@Nullable String input) { public SystemScope apply(@Nullable String input) {
if (input == null) { if (input == null) {
return null; return null;
} else { } else {
SystemScope s = getByValue(input); SystemScope s = getByValue(input);
if (s != null) { if (s != null) {
// get the real scope if it's available // get the real scope if it's available
return s; return s;
} else { } else {
// make a fake one otherwise // make a fake one otherwise
return new SystemScope(input); return new SystemScope(input);
} }
} }
} }
}; };
private Function<SystemScope, String> systemScopeToString = new Function<SystemScope, String>() { private Function<SystemScope, String> systemScopeToString = new Function<SystemScope, String>() {
@Override @Override
public String apply(@Nullable SystemScope input) { public String apply(@Nullable SystemScope input) {
if (input == null) { if (input == null) {
return null; return null;
} else { } else {
return input.getValue(); return input.getValue();
} }
} }
}; };
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.service.SystemScopeService#getAll() * @see org.mitre.oauth2.service.SystemScopeService#getAll()
*/ */
@Override @Override
public Set<SystemScope> getAll() { public Set<SystemScope> getAll() {
return repository.getAll(); return repository.getAll();
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.service.SystemScopeService#getDefaults() * @see org.mitre.oauth2.service.SystemScopeService#getDefaults()
*/ */
@Override @Override
public Set<SystemScope> getDefaults() { public Set<SystemScope> getDefaults() {
return Sets.filter(getAll(), isDefault); return Sets.filter(getAll(), isDefault);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.service.SystemScopeService#getDynReg() * @see org.mitre.oauth2.service.SystemScopeService#getDynReg()
*/ */
@Override @Override
public Set<SystemScope> getDynReg() { public Set<SystemScope> getDynReg() {
return Sets.filter(getAll(), isDynReg); return Sets.filter(getAll(), isDynReg);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.service.SystemScopeService#getById(java.lang.Long) * @see org.mitre.oauth2.service.SystemScopeService#getById(java.lang.Long)
*/ */
@Override @Override
public SystemScope getById(Long id) { public SystemScope getById(Long id) {
return repository.getById(id); return repository.getById(id);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.service.SystemScopeService#getByValue(java.lang.String) * @see org.mitre.oauth2.service.SystemScopeService#getByValue(java.lang.String)
*/ */
@Override @Override
public SystemScope getByValue(String value) { public SystemScope getByValue(String value) {
return repository.getByValue(value); return repository.getByValue(value);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.service.SystemScopeService#remove(org.mitre.oauth2.model.SystemScope) * @see org.mitre.oauth2.service.SystemScopeService#remove(org.mitre.oauth2.model.SystemScope)
*/ */
@Override @Override
public void remove(SystemScope scope) { public void remove(SystemScope scope) {
repository.remove(scope); repository.remove(scope);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.service.SystemScopeService#save(org.mitre.oauth2.model.SystemScope) * @see org.mitre.oauth2.service.SystemScopeService#save(org.mitre.oauth2.model.SystemScope)
*/ */
@Override @Override
public SystemScope save(SystemScope scope) { public SystemScope save(SystemScope scope) {
return repository.save(scope); return repository.save(scope);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.service.SystemScopeService#fromStrings(java.util.Set) * @see org.mitre.oauth2.service.SystemScopeService#fromStrings(java.util.Set)
*/ */
@Override @Override
public Set<SystemScope> fromStrings(Set<String> scope) { public Set<SystemScope> fromStrings(Set<String> scope) {
if (scope == null) { if (scope == null) {
return null; return null;
} else { } else {
return new LinkedHashSet<SystemScope>(Collections2.filter(Collections2.transform(scope, stringToSystemScope), Predicates.notNull())); return new LinkedHashSet<SystemScope>(Collections2.filter(Collections2.transform(scope, stringToSystemScope), Predicates.notNull()));
} }
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.oauth2.service.SystemScopeService#toStrings(java.util.Set) * @see org.mitre.oauth2.service.SystemScopeService#toStrings(java.util.Set)
*/ */
@Override @Override
public Set<String> toStrings(Set<SystemScope> scope) { public Set<String> toStrings(Set<SystemScope> scope) {
if (scope == null) { if (scope == null) {
return null; return null;
} else { } else {
return new LinkedHashSet<String>(Collections2.filter(Collections2.transform(scope, systemScopeToString), Predicates.notNull())); return new LinkedHashSet<String>(Collections2.filter(Collections2.transform(scope, systemScopeToString), Predicates.notNull()));
} }
} }

View File

@ -48,50 +48,50 @@ public class ChainedTokenGranter extends AbstractTokenGranter {
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.security.oauth2.provider.token.AbstractTokenGranter#getOAuth2Authentication(org.springframework.security.oauth2.provider.AuthorizationRequest) * @see org.springframework.security.oauth2.provider.token.AbstractTokenGranter#getOAuth2Authentication(org.springframework.security.oauth2.provider.AuthorizationRequest)
*/ */
@Override @Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) throws AuthenticationException, InvalidTokenException { protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) throws AuthenticationException, InvalidTokenException {
// read and load up the existing token // read and load up the existing token
String incomingTokenValue = tokenRequest.getRequestParameters().get("token"); String incomingTokenValue = tokenRequest.getRequestParameters().get("token");
OAuth2AccessTokenEntity incomingToken = tokenServices.readAccessToken(incomingTokenValue); OAuth2AccessTokenEntity incomingToken = tokenServices.readAccessToken(incomingTokenValue);
// check for scoping in the request, can't up-scope with a chained request // check for scoping in the request, can't up-scope with a chained request
Set<String> approvedScopes = incomingToken.getScope(); Set<String> approvedScopes = incomingToken.getScope();
Set<String> requestedScopes = tokenRequest.getScope(); Set<String> requestedScopes = tokenRequest.getScope();
if (requestedScopes == null) { if (requestedScopes == null) {
requestedScopes = new HashSet<String>(); requestedScopes = new HashSet<String>();
} }
// do a check on the requested scopes -- if they exactly match the client scopes, they were probably shadowed by the token granter // do a check on the requested scopes -- if they exactly match the client scopes, they were probably shadowed by the token granter
if (client.getScope().equals(requestedScopes)) { if (client.getScope().equals(requestedScopes)) {
requestedScopes = new HashSet<String>(); requestedScopes = new HashSet<String>();
} }
// if our scopes are a valid subset of what's allowed, we can continue // if our scopes are a valid subset of what's allowed, we can continue
if (approvedScopes.containsAll(requestedScopes)) { if (approvedScopes.containsAll(requestedScopes)) {
if (requestedScopes.isEmpty()) { if (requestedScopes.isEmpty()) {
// if there are no scopes, inherit the original scopes from the token // if there are no scopes, inherit the original scopes from the token
tokenRequest.setScope(approvedScopes); tokenRequest.setScope(approvedScopes);
} else { } else {
// if scopes were asked for, give only the subset of scopes requested // if scopes were asked for, give only the subset of scopes requested
// this allows safe downscoping // this allows safe downscoping
tokenRequest.setScope(Sets.intersection(requestedScopes, approvedScopes)); tokenRequest.setScope(Sets.intersection(requestedScopes, approvedScopes));
} }
// NOTE: don't revoke the existing access token // NOTE: don't revoke the existing access token
// create a new access token // create a new access token
OAuth2Authentication authentication = new OAuth2Authentication(getRequestFactory().createOAuth2Request(client, tokenRequest), incomingToken.getAuthenticationHolder().getAuthentication().getUserAuthentication()); OAuth2Authentication authentication = new OAuth2Authentication(getRequestFactory().createOAuth2Request(client, tokenRequest), incomingToken.getAuthenticationHolder().getAuthentication().getUserAuthentication());
return authentication; return authentication;
} else { } else {
throw new InvalidScopeException("Invalid scope requested in chained request", approvedScopes); throw new InvalidScopeException("Invalid scope requested in chained request", approvedScopes);
} }
} }
} }

View File

@ -49,63 +49,63 @@ public class JwtAssertionTokenGranter extends AbstractTokenGranter {
@Autowired @Autowired
public JwtAssertionTokenGranter(OAuth2TokenEntityService tokenServices, ClientDetailsEntityService clientDetailsService, OAuth2RequestFactory requestFactory) { public JwtAssertionTokenGranter(OAuth2TokenEntityService tokenServices, ClientDetailsEntityService clientDetailsService, OAuth2RequestFactory requestFactory) {
super(tokenServices, clientDetailsService, requestFactory, grantType); super(tokenServices, clientDetailsService, requestFactory, grantType);
this.tokenServices = tokenServices; this.tokenServices = tokenServices;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.security.oauth2.provider.token.AbstractTokenGranter#getOAuth2Authentication(org.springframework.security.oauth2.provider.AuthorizationRequest) * @see org.springframework.security.oauth2.provider.token.AbstractTokenGranter#getOAuth2Authentication(org.springframework.security.oauth2.provider.AuthorizationRequest)
*/ */
@Override @Override
protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) throws AuthenticationException, InvalidTokenException { protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) throws AuthenticationException, InvalidTokenException {
// read and load up the existing token // read and load up the existing token
String incomingTokenValue = tokenRequest.getRequestParameters().get("assertion"); String incomingTokenValue = tokenRequest.getRequestParameters().get("assertion");
OAuth2AccessTokenEntity incomingToken = tokenServices.readAccessToken(incomingTokenValue); OAuth2AccessTokenEntity incomingToken = tokenServices.readAccessToken(incomingTokenValue);
if (incomingToken.getScope().contains(OAuth2AccessTokenEntity.ID_TOKEN_SCOPE)) { if (incomingToken.getScope().contains(OAuth2AccessTokenEntity.ID_TOKEN_SCOPE)) {
if (!client.getClientId().equals(tokenRequest.getClientId())) { if (!client.getClientId().equals(tokenRequest.getClientId())) {
throw new InvalidClientException("Not the right client for this token"); throw new InvalidClientException("Not the right client for this token");
} }
// it's an ID token, process it accordingly // it's an ID token, process it accordingly
try { try {
// TODO: make this use a more specific idtoken class // TODO: make this use a more specific idtoken class
JWT idToken = JWTParser.parse(incomingTokenValue); JWT idToken = JWTParser.parse(incomingTokenValue);
OAuth2AccessTokenEntity accessToken = tokenServices.getAccessTokenForIdToken(incomingToken); OAuth2AccessTokenEntity accessToken = tokenServices.getAccessTokenForIdToken(incomingToken);
if (accessToken != null) { if (accessToken != null) {
//OAuth2AccessTokenEntity newIdToken = tokenServices.get //OAuth2AccessTokenEntity newIdToken = tokenServices.get
OAuth2AccessTokenEntity newIdTokenEntity = new OAuth2AccessTokenEntity(); OAuth2AccessTokenEntity newIdTokenEntity = new OAuth2AccessTokenEntity();
// copy over all existing claims // copy over all existing claims
JWTClaimsSet claims = new JWTClaimsSet(idToken.getJWTClaimsSet()); JWTClaimsSet claims = new JWTClaimsSet(idToken.getJWTClaimsSet());
if (client instanceof ClientDetailsEntity) { if (client instanceof ClientDetailsEntity) {
ClientDetailsEntity clientEntity = (ClientDetailsEntity) client; ClientDetailsEntity clientEntity = (ClientDetailsEntity) client;
// update expiration and issued-at claims // update expiration and issued-at claims
if (clientEntity.getIdTokenValiditySeconds() != null) { if (clientEntity.getIdTokenValiditySeconds() != null) {
Date expiration = new Date(System.currentTimeMillis() + (clientEntity.getIdTokenValiditySeconds() * 1000L)); Date expiration = new Date(System.currentTimeMillis() + (clientEntity.getIdTokenValiditySeconds() * 1000L));
claims.setExpirationTime(expiration); claims.setExpirationTime(expiration);
newIdTokenEntity.setExpiration(expiration); newIdTokenEntity.setExpiration(expiration);
} }
} else { } else {
//TODO: What should happen in this case? Is this possible? //TODO: What should happen in this case? Is this possible?
} }
claims.setIssueTime(new Date()); claims.setIssueTime(new Date());
SignedJWT newIdToken = new SignedJWT((JWSHeader) idToken.getHeader(), claims); SignedJWT newIdToken = new SignedJWT((JWSHeader) idToken.getHeader(), claims);
jwtService.signJwt(newIdToken); jwtService.signJwt(newIdToken);
newIdTokenEntity.setJwt(newIdToken); newIdTokenEntity.setJwt(newIdToken);
newIdTokenEntity.setAuthenticationHolder(incomingToken.getAuthenticationHolder()); newIdTokenEntity.setAuthenticationHolder(incomingToken.getAuthenticationHolder());
@ -123,20 +123,20 @@ public class JwtAssertionTokenGranter extends AbstractTokenGranter {
return newIdTokenEntity; return newIdTokenEntity;
} }
} catch (ParseException e) { } catch (ParseException e) {
logger.warn("Couldn't parse id token", e); logger.warn("Couldn't parse id token", e);
} }
} }
// if we got down here, we didn't actually create any tokens, so return null // if we got down here, we didn't actually create any tokens, so return null
return null; return null;
/* /*
* Otherwise, process it like an access token assertion ... which we don't support yet so this is all commented out * Otherwise, process it like an access token assertion ... which we don't support yet so this is all commented out
* / * /
if (jwtService.validateSignature(incomingTokenValue)) { if (jwtService.validateSignature(incomingTokenValue)) {
Jwt jwt = Jwt.parse(incomingTokenValue); Jwt jwt = Jwt.parse(incomingTokenValue);
@ -175,9 +175,9 @@ public class JwtAssertionTokenGranter extends AbstractTokenGranter {
} else { } else {
return null; // throw error?? return null; // throw error??
} }
*/ */
} }

View File

@ -47,7 +47,7 @@ public class TokenIntrospectionView extends AbstractView {
private static Logger logger = LoggerFactory.getLogger(TokenIntrospectionView.class); private static Logger logger = LoggerFactory.getLogger(TokenIntrospectionView.class);
@Override @Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) { protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
@ -68,7 +68,7 @@ public class TokenIntrospectionView extends AbstractView {
// serialize other classes without filter (lists and sets and things) // serialize other classes without filter (lists and sets and things)
return false; return false;
} }
*/ */
return false; return false;
} }
@ -84,27 +84,28 @@ public class TokenIntrospectionView extends AbstractView {
}) })
.registerTypeAdapter(OAuth2AccessTokenEntity.class, new JsonSerializer<OAuth2AccessTokenEntity>() { .registerTypeAdapter(OAuth2AccessTokenEntity.class, new JsonSerializer<OAuth2AccessTokenEntity>() {
public JsonElement serialize(OAuth2AccessTokenEntity src, Type typeOfSrc, JsonSerializationContext context) { @Override
JsonObject token = new JsonObject(); public JsonElement serialize(OAuth2AccessTokenEntity src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject token = new JsonObject();
token.addProperty("valid", true); token.addProperty("valid", true);
JsonArray scopes = new JsonArray(); JsonArray scopes = new JsonArray();
for (String scope : src.getScope()) { for (String scope : src.getScope()) {
scopes.add(new JsonPrimitive(scope)); scopes.add(new JsonPrimitive(scope));
} }
token.add("scope", scopes); token.add("scope", scopes);
token.add("expires_at", context.serialize(src.getExpiration())); token.add("expires_at", context.serialize(src.getExpiration()));
//token.addProperty("audience", src.getAuthenticationHolder().getAuthentication().getAuthorizationRequest().getClientId()); //token.addProperty("audience", src.getAuthenticationHolder().getAuthentication().getAuthorizationRequest().getClientId());
token.addProperty("subject", src.getAuthenticationHolder().getAuthentication().getName()); token.addProperty("subject", src.getAuthenticationHolder().getAuthentication().getName());
token.addProperty("client_id", src.getAuthenticationHolder().getAuthentication().getOAuth2Request().getClientId()); token.addProperty("client_id", src.getAuthenticationHolder().getAuthentication().getOAuth2Request().getClientId());
return token; return token;
} }
}) })
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
@ -130,6 +131,6 @@ public class TokenIntrospectionView extends AbstractView {
} }
} }
} }

View File

@ -97,48 +97,48 @@ public class OAuthConfirmationController {
String redirect_uri = clientAuth.getRequestParameters().get("redirect_uri"); String redirect_uri = clientAuth.getRequestParameters().get("redirect_uri");
model.put("redirect_uri", redirect_uri); model.put("redirect_uri", redirect_uri);
/* /*
Map<String, Boolean> scopes = new HashMap<String, Boolean>(); Map<String, Boolean> scopes = new HashMap<String, Boolean>();
for (String scope : clientAuth.getScope()) { for (String scope : clientAuth.getScope()) {
scopes.put(scope, Boolean.TRUE); scopes.put(scope, Boolean.TRUE);
} }
*/ */
Set<SystemScope> scopes = scopeService.fromStrings(clientAuth.getScope()); Set<SystemScope> scopes = scopeService.fromStrings(clientAuth.getScope());
Set<SystemScope> sortedScopes = new LinkedHashSet<SystemScope>(scopes.size()); Set<SystemScope> sortedScopes = new LinkedHashSet<SystemScope>(scopes.size());
Set<SystemScope> systemScopes = scopeService.getAll(); Set<SystemScope> systemScopes = scopeService.getAll();
// sort scopes for display // sort scopes for display
for (SystemScope s : systemScopes) { for (SystemScope s : systemScopes) {
if (scopes.contains(s)) { if (scopes.contains(s)) {
sortedScopes.add(s); sortedScopes.add(s);
} }
} }
sortedScopes.addAll(Sets.difference(scopes, systemScopes)); sortedScopes.addAll(Sets.difference(scopes, systemScopes));
model.put("scopes", sortedScopes); model.put("scopes", sortedScopes);
return new ModelAndView("oauth/approve", model); return new ModelAndView("oauth/approve", model);
} }
/** /**
* @return the clientService * @return the clientService
*/ */
public ClientDetailsEntityService getClientService() { public ClientDetailsEntityService getClientService() {
return clientService; return clientService;
} }
/** /**
* @param clientService the clientService to set * @param clientService the clientService to set
*/ */
public void setClientService(ClientDetailsEntityService clientService) { public void setClientService(ClientDetailsEntityService clientService) {
this.clientService = clientService; this.clientService = clientService;
} }
} }

View File

@ -59,20 +59,20 @@ public class RevocationEndpoint {
OAuth2RefreshTokenEntity refreshToken = null; OAuth2RefreshTokenEntity refreshToken = null;
OAuth2AccessTokenEntity accessToken = null; OAuth2AccessTokenEntity accessToken = null;
try { try {
refreshToken = tokenServices.getRefreshToken(tokenValue); refreshToken = tokenServices.getRefreshToken(tokenValue);
} catch (InvalidTokenException e) { } catch (InvalidTokenException e) {
// it's OK if either of these tokens are bad // it's OK if either of these tokens are bad
//TODO: Error Handling //TODO: Error Handling
} }
try { try {
accessToken = tokenServices.readAccessToken(tokenValue); accessToken = tokenServices.readAccessToken(tokenValue);
} catch (InvalidTokenException e) { } catch (InvalidTokenException e) {
// it's OK if either of these tokens are bad // it's OK if either of these tokens are bad
//TODO: Error Handling //TODO: Error Handling
} catch (AuthenticationException e) { } catch (AuthenticationException e) {
//TODO: Error Handling //TODO: Error Handling
} }
if (refreshToken == null && accessToken == null) { if (refreshToken == null && accessToken == null) {
//TODO: Error Handling //TODO: Error Handling

View File

@ -5,9 +5,6 @@ package org.mitre.oauth2.web;
import java.util.Set; import java.util.Set;
import javax.persistence.EntityExistsException;
import javax.persistence.TransactionRequiredException;
import org.mitre.oauth2.model.SystemScope; import org.mitre.oauth2.model.SystemScope;
import org.mitre.oauth2.service.SystemScopeService; import org.mitre.oauth2.service.SystemScopeService;
import org.slf4j.Logger; import org.slf4j.Logger;

View File

@ -120,21 +120,21 @@ public class ConnectOAuth2RequestFactory extends DefaultOAuth2RequestFactory {
* @param inputParams * @param inputParams
* @return * @return
*/ */
private Map<String, String> processRequestObject(Map<String, String> inputParams) { private Map<String, String> processRequestObject(Map<String, String> inputParams) {
String jwtString = inputParams.get("request"); String jwtString = inputParams.get("request");
// if there's no request object, bail early // if there's no request object, bail early
if (Strings.isNullOrEmpty(jwtString)) { if (Strings.isNullOrEmpty(jwtString)) {
return inputParams; return inputParams;
} }
// start by copying over what's already in there // start by copying over what's already in there
Map<String, String> parameters = new HashMap<String, String>(inputParams); Map<String, String> parameters = new HashMap<String, String>(inputParams);
// parse the request object // parse the request object
try { try {
SignedJWT jwsObject = SignedJWT.parse(jwtString); SignedJWT jwsObject = SignedJWT.parse(jwtString);
JSONObject claims = jwsObject.getPayload().toJSONObject(); JSONObject claims = jwsObject.getPayload().toJSONObject();
// TODO: check parameter consistency, move keys to constants // TODO: check parameter consistency, move keys to constants
@ -219,10 +219,10 @@ public class ConnectOAuth2RequestFactory extends DefaultOAuth2RequestFactory {
} }
} }
} catch (ParseException e) { } catch (ParseException e) {
logger.error("ParseException while parsing RequestObject:", e); logger.error("ParseException while parsing RequestObject:", e);
} }
return parameters; return parameters;
} }
} }

View File

@ -25,11 +25,11 @@ public class JwtBearerAssertionAuthenticationToken extends AbstractAuthenticatio
* @param jwt * @param jwt
*/ */
public JwtBearerAssertionAuthenticationToken(String clientId, JWT jwt) { public JwtBearerAssertionAuthenticationToken(String clientId, JWT jwt) {
super(null); super(null);
this.clientId = clientId; this.clientId = clientId;
this.jwt = jwt; this.jwt = jwt;
setAuthenticated(false); setAuthenticated(false);
} }
/** /**
* Create an authenticated token with the given clientID, jwt, and authorities set * Create an authenticated token with the given clientID, jwt, and authorities set
@ -38,11 +38,11 @@ public class JwtBearerAssertionAuthenticationToken extends AbstractAuthenticatio
* @param authorities * @param authorities
*/ */
public JwtBearerAssertionAuthenticationToken(String clientId, JWT jwt, Collection<? extends GrantedAuthority> authorities) { public JwtBearerAssertionAuthenticationToken(String clientId, JWT jwt, Collection<? extends GrantedAuthority> authorities) {
super(authorities); super(authorities);
this.clientId = clientId; this.clientId = clientId;
this.jwt = jwt; this.jwt = jwt;
setAuthenticated(true); setAuthenticated(true);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.security.core.Authentication#getCredentials() * @see org.springframework.security.core.Authentication#getCredentials()
@ -61,41 +61,41 @@ public class JwtBearerAssertionAuthenticationToken extends AbstractAuthenticatio
} }
/** /**
* @return the clientId * @return the clientId
*/ */
public String getClientId() { public String getClientId() {
return clientId; return clientId;
} }
/** /**
* @param clientId the clientId to set * @param clientId the clientId to set
*/ */
public void setClientId(String clientId) { public void setClientId(String clientId) {
this.clientId = clientId; this.clientId = clientId;
} }
/** /**
* @return the jwt * @return the jwt
*/ */
public JWT getJwt() { public JWT getJwt() {
return jwt; return jwt;
} }
/** /**
* @param jwt the jwt to set * @param jwt the jwt to set
*/ */
public void setJwt(JWT jwt) { public void setJwt(JWT jwt) {
this.jwt = jwt; this.jwt = jwt;
} }
/** /**
* Clear out the JWT that this token holds. * Clear out the JWT that this token holds.
*/ */
@Override @Override
public void eraseCredentials() { public void eraseCredentials() {
super.eraseCredentials(); super.eraseCredentials();
setJwt(null); setJwt(null);
} }

View File

@ -50,27 +50,27 @@ public class JwtBearerAuthenticationProvider implements AuthenticationProvider {
/** /**
* Try to validate the client credentials by parsing and validating the JWT. * Try to validate the client credentials by parsing and validating the JWT.
*/ */
@Override @Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException { public Authentication authenticate(Authentication authentication) throws AuthenticationException {
JwtBearerAssertionAuthenticationToken jwtAuth = (JwtBearerAssertionAuthenticationToken)authentication; JwtBearerAssertionAuthenticationToken jwtAuth = (JwtBearerAssertionAuthenticationToken)authentication;
try { try {
ClientDetailsEntity client = clientService.loadClientByClientId(jwtAuth.getClientId()); ClientDetailsEntity client = clientService.loadClientByClientId(jwtAuth.getClientId());
JWT jwt = jwtAuth.getJwt(); JWT jwt = jwtAuth.getJwt();
ReadOnlyJWTClaimsSet jwtClaims = jwt.getJWTClaimsSet(); ReadOnlyJWTClaimsSet jwtClaims = jwt.getJWTClaimsSet();
// check the signature with nimbus // check the signature with nimbus
if (jwt instanceof SignedJWT) { if (jwt instanceof SignedJWT) {
SignedJWT jws = (SignedJWT)jwt; SignedJWT jws = (SignedJWT)jwt;
JwtSigningAndValidationService validator = validators.get(client.getJwksUri()); JwtSigningAndValidationService validator = validators.get(client.getJwksUri());
if (validator == null || !validator.validateSignature(jws)) { if (validator == null || !validator.validateSignature(jws)) {
throw new AuthenticationServiceException("Invalid signature"); throw new AuthenticationServiceException("Invalid signature");
} }
} }
// check the issuer // check the issuer
if (jwtClaims.getIssuer() == null) { if (jwtClaims.getIssuer() == null) {
@ -114,24 +114,24 @@ public class JwtBearerAuthenticationProvider implements AuthenticationProvider {
throw new AuthenticationServiceException("Audience does not match, expected " + config.getIssuer() + " got " + jwtClaims.getAudience()); throw new AuthenticationServiceException("Audience does not match, expected " + config.getIssuer() + " got " + jwtClaims.getAudience());
} }
// IFF we managed to get all the way down here, the token is valid // IFF we managed to get all the way down here, the token is valid
return new JwtBearerAssertionAuthenticationToken(client.getClientId(), jwt, client.getAuthorities()); return new JwtBearerAssertionAuthenticationToken(client.getClientId(), jwt, client.getAuthorities());
} catch (ClientNotFoundException e) { } catch (ClientNotFoundException e) {
throw new UsernameNotFoundException("Could not find client: " + jwtAuth.getClientId()); throw new UsernameNotFoundException("Could not find client: " + jwtAuth.getClientId());
} catch (ParseException e) { } catch (ParseException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
throw new AuthenticationServiceException("Invalid JWT format"); throw new AuthenticationServiceException("Invalid JWT format");
} }
} }
/** /**
* We support {@link JwtBearerAssertionAuthenticationToken}s only. * We support {@link JwtBearerAssertionAuthenticationToken}s only.
*/ */
@Override @Override
public boolean supports(Class<?> authentication) { public boolean supports(Class<?> authentication) {
return (JwtBearerAssertionAuthenticationToken.class.isAssignableFrom(authentication)); return (JwtBearerAssertionAuthenticationToken.class.isAssignableFrom(authentication));
} }
} }

View File

@ -28,72 +28,72 @@ import com.nimbusds.jwt.JWTParser;
public class JwtBearerClientAssertionTokenEndpointFilter extends ClientCredentialsTokenEndpointFilter { public class JwtBearerClientAssertionTokenEndpointFilter extends ClientCredentialsTokenEndpointFilter {
public JwtBearerClientAssertionTokenEndpointFilter() { public JwtBearerClientAssertionTokenEndpointFilter() {
super(); super();
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
public JwtBearerClientAssertionTokenEndpointFilter(String path) { public JwtBearerClientAssertionTokenEndpointFilter(String path) {
super(path); super(path);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/** /**
* Pull the assertion out of the request and send it up to the auth manager for processing. * Pull the assertion out of the request and send it up to the auth manager for processing.
*/ */
@Override @Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
// check for appropriate parameters // check for appropriate parameters
String assertionType = request.getParameter("client_assertion_type"); String assertionType = request.getParameter("client_assertion_type");
String assertion = request.getParameter("client_assertion"); String assertion = request.getParameter("client_assertion");
try { try {
JWT jwt = JWTParser.parse(assertion); JWT jwt = JWTParser.parse(assertion);
String clientId = jwt.getJWTClaimsSet().getSubject(); String clientId = jwt.getJWTClaimsSet().getSubject();
Authentication authRequest = new JwtBearerAssertionAuthenticationToken(clientId, jwt); Authentication authRequest = new JwtBearerAssertionAuthenticationToken(clientId, jwt);
return this.getAuthenticationManager().authenticate(authRequest); return this.getAuthenticationManager().authenticate(authRequest);
} catch (ParseException e) { } catch (ParseException e) {
throw new BadCredentialsException("Invalid JWT credential: " + assertion); throw new BadCredentialsException("Invalid JWT credential: " + assertion);
} }
} }
/** /**
* Check to see if the "client_assertion_type" and "client_assertion" parameters are present and contain the right values. * Check to see if the "client_assertion_type" and "client_assertion" parameters are present and contain the right values.
*/ */
@Override @Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
// check for appropriate parameters // check for appropriate parameters
String assertionType = request.getParameter("client_assertion_type"); String assertionType = request.getParameter("client_assertion_type");
String assertion = request.getParameter("client_assertion"); String assertion = request.getParameter("client_assertion");
if (Strings.isNullOrEmpty(assertionType) || Strings.isNullOrEmpty(assertion)) { if (Strings.isNullOrEmpty(assertionType) || Strings.isNullOrEmpty(assertion)) {
return false; return false;
} else if (!assertionType.equals("urn:ietf:params:oauth:client-assertion-type:jwt-bearer")) { } else if (!assertionType.equals("urn:ietf:params:oauth:client-assertion-type:jwt-bearer")) {
return false; return false;
} }
// Can't call to superclass here b/c client creds would break for lack of client_id // Can't call to superclass here b/c client creds would break for lack of client_id
// return super.requiresAuthentication(request, response); // return super.requiresAuthentication(request, response);
String uri = request.getRequestURI(); String uri = request.getRequestURI();
int pathParamIndex = uri.indexOf(';'); int pathParamIndex = uri.indexOf(';');
if (pathParamIndex > 0) { if (pathParamIndex > 0) {
// strip everything after the first semi-colon // strip everything after the first semi-colon
uri = uri.substring(0, pathParamIndex); uri = uri.substring(0, pathParamIndex);
} }
if ("".equals(request.getContextPath())) { if ("".equals(request.getContextPath())) {
return uri.endsWith(getFilterProcessesUrl()); return uri.endsWith(getFilterProcessesUrl());
} }
return uri.endsWith(request.getContextPath() + getFilterProcessesUrl()); return uri.endsWith(request.getContextPath() + getFilterProcessesUrl());
} }

View File

@ -5,23 +5,23 @@ public class UserNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public UserNotFoundException() { public UserNotFoundException() {
super(); super();
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
public UserNotFoundException(String message, Throwable cause) { public UserNotFoundException(String message, Throwable cause) {
super(message, cause); super(message, cause);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
public UserNotFoundException(String message) { public UserNotFoundException(String message) {
super(message); super(message);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
public UserNotFoundException(Throwable cause) { public UserNotFoundException(Throwable cause) {
super(cause); super(cause);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
} }

View File

@ -25,7 +25,6 @@ import javax.persistence.TypedQuery;
import org.mitre.openid.connect.model.ApprovedSite; import org.mitre.openid.connect.model.ApprovedSite;
import org.mitre.openid.connect.repository.ApprovedSiteRepository; import org.mitre.openid.connect.repository.ApprovedSiteRepository;
import org.mitre.util.jpa.JpaUtil;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -83,22 +82,22 @@ public class JpaApprovedSiteRepository implements ApprovedSiteRepository {
return query.getResultList(); return query.getResultList();
} }
@Override @Override
@Transactional @Transactional
public Collection<ApprovedSite> getByUserId(String userId) { public Collection<ApprovedSite> getByUserId(String userId) {
TypedQuery<ApprovedSite> query = manager.createNamedQuery("ApprovedSite.getByUserId", ApprovedSite.class); TypedQuery<ApprovedSite> query = manager.createNamedQuery("ApprovedSite.getByUserId", ApprovedSite.class);
query.setParameter("userId", userId); query.setParameter("userId", userId);
return query.getResultList(); return query.getResultList();
} }
@Override @Override
@Transactional @Transactional
public Collection<ApprovedSite> getByClientId(String clientId) { public Collection<ApprovedSite> getByClientId(String clientId) {
TypedQuery<ApprovedSite> query = manager.createNamedQuery("ApprovedSite.getByClientId", ApprovedSite.class); TypedQuery<ApprovedSite> query = manager.createNamedQuery("ApprovedSite.getByClientId", ApprovedSite.class);
query.setParameter("clientId", clientId); query.setParameter("clientId", clientId);
return query.getResultList(); return query.getResultList();
} }
} }

View File

@ -58,7 +58,7 @@ public class JpaEventRepository implements EventRepository {
query = query.setParameter("start", start, TemporalType.DATE); query = query.setParameter("start", start, TemporalType.DATE);
query = query.setParameter("end", end, TemporalType.DATE); query = query.setParameter("end", end, TemporalType.DATE);
query = query.setFirstResult(startChunk); query = query.setFirstResult(startChunk);
query = query.setMaxResults(chunkSize); query = query.setMaxResults(chunkSize);
return query.getResultList(); return query.getResultList();
} }

View File

@ -8,7 +8,6 @@ import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery; import javax.persistence.TypedQuery;
import org.mitre.openid.connect.model.ApprovedSite;
import org.mitre.openid.connect.model.Nonce; import org.mitre.openid.connect.model.Nonce;
import org.mitre.openid.connect.repository.NonceRepository; import org.mitre.openid.connect.repository.NonceRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;

View File

@ -15,8 +15,8 @@
******************************************************************************/ ******************************************************************************/
package org.mitre.openid.connect.repository.impl; package org.mitre.openid.connect.repository.impl;
import static org.mitre.util.jpa.JpaUtil.saveOrUpdate;
import static org.mitre.util.jpa.JpaUtil.getSingleResult; import static org.mitre.util.jpa.JpaUtil.getSingleResult;
import static org.mitre.util.jpa.JpaUtil.saveOrUpdate;
import java.util.Collection; import java.util.Collection;
@ -40,10 +40,10 @@ import org.springframework.transaction.annotation.Transactional;
public class JpaUserInfoRepository implements UserInfoRepository { public class JpaUserInfoRepository implements UserInfoRepository {
@PersistenceContext @PersistenceContext
private EntityManager manager; private EntityManager manager;
@Override @Override
@Transactional @Transactional
public UserInfo getBySubject(String sub) { public UserInfo getBySubject(String sub) {
TypedQuery<DefaultUserInfo> query = manager.createNamedQuery("DefaultUserInfo.getBySubject", DefaultUserInfo.class); TypedQuery<DefaultUserInfo> query = manager.createNamedQuery("DefaultUserInfo.getBySubject", DefaultUserInfo.class);
query.setParameter("sub", sub); query.setParameter("sub", sub);
@ -84,12 +84,12 @@ public class JpaUserInfoRepository implements UserInfoRepository {
* Get a single UserInfo object by its username * Get a single UserInfo object by its username
*/ */
@Override @Override
public UserInfo getByUsername(String username) { public UserInfo getByUsername(String username) {
TypedQuery<DefaultUserInfo> query = manager.createNamedQuery("DefaultUserInfo.getByUsername", DefaultUserInfo.class); TypedQuery<DefaultUserInfo> query = manager.createNamedQuery("DefaultUserInfo.getByUsername", DefaultUserInfo.class);
query.setParameter("username", username); query.setParameter("username", username);
return getSingleResult(query.getResultList()); return getSingleResult(query.getResultList());
} }
} }

View File

@ -53,11 +53,11 @@ public class DefaultApprovedSiteService implements ApprovedSiteService {
} }
/** /**
* Constructor for use in test harnesses. * Constructor for use in test harnesses.
* *
* @param repository * @param repository
*/ */
public DefaultApprovedSiteService(ApprovedSiteRepository approvedSiteRepository) { public DefaultApprovedSiteService(ApprovedSiteRepository approvedSiteRepository) {
this.approvedSiteRepository = approvedSiteRepository; this.approvedSiteRepository = approvedSiteRepository;
} }
@ -98,7 +98,7 @@ public class DefaultApprovedSiteService implements ApprovedSiteService {
@Override @Override
@Transactional @Transactional
public ApprovedSite createApprovedSite(String clientId, String userId, Date timeoutDate, Set<String> allowedScopes, public ApprovedSite createApprovedSite(String clientId, String userId, Date timeoutDate, Set<String> allowedScopes,
WhitelistedSite whitelistedSite) { WhitelistedSite whitelistedSite) {
ApprovedSite as = approvedSiteRepository.save(new ApprovedSite()); ApprovedSite as = approvedSiteRepository.save(new ApprovedSite());
@ -123,34 +123,34 @@ public class DefaultApprovedSiteService implements ApprovedSiteService {
} }
/** /**
* @param userId * @param userId
* @return * @return
* @see org.mitre.openid.connect.repository.ApprovedSiteRepository#getByUserId(java.lang.String) * @see org.mitre.openid.connect.repository.ApprovedSiteRepository#getByUserId(java.lang.String)
*/ */
@Override @Override
public Collection<ApprovedSite> getByUserId(String userId) { public Collection<ApprovedSite> getByUserId(String userId) {
return approvedSiteRepository.getByUserId(userId); return approvedSiteRepository.getByUserId(userId);
} }
/** /**
* @param clientId * @param clientId
* @return * @return
* @see org.mitre.openid.connect.repository.ApprovedSiteRepository#getByClientId(java.lang.String) * @see org.mitre.openid.connect.repository.ApprovedSiteRepository#getByClientId(java.lang.String)
*/ */
@Override @Override
public Collection<ApprovedSite> getByClientId(String clientId) { public Collection<ApprovedSite> getByClientId(String clientId) {
return approvedSiteRepository.getByClientId(clientId); return approvedSiteRepository.getByClientId(clientId);
} }
@Override @Override
public void clearApprovedSitesForClient(ClientDetails client) { public void clearApprovedSitesForClient(ClientDetails client) {
Collection<ApprovedSite> approvedSites = approvedSiteRepository.getByClientId(client.getClientId()); Collection<ApprovedSite> approvedSites = approvedSiteRepository.getByClientId(client.getClientId());
if (approvedSites != null) { if (approvedSites != null) {
for (ApprovedSite approvedSite : approvedSites) { for (ApprovedSite approvedSite : approvedSites) {
approvedSiteRepository.remove(approvedSite); approvedSiteRepository.remove(approvedSite);
} }
} }
} }
} }

View File

@ -80,10 +80,10 @@ public class DefaultBlacklistedSiteService implements BlacklistedSiteService {
// TODO: rewrite this to do regex matching and use the Guava predicates collection // TODO: rewrite this to do regex matching and use the Guava predicates collection
for (BlacklistedSite blacklistedSite : sites) { for (BlacklistedSite blacklistedSite : sites) {
if (Strings.nullToEmpty(blacklistedSite.getUri()).equals(uri)) { if (Strings.nullToEmpty(blacklistedSite.getUri()).equals(uri)) {
return true; return true;
} }
} }
return false; return false;
} }

View File

@ -29,6 +29,7 @@ public class DefaultNonceService implements NonceService, InitializingBean {
/** /**
* Make sure that the nonce storage duration was set * Make sure that the nonce storage duration was set
*/ */
@Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
if (nonceStorageDuration == null) { if (nonceStorageDuration == null) {
logger.error("Nonce storage duration must be set!"); logger.error("Nonce storage duration must be set!");

View File

@ -26,24 +26,24 @@ public class DefaultStatsService implements StatsService {
private ApprovedSiteService approvedSiteService; private ApprovedSiteService approvedSiteService;
@Override @Override
public Map<String, Integer> calculateSummaryStats() { public Map<String, Integer> calculateSummaryStats() {
// get all approved sites // get all approved sites
Collection<ApprovedSite> allSites = approvedSiteService.getAll(); Collection<ApprovedSite> allSites = approvedSiteService.getAll();
// process to find number of unique users and sites // process to find number of unique users and sites
Set<String> userIds = new HashSet<String>(); Set<String> userIds = new HashSet<String>();
Set<String> clientIds = new HashSet<String>(); Set<String> clientIds = new HashSet<String>();
for (ApprovedSite approvedSite : allSites) { for (ApprovedSite approvedSite : allSites) {
userIds.add(approvedSite.getUserId()); userIds.add(approvedSite.getUserId());
clientIds.add(approvedSite.getClientId()); clientIds.add(approvedSite.getClientId());
} }
Map<String, Integer> e = new HashMap<String, Integer>(); Map<String, Integer> e = new HashMap<String, Integer>();
e.put("approvalCount", allSites.size()); e.put("approvalCount", allSites.size());
e.put("userCount", userIds.size()); e.put("userCount", userIds.size());
e.put("clientCount", clientIds.size()); e.put("clientCount", clientIds.size());
return e; return e;
} }
} }

View File

@ -72,17 +72,17 @@ public class DefaultUserInfoService implements UserInfoService {
} }
/** /**
* @return the userInfoRepository * @return the userInfoRepository
*/ */
public UserInfoRepository getUserInfoRepository() { public UserInfoRepository getUserInfoRepository() {
return userInfoRepository; return userInfoRepository;
} }
/** /**
* @param userInfoRepository the userInfoRepository to set * @param userInfoRepository the userInfoRepository to set
*/ */
public void setUserInfoRepository(UserInfoRepository userInfoRepository) { public void setUserInfoRepository(UserInfoRepository userInfoRepository) {
this.userInfoRepository = userInfoRepository; this.userInfoRepository = userInfoRepository;
} }
} }

View File

@ -26,10 +26,10 @@ public class DefaultUserInfoUserDetailsService implements UserDetailsService {
@Autowired @Autowired
UserInfoRepository repository; UserInfoRepository repository;
public static final GrantedAuthority ROLE_USER = new SimpleGrantedAuthority("ROLE_USER"); public static final GrantedAuthority ROLE_USER = new SimpleGrantedAuthority("ROLE_USER");
public static final GrantedAuthority ROLE_ADMIN = new SimpleGrantedAuthority("ROLE_ADMIN"); public static final GrantedAuthority ROLE_ADMIN = new SimpleGrantedAuthority("ROLE_ADMIN");
private List<String> admins = new ArrayList<String>(); private List<String> admins = new ArrayList<String>();
@Override @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
@ -40,14 +40,14 @@ public class DefaultUserInfoUserDetailsService implements UserDetailsService {
// TODO: make passwords configurable? part of object? // TODO: make passwords configurable? part of object?
String password = "password"; String password = "password";
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(ROLE_USER); authorities.add(ROLE_USER);
if (admins != null && admins.contains(username)) { if (admins != null && admins.contains(username)) {
authorities.add(ROLE_ADMIN); authorities.add(ROLE_ADMIN);
} }
// TODO: this should really be our own UserDetails wrapper class, shouldn't it? // TODO: this should really be our own UserDetails wrapper class, shouldn't it?
User user = new User(userInfo.getSub(), password, authorities); User user = new User(userInfo.getSub(), password, authorities);
return user; return user;
} else { } else {
@ -56,17 +56,17 @@ public class DefaultUserInfoUserDetailsService implements UserDetailsService {
} }
/** /**
* @return the admins * @return the admins
*/ */
public List<String> getAdmins() { public List<String> getAdmins() {
return admins; return admins;
} }
/** /**
* @param admins the admins to set * @param admins the admins to set
*/ */
public void setAdmins(List<String> admins) { public void setAdmins(List<String> admins) {
this.admins = admins; this.admins = admins;
} }
} }

View File

@ -86,12 +86,12 @@ public class DefaultWhitelistedSiteService implements WhitelistedSiteService {
return repository.getByCreator(creatorId); return repository.getByCreator(creatorId);
} }
@Override @Override
public WhitelistedSite update(WhitelistedSite oldWhitelistedSite, WhitelistedSite whitelistedSite) { public WhitelistedSite update(WhitelistedSite oldWhitelistedSite, WhitelistedSite whitelistedSite) {
if (oldWhitelistedSite == null || whitelistedSite == null) { if (oldWhitelistedSite == null || whitelistedSite == null) {
throw new IllegalArgumentException("Neither the old or new sites may be null"); throw new IllegalArgumentException("Neither the old or new sites may be null");
} }
return repository.update(oldWhitelistedSite, whitelistedSite); return repository.update(oldWhitelistedSite, whitelistedSite);
} }
} }

View File

@ -83,9 +83,9 @@ public class ConnectTokenEnhancer implements TokenEnhancer {
SignedJWT signed = new SignedJWT(new JWSHeader(jwtService.getDefaultSigningAlgorithm()), claims); SignedJWT signed = new SignedJWT(new JWSHeader(jwtService.getDefaultSigningAlgorithm()), claims);
jwtService.signJwt(signed); jwtService.signJwt(signed);
token.setJwt(signed); token.setJwt(signed);
/** /**
* Authorization request scope MUST include "openid" in OIDC, but access token request * Authorization request scope MUST include "openid" in OIDC, but access token request

View File

@ -122,7 +122,7 @@ public class TofuUserApprovalHandler implements UserApprovalHandler {
alreadyApproved = true; alreadyApproved = true;
} }
} }
} }
if (!alreadyApproved) { if (!alreadyApproved) {
WhitelistedSite ws = whitelistedSiteService.getByClientId(clientId); WhitelistedSite ws = whitelistedSiteService.getByClientId(clientId);
@ -141,7 +141,7 @@ public class TofuUserApprovalHandler implements UserApprovalHandler {
@Override @Override
public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
String userId = userAuthentication.getName(); String userId = userAuthentication.getName();
String clientId = authorizationRequest.getClientId(); String clientId = authorizationRequest.getClientId();
@ -198,7 +198,7 @@ public class TofuUserApprovalHandler implements UserApprovalHandler {
} }
return authorizationRequest; return authorizationRequest;
} }
/** /**
* Check whether the requested scope set is a proper subset of the allowed scopes. * Check whether the requested scope set is a proper subset of the allowed scopes.

View File

@ -17,11 +17,9 @@ import org.mitre.jose.JWSAlgorithmEmbed;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.web.servlet.view.AbstractView; import org.springframework.web.servlet.view.AbstractView;
import com.google.gson.ExclusionStrategy; import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
@ -43,71 +41,72 @@ public abstract class AbstractClientEntityView extends AbstractView {
private static Logger logger = LoggerFactory.getLogger(ClientEntityViewForAdmins.class); private static Logger logger = LoggerFactory.getLogger(ClientEntityViewForAdmins.class);
private Gson gson = new GsonBuilder() private Gson gson = new GsonBuilder()
.setExclusionStrategies(getExclusionStrategy()) .setExclusionStrategies(getExclusionStrategy())
.registerTypeAdapter(JWSAlgorithmEmbed.class, new JsonSerializer<JWSAlgorithmEmbed>() { .registerTypeAdapter(JWSAlgorithmEmbed.class, new JsonSerializer<JWSAlgorithmEmbed>() {
@Override @Override
public JsonElement serialize(JWSAlgorithmEmbed src, Type typeOfSrc, JsonSerializationContext context) { public JsonElement serialize(JWSAlgorithmEmbed src, Type typeOfSrc, JsonSerializationContext context) {
if (src != null) { if (src != null) {
return new JsonPrimitive(src.getAlgorithmName()); return new JsonPrimitive(src.getAlgorithmName());
} else { } else {
return null; return null;
} }
} }
}) })
.registerTypeAdapter(JWEAlgorithmEmbed.class, new JsonSerializer<JWEAlgorithmEmbed>() { .registerTypeAdapter(JWEAlgorithmEmbed.class, new JsonSerializer<JWEAlgorithmEmbed>() {
@Override @Override
public JsonElement serialize(JWEAlgorithmEmbed src, Type typeOfSrc, JsonSerializationContext context) { public JsonElement serialize(JWEAlgorithmEmbed src, Type typeOfSrc, JsonSerializationContext context) {
if (src != null) { if (src != null) {
return new JsonPrimitive(src.getAlgorithmName()); return new JsonPrimitive(src.getAlgorithmName());
} else { } else {
return null; return null;
} }
} }
}) })
.registerTypeAdapter(JWEEncryptionMethodEmbed.class, new JsonSerializer<JWEEncryptionMethodEmbed>() { .registerTypeAdapter(JWEEncryptionMethodEmbed.class, new JsonSerializer<JWEEncryptionMethodEmbed>() {
@Override @Override
public JsonElement serialize(JWEEncryptionMethodEmbed src, Type typeOfSrc, JsonSerializationContext context) { public JsonElement serialize(JWEEncryptionMethodEmbed src, Type typeOfSrc, JsonSerializationContext context) {
if (src != null) { if (src != null) {
return new JsonPrimitive(src.getAlgorithmName()); return new JsonPrimitive(src.getAlgorithmName());
} else { } else {
return null; return null;
} }
} }
}) })
.serializeNulls() .serializeNulls()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create(); .create();
/** /**
* @return * @return
*/ */
protected abstract ExclusionStrategy getExclusionStrategy(); protected abstract ExclusionStrategy getExclusionStrategy();
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) { @Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/json"); response.setContentType("application/json");
HttpStatus code = (HttpStatus) model.get("code"); HttpStatus code = (HttpStatus) model.get("code");
if (code == null) { if (code == null) {
code = HttpStatus.OK; // default to 200 code = HttpStatus.OK; // default to 200
} }
response.setStatus(code.value()); response.setStatus(code.value());
try { try {
Writer out = response.getWriter(); Writer out = response.getWriter();
Object obj = model.get("entity"); Object obj = model.get("entity");
gson.toJson(obj, out); gson.toJson(obj, out);
} catch (IOException e) { } catch (IOException e) {
logger.error("IOException in JsonEntityView.java: ", e); logger.error("IOException in JsonEntityView.java: ", e);
} }
} }
} }

View File

@ -3,34 +3,14 @@
*/ */
package org.mitre.openid.connect.view; package org.mitre.openid.connect.view;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mitre.jose.JWEAlgorithmEmbed;
import org.mitre.jose.JWEEncryptionMethodEmbed;
import org.mitre.jose.JWSAlgorithmEmbed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.web.servlet.view.AbstractView;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.gson.ExclusionStrategy; import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes; import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
/** /**
* *
@ -48,25 +28,28 @@ public class ClientEntityViewForAdmins extends AbstractClientEntityView {
/** /**
* @return * @return
*/ */
protected ExclusionStrategy getExclusionStrategy() { @Override
return new ExclusionStrategy() { protected ExclusionStrategy getExclusionStrategy() {
return new ExclusionStrategy() {
public boolean shouldSkipField(FieldAttributes f) { @Override
if (blacklistedFields.contains(f.getName())) { public boolean shouldSkipField(FieldAttributes f) {
return true; if (blacklistedFields.contains(f.getName())) {
} else { return true;
return false; } else {
} return false;
} }
}
public boolean shouldSkipClass(Class<?> clazz) { @Override
// skip the JPA binding wrapper public boolean shouldSkipClass(Class<?> clazz) {
if (clazz.equals(BeanPropertyBindingResult.class)) { // skip the JPA binding wrapper
return true; if (clazz.equals(BeanPropertyBindingResult.class)) {
} return true;
return false; }
} return false;
}
}; };
} }
} }

View File

@ -3,34 +3,14 @@
*/ */
package org.mitre.openid.connect.view; package org.mitre.openid.connect.view;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mitre.jose.JWEAlgorithmEmbed;
import org.mitre.jose.JWEEncryptionMethodEmbed;
import org.mitre.jose.JWSAlgorithmEmbed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.web.servlet.view.AbstractView;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.gson.ExclusionStrategy; import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes; import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
/** /**
* *
@ -49,28 +29,30 @@ public class ClientEntityViewForUsers extends AbstractClientEntityView {
/* (non-Javadoc) /* (non-Javadoc)
* @see org.mitre.openid.connect.view.AbstractClientEntityView#getExclusionStrategy() * @see org.mitre.openid.connect.view.AbstractClientEntityView#getExclusionStrategy()
*/ */
@Override @Override
protected ExclusionStrategy getExclusionStrategy() { protected ExclusionStrategy getExclusionStrategy() {
return new ExclusionStrategy() { return new ExclusionStrategy() {
public boolean shouldSkipField(FieldAttributes f) { @Override
// whitelist the handful of fields that are good public boolean shouldSkipField(FieldAttributes f) {
if (whitelistedFields.contains(f.getName())) { // whitelist the handful of fields that are good
return false; if (whitelistedFields.contains(f.getName())) {
} else { return false;
return true; } else {
} return true;
} }
}
public boolean shouldSkipClass(Class<?> clazz) { @Override
// skip the JPA binding wrapper public boolean shouldSkipClass(Class<?> clazz) {
if (clazz.equals(BeanPropertyBindingResult.class)) { // skip the JPA binding wrapper
return true; if (clazz.equals(BeanPropertyBindingResult.class)) {
} return true;
return false; }
} return false;
}
}; };
} }
} }

View File

@ -106,15 +106,15 @@ public class ClientInformationResponseView extends AbstractView {
o.add("request_uris", getAsArray(c.getRequestUris())); o.add("request_uris", getAsArray(c.getRequestUris()));
try { try {
Writer out = response.getWriter(); Writer out = response.getWriter();
gson.toJson(o, out); gson.toJson(o, out);
} catch (JsonIOException e) { } catch (JsonIOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }

View File

@ -55,6 +55,7 @@ public class JSONUserInfoView extends AbstractView {
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) * @see org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/ */
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) { protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
UserInfo userInfo = (UserInfo) model.get("userInfo"); UserInfo userInfo = (UserInfo) model.get("userInfo");
@ -62,22 +63,24 @@ public class JSONUserInfoView extends AbstractView {
Set<String> scope = (Set<String>) model.get("scope"); Set<String> scope = (Set<String>) model.get("scope");
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() { .setExclusionStrategies(new ExclusionStrategy() {
public boolean shouldSkipField(FieldAttributes f) { @Override
public boolean shouldSkipField(FieldAttributes f) {
return false; return false;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
// skip the JPA binding wrapper
if (clazz.equals(BeanPropertyBindingResult.class)) {
return true;
} }
return false;
}
public boolean shouldSkipClass(Class<?> clazz) { }).create();
// skip the JPA binding wrapper
if (clazz.equals(BeanPropertyBindingResult.class)) {
return true;
}
return false;
}
}).create();
response.setContentType("application/json"); response.setContentType("application/json");
@ -90,23 +93,23 @@ public class JSONUserInfoView extends AbstractView {
if (model.get("requestObject") != null) { if (model.get("requestObject") != null) {
try { try {
String jwtString = (String)model.get("requestObject"); String jwtString = (String)model.get("requestObject");
JWT requestObject = JWTParser.parse(jwtString); JWT requestObject = JWTParser.parse(jwtString);
// FIXME: move to GSON for easier processing // FIXME: move to GSON for easier processing
JsonObject obj = (JsonObject) new JsonParser().parse(requestObject.getJWTClaimsSet().toJSONObject().toJSONString()); JsonObject obj = (JsonObject) new JsonParser().parse(requestObject.getJWTClaimsSet().toJSONObject().toJSONString());
gson.toJson(toJsonFromRequestObj(userInfo, scope, obj), out); gson.toJson(toJsonFromRequestObj(userInfo, scope, obj), out);
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} catch (JsonIOException e) { } catch (JsonIOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} catch (ParseException e) { } catch (ParseException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {

View File

@ -38,35 +38,38 @@ public class JsonApprovedSiteView extends AbstractView {
private static Logger logger = LoggerFactory.getLogger(JsonApprovedSiteView.class); private static Logger logger = LoggerFactory.getLogger(JsonApprovedSiteView.class);
private Gson gson = new GsonBuilder() private Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() { .setExclusionStrategies(new ExclusionStrategy() {
public boolean shouldSkipField(FieldAttributes f) { @Override
public boolean shouldSkipField(FieldAttributes f) {
return false; return false;
} }
public boolean shouldSkipClass(Class<?> clazz) { @Override
// skip the JPA binding wrapper public boolean shouldSkipClass(Class<?> clazz) {
if (clazz.equals(BeanPropertyBindingResult.class)) { // skip the JPA binding wrapper
return true; if (clazz.equals(BeanPropertyBindingResult.class)) {
} return true;
return false;
}
})
.registerTypeAdapter(OAuth2AccessTokenEntity.class, new JsonSerializer<OAuth2AccessTokenEntity>() {
@Override
public JsonElement serialize(OAuth2AccessTokenEntity src,
Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getId());
} }
return false;
}
}) })
.serializeNulls() .registerTypeAdapter(OAuth2AccessTokenEntity.class, new JsonSerializer<OAuth2AccessTokenEntity>() {
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
@Override
public JsonElement serialize(OAuth2AccessTokenEntity src,
Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getId());
}
})
.serializeNulls()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) { protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/json"); response.setContentType("application/json");
@ -83,7 +86,7 @@ public class JsonApprovedSiteView extends AbstractView {
Writer out = response.getWriter(); Writer out = response.getWriter();
Object obj = model.get("entity"); Object obj = model.get("entity");
gson.toJson(obj, out); gson.toJson(obj, out);
} catch (IOException e) { } catch (IOException e) {
@ -91,6 +94,6 @@ public class JsonApprovedSiteView extends AbstractView {
logger.error("IOException in JsonEntityView.java: ", e); logger.error("IOException in JsonEntityView.java: ", e);
} }
} }
} }

View File

@ -32,26 +32,29 @@ public class JsonEntityView extends AbstractView {
private static Logger logger = LoggerFactory.getLogger(JsonEntityView.class); private static Logger logger = LoggerFactory.getLogger(JsonEntityView.class);
private Gson gson = new GsonBuilder() private Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() { .setExclusionStrategies(new ExclusionStrategy() {
public boolean shouldSkipField(FieldAttributes f) { @Override
public boolean shouldSkipField(FieldAttributes f) {
return false; return false;
} }
public boolean shouldSkipClass(Class<?> clazz) { @Override
// skip the JPA binding wrapper public boolean shouldSkipClass(Class<?> clazz) {
if (clazz.equals(BeanPropertyBindingResult.class)) { // skip the JPA binding wrapper
return true; if (clazz.equals(BeanPropertyBindingResult.class)) {
} return true;
return false; }
} return false;
}
}) })
.serializeNulls() .serializeNulls()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create(); .create();
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) { protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/json"); response.setContentType("application/json");
@ -68,7 +71,7 @@ public class JsonEntityView extends AbstractView {
Writer out = response.getWriter(); Writer out = response.getWriter();
Object obj = model.get("entity"); Object obj = model.get("entity");
gson.toJson(obj, out); gson.toJson(obj, out);
} catch (IOException e) { } catch (IOException e) {
@ -76,6 +79,6 @@ public class JsonEntityView extends AbstractView {
logger.error("IOException in JsonEntityView.java: ", e); logger.error("IOException in JsonEntityView.java: ", e);
} }
} }
} }

View File

@ -30,26 +30,29 @@ public class JsonErrorView extends AbstractView {
private static Logger logger = LoggerFactory.getLogger(JsonEntityView.class); private static Logger logger = LoggerFactory.getLogger(JsonEntityView.class);
private Gson gson = new GsonBuilder() private Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() { .setExclusionStrategies(new ExclusionStrategy() {
public boolean shouldSkipField(FieldAttributes f) { @Override
public boolean shouldSkipField(FieldAttributes f) {
return false; return false;
} }
public boolean shouldSkipClass(Class<?> clazz) { @Override
// skip the JPA binding wrapper public boolean shouldSkipClass(Class<?> clazz) {
if (clazz.equals(BeanPropertyBindingResult.class)) { // skip the JPA binding wrapper
return true; if (clazz.equals(BeanPropertyBindingResult.class)) {
} return true;
return false; }
} return false;
}
}) })
.serializeNulls() .serializeNulls()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create(); .create();
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) { protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/json"); response.setContentType("application/json");
@ -69,7 +72,7 @@ public class JsonErrorView extends AbstractView {
String errorMessage = (String) model.get("errorMessage"); String errorMessage = (String) model.get("errorMessage");
JsonObject obj = new JsonObject(); JsonObject obj = new JsonObject();
obj.addProperty("error_message", errorMessage); obj.addProperty("error_message", errorMessage);
gson.toJson(obj, out); gson.toJson(obj, out);
} catch (IOException e) { } catch (IOException e) {
@ -77,6 +80,6 @@ public class JsonErrorView extends AbstractView {
logger.error("IOException in JsonErrorView.java: ", e); logger.error("IOException in JsonErrorView.java: ", e);
} }
} }
} }

View File

@ -45,6 +45,7 @@ public class POCOUserInfoView extends AbstractView {
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) * @see org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/ */
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) { protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
UserInfo userInfo = (UserInfo) model.get("userInfo"); UserInfo userInfo = (UserInfo) model.get("userInfo");
@ -52,22 +53,24 @@ public class POCOUserInfoView extends AbstractView {
Set<String> scope = (Set<String>) model.get("scope"); Set<String> scope = (Set<String>) model.get("scope");
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() { .setExclusionStrategies(new ExclusionStrategy() {
public boolean shouldSkipField(FieldAttributes f) { @Override
public boolean shouldSkipField(FieldAttributes f) {
return false; return false;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
// skip the JPA binding wrapper
if (clazz.equals(BeanPropertyBindingResult.class)) {
return true;
} }
return false;
}
public boolean shouldSkipClass(Class<?> clazz) { }).create();
// skip the JPA binding wrapper
if (clazz.equals(BeanPropertyBindingResult.class)) {
return true;
}
return false;
}
}).create();
response.setContentType("application/json"); response.setContentType("application/json");

View File

@ -28,42 +28,44 @@ public class StatsSummary extends AbstractView {
@Override @Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) { protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() { .setExclusionStrategies(new ExclusionStrategy() {
public boolean shouldSkipField(FieldAttributes f) { @Override
public boolean shouldSkipField(FieldAttributes f) {
return false; return false;
} }
public boolean shouldSkipClass(Class<?> clazz) { @Override
// skip the JPA binding wrapper public boolean shouldSkipClass(Class<?> clazz) {
if (clazz.equals(BeanPropertyBindingResult.class)) { // skip the JPA binding wrapper
return true; if (clazz.equals(BeanPropertyBindingResult.class)) {
} return true;
return false; }
} return false;
}
}).create(); }).create();
response.setContentType("application/json"); response.setContentType("application/json");
try { try {
Writer out = response.getWriter(); Writer out = response.getWriter();
Object obj = model.get("entity"); Object obj = model.get("entity");
if (obj == null) { if (obj == null) {
obj = model; obj = model;
} }
gson.toJson(obj, out); gson.toJson(obj, out);
} catch (IOException e) { } catch (IOException e) {
logger.error("IOException in JSONClientView.java: ", e); logger.error("IOException in JSONClientView.java: ", e);
} }
} }

View File

@ -58,111 +58,111 @@ import com.google.gson.JsonSyntaxException;
@PreAuthorize("hasRole('ROLE_USER')") @PreAuthorize("hasRole('ROLE_USER')")
public class ClientAPI { public class ClientAPI {
@Autowired @Autowired
private ClientDetailsEntityService clientService; private ClientDetailsEntityService clientService;
private JsonParser parser = new JsonParser(); private JsonParser parser = new JsonParser();
private Gson gson = new GsonBuilder() private Gson gson = new GsonBuilder()
.serializeNulls() .serializeNulls()
.registerTypeAdapter(JWSAlgorithmEmbed.class, new JsonDeserializer<JWSAlgorithmEmbed>() { .registerTypeAdapter(JWSAlgorithmEmbed.class, new JsonDeserializer<JWSAlgorithmEmbed>() {
@Override @Override
public JWSAlgorithmEmbed deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { public JWSAlgorithmEmbed deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonPrimitive()) { if (json.isJsonPrimitive()) {
return JWSAlgorithmEmbed.getForAlgorithmName(json.getAsString()); return JWSAlgorithmEmbed.getForAlgorithmName(json.getAsString());
} else { } else {
return null; return null;
} }
} }
}) })
.registerTypeAdapter(JWEAlgorithmEmbed.class, new JsonDeserializer<JWEAlgorithmEmbed>() { .registerTypeAdapter(JWEAlgorithmEmbed.class, new JsonDeserializer<JWEAlgorithmEmbed>() {
@Override @Override
public JWEAlgorithmEmbed deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { public JWEAlgorithmEmbed deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonPrimitive()) { if (json.isJsonPrimitive()) {
return JWEAlgorithmEmbed.getForAlgorithmName(json.getAsString()); return JWEAlgorithmEmbed.getForAlgorithmName(json.getAsString());
} else { } else {
return null; return null;
} }
} }
}) })
.registerTypeAdapter(JWEEncryptionMethodEmbed.class, new JsonDeserializer<JWEEncryptionMethodEmbed>() { .registerTypeAdapter(JWEEncryptionMethodEmbed.class, new JsonDeserializer<JWEEncryptionMethodEmbed>() {
@Override @Override
public JWEEncryptionMethodEmbed deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { public JWEEncryptionMethodEmbed deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonPrimitive()) { if (json.isJsonPrimitive()) {
return JWEEncryptionMethodEmbed.getForAlgorithmName(json.getAsString()); return JWEEncryptionMethodEmbed.getForAlgorithmName(json.getAsString());
} else { } else {
return null; return null;
} }
} }
}) })
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create(); .create();
private static Logger logger = LoggerFactory.getLogger(ClientAPI.class); private static Logger logger = LoggerFactory.getLogger(ClientAPI.class);
/** /**
* Get a list of all clients * Get a list of all clients
* @param modelAndView * @param modelAndView
* @return * @return
*/ */
@RequestMapping(method = RequestMethod.GET, produces = "application/json") @RequestMapping(method = RequestMethod.GET, produces = "application/json")
public String apiGetAllClients(Model model, Authentication auth) { public String apiGetAllClients(Model model, Authentication auth) {
Collection<ClientDetailsEntity> clients = clientService.getAllClients(); Collection<ClientDetailsEntity> clients = clientService.getAllClients();
model.addAttribute("entity", clients); model.addAttribute("entity", clients);
if (isAdmin(auth)) { if (isAdmin(auth)) {
return "clientEntityViewAdmins"; return "clientEntityViewAdmins";
} else { } else {
return "clientEntityViewUsers"; return "clientEntityViewUsers";
} }
} }
/** /**
* Create a new client * Create a new client
* @param json * @param json
* @param m * @param m
* @param principal * @param principal
* @return * @return
*/ */
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public String apiAddClient(@RequestBody String jsonString, Model m, Authentication auth) { public String apiAddClient(@RequestBody String jsonString, Model m, Authentication auth) {
JsonObject json = null; JsonObject json = null;
ClientDetailsEntity client = null; ClientDetailsEntity client = null;
try { try {
json = parser.parse(jsonString).getAsJsonObject(); json = parser.parse(jsonString).getAsJsonObject();
client = gson.fromJson(json, ClientDetailsEntity.class); client = gson.fromJson(json, ClientDetailsEntity.class);
} }
catch (JsonSyntaxException e) { catch (JsonSyntaxException e) {
logger.error("apiAddClient failed due to JsonSyntaxException: " , e); logger.error("apiAddClient failed due to JsonSyntaxException: " , e);
m.addAttribute("code", HttpStatus.BAD_REQUEST); m.addAttribute("code", HttpStatus.BAD_REQUEST);
m.addAttribute("errorMessage", "Could not save new client. The server encountered a JSON syntax exception. Contact a system administrator for assistance."); m.addAttribute("errorMessage", "Could not save new client. The server encountered a JSON syntax exception. Contact a system administrator for assistance.");
return "jsonErrorView"; return "jsonErrorView";
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
logger.error("apiAddClient failed due to IllegalStateException: " , e); logger.error("apiAddClient failed due to IllegalStateException: " , e);
m.addAttribute("code", HttpStatus.BAD_REQUEST); m.addAttribute("code", HttpStatus.BAD_REQUEST);
m.addAttribute("errorMessage", "Could not save new client. The server encountered an IllegalStateException. Refresh and try again - if the problem persists, contact a system administrator for assistance."); m.addAttribute("errorMessage", "Could not save new client. The server encountered an IllegalStateException. Refresh and try again - if the problem persists, contact a system administrator for assistance.");
return "jsonErrorView"; return "jsonErrorView";
} }
// if they leave the client secret empty, force it to be generated // if they leave the client secret empty, force it to be generated
if (Strings.isNullOrEmpty(client.getClientId())) { if (Strings.isNullOrEmpty(client.getClientId())) {
client = clientService.generateClientId(client); client = clientService.generateClientId(client);
} }
// if they've asked for us to generate a client secret, do so here // if they've asked for us to generate a client secret, do so here
if (json.has("generateClientSecret") && json.get("generateClientSecret").getAsBoolean()) { if (json.has("generateClientSecret") && json.get("generateClientSecret").getAsBoolean()) {
client = clientService.generateClientSecret(client); client = clientService.generateClientSecret(client);
} }
// set owners as current logged in user // set owners as current logged in user
//client.setOwner(principal.getName()); //client.setOwner(principal.getName());
//TODO: owner has been replaced by a list of contacts, which should be styled as email addresses. //TODO: owner has been replaced by a list of contacts, which should be styled as email addresses.
client.setDynamicallyRegistered(false); client.setDynamicallyRegistered(false);
ClientDetailsEntity newClient = clientService.saveNewClient(client); ClientDetailsEntity newClient = clientService.saveNewClient(client);
m.addAttribute("entity", newClient); m.addAttribute("entity", newClient);
if (isAdmin(auth)) { if (isAdmin(auth)) {
@ -170,64 +170,64 @@ public class ClientAPI {
} else { } else {
return "clientEntityViewUsers"; return "clientEntityViewUsers";
} }
} }
/** /**
* Update an existing client * Update an existing client
* @param id * @param id
* @param jsonString * @param jsonString
* @param m * @param m
* @param principal * @param principal
* @return * @return
*/ */
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value="/{id}", method = RequestMethod.PUT, consumes = "application/json", produces = "application/json") @RequestMapping(value="/{id}", method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")
public String apiUpdateClient(@PathVariable("id") Long id, @RequestBody String jsonString, Model m, Authentication auth) { public String apiUpdateClient(@PathVariable("id") Long id, @RequestBody String jsonString, Model m, Authentication auth) {
JsonObject json = null; JsonObject json = null;
ClientDetailsEntity client = null; ClientDetailsEntity client = null;
try { try {
// parse the client passed in (from JSON) and fetch the old client from the store // parse the client passed in (from JSON) and fetch the old client from the store
json = parser.parse(jsonString).getAsJsonObject(); json = parser.parse(jsonString).getAsJsonObject();
client = gson.fromJson(json, ClientDetailsEntity.class); client = gson.fromJson(json, ClientDetailsEntity.class);
} }
catch (JsonSyntaxException e) { catch (JsonSyntaxException e) {
logger.error("apiUpdateClient failed due to JsonSyntaxException: " , e); logger.error("apiUpdateClient failed due to JsonSyntaxException: " , e);
m.addAttribute("code", HttpStatus.BAD_REQUEST); m.addAttribute("code", HttpStatus.BAD_REQUEST);
m.addAttribute("errorMessage", "Could not update client. The server encountered a JSON syntax exception. Contact a system administrator for assistance."); m.addAttribute("errorMessage", "Could not update client. The server encountered a JSON syntax exception. Contact a system administrator for assistance.");
return "jsonErrorView"; return "jsonErrorView";
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
logger.error("apiUpdateClient failed due to IllegalStateException: " , e); logger.error("apiUpdateClient failed due to IllegalStateException: " , e);
m.addAttribute("code", HttpStatus.BAD_REQUEST); m.addAttribute("code", HttpStatus.BAD_REQUEST);
m.addAttribute("errorMessage", "Could not update client. The server encountered an IllegalStateException. Refresh and try again - if the problem persists, contact a system administrator for assistance."); m.addAttribute("errorMessage", "Could not update client. The server encountered an IllegalStateException. Refresh and try again - if the problem persists, contact a system administrator for assistance.");
return "jsonErrorView"; return "jsonErrorView";
} }
ClientDetailsEntity oldClient = clientService.getClientById(id); ClientDetailsEntity oldClient = clientService.getClientById(id);
if (oldClient == null) { if (oldClient == null) {
logger.error("apiUpdateClient failed; client with id " + id + " could not be found."); logger.error("apiUpdateClient failed; client with id " + id + " could not be found.");
m.addAttribute("code", HttpStatus.NOT_FOUND); m.addAttribute("code", HttpStatus.NOT_FOUND);
m.addAttribute("errorMessage", "Could not update client. The requested client with id " + id + "could not be found."); m.addAttribute("errorMessage", "Could not update client. The requested client with id " + id + "could not be found.");
return "jsonErrorView"; return "jsonErrorView";
} }
// if they leave the client secret empty, force it to be generated // if they leave the client secret empty, force it to be generated
if (Strings.isNullOrEmpty(client.getClientId())) { if (Strings.isNullOrEmpty(client.getClientId())) {
client = clientService.generateClientId(client); client = clientService.generateClientId(client);
} }
// if they've asked for us to generate a client secret, do so here // if they've asked for us to generate a client secret, do so here
if (json.has("generateClientSecret") && json.get("generateClientSecret").getAsBoolean()) { if (json.has("generateClientSecret") && json.get("generateClientSecret").getAsBoolean()) {
client = clientService.generateClientSecret(client); client = clientService.generateClientSecret(client);
} }
// set owners as current logged in user // set owners as current logged in user
// client.setOwner(principal.getName()); // client.setOwner(principal.getName());
//TODO: owner has been replaced by a list of contacts, which should be styled as email addresses. //TODO: owner has been replaced by a list of contacts, which should be styled as email addresses.
ClientDetailsEntity newClient = clientService.updateClient(oldClient, client); ClientDetailsEntity newClient = clientService.updateClient(oldClient, client);
m.addAttribute("entity", newClient); m.addAttribute("entity", newClient);
if (isAdmin(auth)) { if (isAdmin(auth)) {
@ -235,19 +235,19 @@ public class ClientAPI {
} else { } else {
return "clientEntityViewUsers"; return "clientEntityViewUsers";
} }
} }
/** /**
* Delete a client * Delete a client
* @param id * @param id
* @param modelAndView * @param modelAndView
* @return * @return
*/ */
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@RequestMapping(value="/{id}", method=RequestMethod.DELETE) @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public String apiDeleteClient(@PathVariable("id") Long id, ModelAndView modelAndView) { public String apiDeleteClient(@PathVariable("id") Long id, ModelAndView modelAndView) {
ClientDetailsEntity client = clientService.getClientById(id); ClientDetailsEntity client = clientService.getClientById(id);
if (client == null) { if (client == null) {
logger.error("apiDeleteClient failed; client with id " + id + " could not be found."); logger.error("apiDeleteClient failed; client with id " + id + " could not be found.");
@ -260,47 +260,47 @@ public class ClientAPI {
} }
return "httpCodeView"; return "httpCodeView";
} }
/** /**
* Get an individual client * Get an individual client
* @param id * @param id
* @param modelAndView * @param modelAndView
* @return * @return
*/ */
@RequestMapping(value="/{id}", method=RequestMethod.GET, produces = "application/json") @RequestMapping(value="/{id}", method=RequestMethod.GET, produces = "application/json")
public String apiShowClient(@PathVariable("id") Long id, Model model, Authentication auth) { public String apiShowClient(@PathVariable("id") Long id, Model model, Authentication auth) {
ClientDetailsEntity client = clientService.getClientById(id); ClientDetailsEntity client = clientService.getClientById(id);
if (client == null) { if (client == null) {
logger.error("apiShowClient failed; client with id " + id + " could not be found."); logger.error("apiShowClient failed; client with id " + id + " could not be found.");
model.addAttribute("code", HttpStatus.NOT_FOUND); model.addAttribute("code", HttpStatus.NOT_FOUND);
model.addAttribute("errorMessage", "The requested client with id " + id + "could not be found."); model.addAttribute("errorMessage", "The requested client with id " + id + "could not be found.");
return "jsonErrorView"; return "jsonErrorView";
} }
model.addAttribute("entity", client); model.addAttribute("entity", client);
if (isAdmin(auth)) { if (isAdmin(auth)) {
return "clientEntityViewAdmins"; return "clientEntityViewAdmins";
} else { } else {
return "clientEntityViewUsers"; return "clientEntityViewUsers";
} }
} }
/** /**
* Check to see if the given auth object has ROLE_ADMIN assigned to it or not * Check to see if the given auth object has ROLE_ADMIN assigned to it or not
* @param auth * @param auth
* @return * @return
*/ */
private boolean isAdmin(Authentication auth) { private boolean isAdmin(Authentication auth) {
for (GrantedAuthority grantedAuthority : auth.getAuthorities()) { for (GrantedAuthority grantedAuthority : auth.getAuthorities()) {
if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) { if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
return true; return true;
} }
} }
return false; return false;
} }
} }

View File

@ -314,7 +314,7 @@ public class ClientDynamicRegistrationEndpoint {
* @param jsonString * @param jsonString
* @return the entity if successful, null otherwise * @return the entity if successful, null otherwise
*/ */
private ClientDetailsEntity parse(String jsonString) { private ClientDetailsEntity parse(String jsonString) {
JsonElement jsonEl = parser.parse(jsonString); JsonElement jsonEl = parser.parse(jsonString);
if (jsonEl.isJsonObject()) { if (jsonEl.isJsonObject()) {
@ -393,89 +393,89 @@ public class ClientDynamicRegistrationEndpoint {
return c; return c;
} else { } else {
return null; return null;
} }
} }
/** /**
* Gets the value of the given given member as a set of strings, null if it doesn't exist * Gets the value of the given given member as a set of strings, null if it doesn't exist
*/ */
private Set<String> getAsStringSet(JsonObject o, String member) throws JsonSyntaxException { private Set<String> getAsStringSet(JsonObject o, String member) throws JsonSyntaxException {
if (o.has(member)) { if (o.has(member)) {
return gson.fromJson(o.get(member), new TypeToken<Set<String>>(){}.getType()); return gson.fromJson(o.get(member), new TypeToken<Set<String>>(){}.getType());
} else { } else {
return null; return null;
} }
} }
/**
* Gets the value of the given member as a string, null if it doesn't exist
*/
private String getAsString(JsonObject o, String member) {
if (o.has(member)) {
JsonElement e = o.get(member);
if (e != null && e.isJsonPrimitive()) {
return e.getAsString();
} else {
return null;
}
} else {
return null;
}
}
/**
* Gets the value of the given member as a JWS Algorithm, null if it doesn't exist
*/
private JWSAlgorithmEmbed getAsJwsAlgorithm(JsonObject o, String member) {
String s = getAsString(o, member);
if (s != null) {
return JWSAlgorithmEmbed.getForAlgorithmName(s);
} else {
return null;
}
}
/**
* Gets the value of the given member as a JWE Algorithm, null if it doesn't exist
*/
private JWEAlgorithmEmbed getAsJweAlgorithm(JsonObject o, String member) {
String s = getAsString(o, member);
if (s != null) {
return JWEAlgorithmEmbed.getForAlgorithmName(s);
} else {
return null;
}
}
/**
* Gets the value of the given member as a JWE Encryption Method, null if it doesn't exist
*/
private JWEEncryptionMethodEmbed getAsJweEncryptionMethod(JsonObject o, String member) {
String s = getAsString(o, member);
if (s != null) {
return JWEEncryptionMethodEmbed.getForAlgorithmName(s);
} else {
return null;
}
}
/** /**
* @param client * Gets the value of the given member as a string, null if it doesn't exist
* @return */
* @throws AuthenticationException private String getAsString(JsonObject o, String member) {
*/ if (o.has(member)) {
private OAuth2AccessTokenEntity createRegistrationAccessToken(ClientDetailsEntity client) throws AuthenticationException { JsonElement e = o.get(member);
if (e != null && e.isJsonPrimitive()) {
return e.getAsString();
} else {
return null;
}
} else {
return null;
}
}
Map<String, String> authorizationParameters = Maps.newHashMap(); /**
authorizationParameters.put("client_id", client.getClientId()); * Gets the value of the given member as a JWS Algorithm, null if it doesn't exist
authorizationParameters.put("scope", OAuth2AccessTokenEntity.REGISTRATION_TOKEN_SCOPE); */
OAuth2Request storedRequest = new OAuth2Request(authorizationParameters, client.getClientId(), private JWSAlgorithmEmbed getAsJwsAlgorithm(JsonObject o, String member) {
Sets.newHashSet(new SimpleGrantedAuthority("ROLE_CLIENT")), true, String s = getAsString(o, member);
Sets.newHashSet(OAuth2AccessTokenEntity.REGISTRATION_TOKEN_SCOPE), null, null, null); if (s != null) {
return JWSAlgorithmEmbed.getForAlgorithmName(s);
} else {
return null;
}
}
/**
* Gets the value of the given member as a JWE Algorithm, null if it doesn't exist
*/
private JWEAlgorithmEmbed getAsJweAlgorithm(JsonObject o, String member) {
String s = getAsString(o, member);
if (s != null) {
return JWEAlgorithmEmbed.getForAlgorithmName(s);
} else {
return null;
}
}
/**
* Gets the value of the given member as a JWE Encryption Method, null if it doesn't exist
*/
private JWEEncryptionMethodEmbed getAsJweEncryptionMethod(JsonObject o, String member) {
String s = getAsString(o, member);
if (s != null) {
return JWEEncryptionMethodEmbed.getForAlgorithmName(s);
} else {
return null;
}
}
/**
* @param client
* @return
* @throws AuthenticationException
*/
private OAuth2AccessTokenEntity createRegistrationAccessToken(ClientDetailsEntity client) throws AuthenticationException {
Map<String, String> authorizationParameters = Maps.newHashMap();
authorizationParameters.put("client_id", client.getClientId());
authorizationParameters.put("scope", OAuth2AccessTokenEntity.REGISTRATION_TOKEN_SCOPE);
OAuth2Request storedRequest = new OAuth2Request(authorizationParameters, client.getClientId(),
Sets.newHashSet(new SimpleGrantedAuthority("ROLE_CLIENT")), true,
Sets.newHashSet(OAuth2AccessTokenEntity.REGISTRATION_TOKEN_SCOPE), null, null, null);
OAuth2Authentication authentication = new OAuth2Authentication(storedRequest, null); OAuth2Authentication authentication = new OAuth2Authentication(storedRequest, null);
OAuth2AccessTokenEntity registrationAccessToken = (OAuth2AccessTokenEntity) tokenService.createAccessToken(authentication); OAuth2AccessTokenEntity registrationAccessToken = (OAuth2AccessTokenEntity) tokenService.createAccessToken(authentication);
return registrationAccessToken; return registrationAccessToken;
} }
} }

View File

@ -45,17 +45,17 @@ public class JsonWebKeyEndpoint {
} }
/** /**
* @return the jwtService * @return the jwtService
*/ */
public JwtSigningAndValidationService getJwtService() { public JwtSigningAndValidationService getJwtService() {
return jwtService; return jwtService;
} }
/** /**
* @param jwtService the jwtService to set * @param jwtService the jwtService to set
*/ */
public void setJwtService(JwtSigningAndValidationService jwtService) { public void setJwtService(JwtSigningAndValidationService jwtService) {
this.jwtService = jwtService; this.jwtService = jwtService;
} }
} }

View File

@ -17,7 +17,6 @@ package org.mitre.openid.connect.web;
import java.util.Map; import java.util.Map;
import org.mitre.openid.connect.config.ConfigurationPropertiesBean;
import org.mitre.openid.connect.service.StatsService; import org.mitre.openid.connect.service.StatsService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
@ -35,41 +34,41 @@ public class ManagerController {
@Autowired @Autowired
private StatsService statsService; private StatsService statsService;
@RequestMapping({"", "home", "index"}) @RequestMapping({"", "home", "index"})
public String showHomePage(ModelMap m) { public String showHomePage(ModelMap m) {
Map<String, Integer> summary = statsService.calculateSummaryStats(); Map<String, Integer> summary = statsService.calculateSummaryStats();
m.put("statsSummary", summary); m.put("statsSummary", summary);
return "home"; return "home";
} }
@RequestMapping({"about", "about/"}) @RequestMapping({"about", "about/"})
public String showAboutPage(ModelMap m) { public String showAboutPage(ModelMap m) {
return "about"; return "about";
} }
@RequestMapping({"stats", "stats/"}) @RequestMapping({"stats", "stats/"})
public String showStatsPage(ModelMap m) { public String showStatsPage(ModelMap m) {
Map<String, Integer> summary = statsService.calculateSummaryStats(); Map<String, Integer> summary = statsService.calculateSummaryStats();
m.put("statsSummary", summary); m.put("statsSummary", summary);
return "stats"; return "stats";
} }
@RequestMapping({"contact", "contact/"}) @RequestMapping({"contact", "contact/"})
public String showContactPage(ModelMap m) { public String showContactPage(ModelMap m) {
return "contact"; return "contact";
} }
@PreAuthorize("hasRole('ROLE_USER')") // TODO: this probably shouldn't be here @PreAuthorize("hasRole('ROLE_USER')") // TODO: this probably shouldn't be here
@RequestMapping("manage/**") @RequestMapping("manage/**")
public String showClientManager(ModelMap m) { public String showClientManager(ModelMap m) {
return "manage"; return "manage";
} }
public StatsService getStatsService() { public StatsService getStatsService() {
return statsService; return statsService;

View File

@ -23,11 +23,11 @@ public class ServerConfigInterceptor extends HandlerInterceptorAdapter {
@Autowired @Autowired
private ConfigurationPropertiesBean config; private ConfigurationPropertiesBean config;
@Override @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (modelAndView != null) { // skip checking at all if we have no model and view to hand the config to if (modelAndView != null) { // skip checking at all if we have no model and view to hand the config to
modelAndView.addObject("config", config); modelAndView.addObject("config", config);
} }
} }
} }

View File

@ -54,7 +54,7 @@ public class UserInfoEndpoint {
private Map<String, String> schemaToViewNameMap = ImmutableMap.of( private Map<String, String> schemaToViewNameMap = ImmutableMap.of(
openIdSchema, jsonUserInfoViewName, openIdSchema, jsonUserInfoViewName,
pocoSchema, pocoUserInfoViewName pocoSchema, pocoUserInfoViewName
); );
// Valid schemas and associated views // Valid schemas and associated views
private static final String openIdSchema = "openid"; private static final String openIdSchema = "openid";
@ -96,11 +96,11 @@ public class UserInfoEndpoint {
} }
if (p instanceof OAuth2Authentication) { if (p instanceof OAuth2Authentication) {
OAuth2Authentication authentication = (OAuth2Authentication)p; OAuth2Authentication authentication = (OAuth2Authentication)p;
model.addAttribute("scope", authentication.getOAuth2Request().getScope()); model.addAttribute("scope", authentication.getOAuth2Request().getScope());
model.addAttribute("requestObject", authentication.getOAuth2Request().getRequestParameters().get("request")); model.addAttribute("requestObject", authentication.getOAuth2Request().getRequestParameters().get("request"));
} }
model.addAttribute("userInfo", userInfo); model.addAttribute("userInfo", userInfo);
@ -109,17 +109,17 @@ public class UserInfoEndpoint {
} }
/** /**
* @return the schemaToViewNameMap (defaults to an immutable map) * @return the schemaToViewNameMap (defaults to an immutable map)
*/ */
public Map<String, String> getSchemaToViewNameMap() { public Map<String, String> getSchemaToViewNameMap() {
return schemaToViewNameMap; return schemaToViewNameMap;
} }
/** /**
* @param schemaToViewNameMap the schemaToViewNameMap to set * @param schemaToViewNameMap the schemaToViewNameMap to set
*/ */
public void setSchemaToViewNameMap(Map<String, String> schemaToViewNameMap) { public void setSchemaToViewNameMap(Map<String, String> schemaToViewNameMap) {
this.schemaToViewNameMap = schemaToViewNameMap; this.schemaToViewNameMap = schemaToViewNameMap;
} }
} }

View File

@ -9,7 +9,6 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.mitre.openid.connect.model.UserInfo; import org.mitre.openid.connect.model.UserInfo;
import org.mitre.openid.connect.repository.UserInfoRepository;
import org.mitre.openid.connect.service.UserInfoService; import org.mitre.openid.connect.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
@ -26,26 +25,26 @@ public class UserInfoInterceptor extends HandlerInterceptorAdapter {
@Autowired @Autowired
private UserInfoService userInfoService; private UserInfoService userInfoService;
@Override @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (modelAndView != null) { // skip checking at all if we have no model and view to hand the user to if (modelAndView != null) { // skip checking at all if we have no model and view to hand the user to
// get our principal from the security context // get our principal from the security context
Principal p = request.getUserPrincipal(); Principal p = request.getUserPrincipal();
if (p != null && p.getName() != null) { // don't bother checking if we don't have a principal if (p != null && p.getName() != null) { // don't bother checking if we don't have a principal
// try to look up a user based on it // try to look up a user based on it
UserInfo user = userInfoService.getBySubject(p.getName()); UserInfo user = userInfoService.getBySubject(p.getName());
// if we have one, inject it so views can use it // if we have one, inject it so views can use it
if (user != null) { if (user != null) {
modelAndView.addObject("userInfo", user); modelAndView.addObject("userInfo", user);
} }
} }
} }
} }

View File

@ -1,8 +1,9 @@
<h2>About</h2> <h2>About</h2>
<p>This OpenID Connect service is built from the MITREid Connect
Open Source project started by The MITRE Corporation.</p>
<p> <p>
This OpenID Connect service is built from the MITREid Connect Open Source project started by The MITRE Corporation. More information about the project can be found on our GitHub page: <a
</p> href="http://github.com/mitreid-connect/">MTIREid Connect on
<p> GitHub</a> There, you can submit bug reports, give feedback, or even
More information about the project can be found on our GitHub page: <a href="http://github.com/mitreid-connect/">MTIREid Connect on GitHub</a> contribute code patches for additional features you'd like to see.
There, you can submit bug reports, give feedback, or even contribute code patches for additional features you'd like to see.
</p> </p>

View File

@ -1,12 +1,13 @@
<%@ tag language="java" pageEncoding="UTF-8"%> <%@ tag language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %> <%@ taglib prefix="security"
uri="http://www.springframework.org/security/tags"%>
<security:authorize access="hasRole('ROLE_ADMIN')"> <security:authorize access="hasRole('ROLE_ADMIN')">
<li class="nav-header">Administrative</li> <li class="nav-header">Administrative</li>
<li><a href="manage/#admin/clients">Manage Clients</a></li> <li><a href="manage/#admin/clients">Manage Clients</a></li>
<li><a href="manage/#admin/whitelists">Whitelisted Clients</a></li> <li><a href="manage/#admin/whitelists">Whitelisted Clients</a></li>
<li><a href="manage/#admin/blacklist">Blacklisted Clients</a></li> <li><a href="manage/#admin/blacklist">Blacklisted Clients</a></li>
<li><a href="manage/#admin/scope">System Scopes</a></li> <li><a href="manage/#admin/scope">System Scopes</a></li>
<li class="divider"></li> <li class="divider"></li>
</security:authorize> </security:authorize>
<li class="nav-header">Personal</li> <li class="nav-header">Personal</li>
<li><a href="manage/#user/approved">Manage Sites</a></li> <li><a href="manage/#user/approved">Manage Sites</a></li>

View File

@ -1,2 +1,2 @@
<%@attribute name="crumb" required="false" %> <%@attribute name="crumb" required="false"%>
<div id="breadcrumbs"></div> <div id="breadcrumbs"></div>

View File

@ -1,6 +1,9 @@
<h2>Contact</h2> <h2>Contact</h2>
<p> <p>
For general assistance, email Bob at <a href="mailto:email@address.com?Subject=OIDC%20Server%20Assistance">email@address.com</a>. For general assistance, email Bob at <a
To offer feedback, email Sue at <a href="mailto:email@address.com?Subject=OIDC%20Server%20Feedback">email@address.com</a>. href="mailto:email@address.com?Subject=OIDC%20Server%20Assistance">email@address.com</a>.
To report a system failure or bug report, email Joe at <a href="mailto:email@address.com?Subject=OIDC%20Server%20Failure">email@address.com</a>. To offer feedback, email Sue at <a
href="mailto:email@address.com?Subject=OIDC%20Server%20Feedback">email@address.com</a>.
To report a system failure or bug report, email Joe at <a
href="mailto:email@address.com?Subject=OIDC%20Server%20Failure">email@address.com</a>.
</p> </p>

View File

@ -1 +1,3 @@
Powered by <a href="https://github.com/mitreid-connect/">MITREid Connect</a> &copy; 2013 The MITRE Corporation. Powered by
<a href="https://github.com/mitreid-connect/">MITREid Connect</a>
&copy; 2013 The MITRE Corporation.

View File

@ -1,28 +1,33 @@
<%@attribute name="js" required="false" %> <%@attribute name="js" required="false"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="o" tagdir="/WEB-INF/tags" %> <%@ taglib prefix="o" tagdir="/WEB-INF/tags"%>
<div id="push"></div> <div id="push"></div>
</div> <!-- end #wrap --> </div>
<!-- end #wrap -->
<div id="footer"> <div id="footer">
<div class="container"> <div class="container">
<p class="muted credit"><o:copyright /></p> <p class="muted credit">
</div> <o:copyright />
</p>
</div>
</div> </div>
<!-- Le javascript <!-- Le javascript
================================================== --> ================================================== -->
<!-- Placed at the end of the document so the pages load faster --> <!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="resources/bootstrap2/js/bootstrap.js"></script> <script type="text/javascript"
src="resources/bootstrap2/js/bootstrap.js"></script>
<script type="text/javascript" src="resources/js/lib/underscore.js"></script> <script type="text/javascript" src="resources/js/lib/underscore.js"></script>
<script type="text/javascript" src="resources/js/lib/backbone.js"></script> <script type="text/javascript" src="resources/js/lib/backbone.js"></script>
<script type="text/javascript" src="resources/js/lib/purl.js"></script> <script type="text/javascript" src="resources/js/lib/purl.js"></script>
<script type="text/javascript" src="resources/js/lib/bootstrapx-clickover.js"></script> <script type="text/javascript"
src="resources/js/lib/bootstrapx-clickover.js"></script>
<c:if test="${js != null && js != ''}"> <c:if test="${js != null && js != ''}">
<script type="text/javascript" src="resources/js/client.js"></script> <script type="text/javascript" src="resources/js/client.js"></script>
<script type="text/javascript" src="resources/js/grant.js"></script> <script type="text/javascript" src="resources/js/grant.js"></script>
<script type="text/javascript" src="resources/js/scope.js"></script> <script type="text/javascript" src="resources/js/scope.js"></script>
<script type="text/javascript" src="resources/js/whitelist.js"></script> <script type="text/javascript" src="resources/js/whitelist.js"></script>
<script type="text/javascript" src="resources/js/admin.js"></script> <script type="text/javascript" src="resources/js/admin.js"></script>
</c:if> </c:if>
</body> </body>
</html> </html>

View File

@ -1,119 +1,123 @@
<%@attribute name="title" required="false" %> <%@attribute name="title" required="false"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<c:set var="url">${pageContext.request.requestURL}</c:set> <c:set var="url">${pageContext.request.requestURL}</c:set>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(pageContext.request.requestURI))}${pageContext.request.contextPath}/" /> <base
href="${fn:substring(url, 0, fn:length(url) - fn:length(pageContext.request.requestURI))}${pageContext.request.contextPath}/" />
<meta charset="utf-8"> <meta charset="utf-8">
<title>OpenID Connect - ${title}</title> <title>OpenID Connect - ${title}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content=""> <meta name="description" content="">
<meta name="author" content=""> <meta name="author" content="">
<!-- Le styles --> <!-- Le styles -->
<link href="resources/bootstrap2/css/bootstrap.min.css" rel="stylesheet"> <link href="resources/bootstrap2/css/bootstrap.min.css" rel="stylesheet">
<style type="text/css"> <style type="text/css">
html,body {
height: 100%;
/* The html and body elements cannot have any padding or margin. */
}
html, .sidebar-nav {
body { padding: 9px 0;
height: 100%; }
/* The html and body elements cannot have any padding or margin. */
}
.sidebar-nav { h1,label {
padding: 9px 0; text-shadow: 1px 1px 1px #FFFFFF;
} }
h1,label { .brand {
text-shadow: 1px 1px 1px #FFFFFF; padding-left: 35px !important;
} }
.brand { /* Wrapper for page content to push down footer */
padding-left: 35px !important; #wrap {
} min-height: 100%;
height: auto !important;
height: 100%;
/* Negative indent footer by it's height */
margin: 0 auto -60px;
}
/* Wrapper for page content to push down footer */ /* Set the fixed height of the footer here */
#wrap { #push,#footer {
min-height: 100%; min-height: 60px;
height: auto !important; }
height: 100%;
/* Negative indent footer by it's height */
margin: 0 auto -60px;
}
/* Set the fixed height of the footer here */ #footer {
#push, background-color: #f5f5f5;
#footer { }
min-height: 60px;
}
#footer {
background-color: #f5f5f5;
}
.main { .main {
padding-top: 60px; padding-top: 60px;
} }
.credit { .credit {
margin: 20px 0; margin: 20px 0;
} }
.inputError { .inputError {
border: 1px solid #b94a48 !important; border: 1px solid #b94a48 !important;
} }
a.brand { a.brand {
background: url('${config.logoImageUrl}') no-repeat scroll 7px 7px transparent; background: url('${config.logoImageUrl}') no-repeat scroll 7px 7px
} transparent;
</style> }
<link href="resources/bootstrap2/css/bootstrap-responsive.css" rel="stylesheet"> </style>
<style type="text/css"> <link href="resources/bootstrap2/css/bootstrap-responsive.css"
@media (min-width: 768px) and (max-width: 979px) { rel="stylesheet">
.main { <style type="text/css">
padding-top: 0px; @media ( min-width : 768px) and (max-width: 979px) {
} .main {
padding-top: 0px;
}
}
} @media ( max-width : 767px) {
#footer {
margin-left: -20px;
margin-right: -20px;
padding-left: 20px;
padding-right: 20px;
}
}
</style>
@media (max-width: 767px) { <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
#footer { <!--[if lt IE 9]>
margin-left: -20px;
margin-right: -20px;
padding-left: 20px;
padding-right: 20px;
}
}
</style>
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]--> <![endif]-->
<!-- Le fav and touch icons --> <!-- Le fav and touch icons -->
<link rel="shortcut icon" href="../bootstrap2/ico/favicon.ico"> <link rel="shortcut icon" href="../bootstrap2/ico/favicon.ico">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="../bootstrap2/ico/apple-touch-icon-114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114"
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="../bootstrap2/ico/apple-touch-icon-72-precomposed.png"> href="../bootstrap2/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="../bootstrap2/ico/apple-touch-icon-57-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72"
href="../bootstrap2/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed"
href="../bootstrap2/ico/apple-touch-icon-57-precomposed.png">
<!-- Load jQuery up here so that we can use in-page functions --> <!-- Load jQuery up here so that we can use in-page functions -->
<script type="text/javascript" src="resources/js/lib/jquery.js"></script> <script type="text/javascript" src="resources/js/lib/jquery.js"></script>
</head> </head>
<body> <body>
<div id="modalAlert" class="modal hide fade"> <div id="modalAlert" class="modal hide fade">
<div class="alert alert-error"> <div class="alert alert-error">
<strong>Warning!</strong> <strong>Warning!</strong>
<div class="modal-body"></div> <div class="modal-body"></div>
</div>
<div class="modal-footer">
<button class="btn primary" type="button"
onclick="$('#modalAlert').modal('hide');">OK</button>
</div>
</div> </div>
<div class="modal-footer"><button class="btn primary" type="button" onclick="$('#modalAlert').modal('hide');">OK</button></div>
</div>
<div id="wrap"> <div id="wrap">

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