use of oidc.model.OpenIDClient in project OpenConext-oidcng by OpenConext.
the class AuthorizationEndpoint method doConsent.
private ModelAndView doConsent(MultiValueMap<String, String> parameters, OpenIDClient client, Set<String> scopes, List<OpenIDClient> resourceServers) {
Map<String, Object> body = new HashMap<>();
body.put("parameters", parameters.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().get(0))));
body.put("client", client);
body.put("resourceServers", resourceServers.stream().filter(rs -> StringUtils.hasText(rs.getLogoUrl())).collect(toList()));
body.put("scopes", resourceServers.stream().map(OpenIDClient::getScopes).flatMap(List::stream).filter(scope -> scopes.contains(scope.getName().toLowerCase())).collect(Collectors.toSet()));
Locale locale = LocaleContextHolder.getLocale();
body.put("lang", locale.getLanguage());
body.put("environment", environment);
return new ModelAndView("consent", body);
}
use of oidc.model.OpenIDClient in project OpenConext-oidcng by OpenConext.
the class AuthorizationEndpoint method validateRedirectionURI.
public static ProvidedRedirectURI validateRedirectionURI(URI redirectionURI, OpenIDClient client) throws UnsupportedEncodingException {
List<String> registeredRedirectUrls = client.getRedirectUrls();
if (registeredRedirectUrls == null) {
throw new IllegalArgumentException(String.format("Client %s must have at least one redirectURI configured to use the Authorization flow", client.getClientId()));
}
if (redirectionURI == null) {
return registeredRedirectUrls.stream().findFirst().map(s -> new ProvidedRedirectURI(s, false)).orElseThrow(() -> new IllegalArgumentException(String.format("Client %s must have at least one redirectURI configured to use the Authorization flow", client.getClientId())));
}
String redirectURI = URLDecoder.decode(redirectionURI.toString(), "UTF-8");
Optional<ProvidedRedirectURI> optionalProvidedRedirectURI = registeredRedirectUrls.stream().map(url -> new ProvidedRedirectURI(url, true)).filter(providedRedirectURI -> providedRedirectURI.equalsIgnorePort(redirectURI)).findFirst();
if (!optionalProvidedRedirectURI.isPresent()) {
throw new RedirectMismatchException(String.format("Client %s with registered redirect URI's %s requested authorization with redirectURI %s", client.getClientId(), registeredRedirectUrls, redirectURI));
}
return optionalProvidedRedirectURI.get();
}
use of oidc.model.OpenIDClient in project OpenConext-oidcng by OpenConext.
the class IntrospectEndpoint method introspect.
@PostMapping(value = { "oidc/introspect" }, consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE })
public ResponseEntity<Map<String, Object>> introspect(HttpServletRequest request) throws ParseException, IOException, java.text.ParseException {
HTTPRequest httpRequest = ServletUtils.createHTTPRequest(request);
TokenIntrospectionRequest tokenIntrospectionRequest = TokenIntrospectionRequest.parse(httpRequest);
ClientAuthentication clientAuthentication = tokenIntrospectionRequest.getClientAuthentication();
String accessTokenValue = tokenIntrospectionRequest.getToken().getValue();
// https://tools.ietf.org/html/rfc7662 is vague about the authorization requirements, but we enforce basic auth
if (!(clientAuthentication instanceof PlainClientSecret)) {
LOG.warn("No authentication present");
throw new UnauthorizedException("Invalid user / secret");
}
String clientId = clientAuthentication.getClientID().getValue();
OpenIDClient resourceServer = openIDClientRepository.findOptionalByClientId(clientId).orElseThrow(() -> new UnknownClientException(clientId));
MDCContext.mdcContext("action", "Introspect", "rp", resourceServer.getClientId(), "accessTokenValue", accessTokenValue);
if (!secretsMatch((PlainClientSecret) clientAuthentication, resourceServer)) {
LOG.warn("Secret does not match for RS " + resourceServer.getClientId());
throw new UnauthorizedException("Invalid user / secret");
}
if (!resourceServer.isResourceServer()) {
LOG.warn("RS required for not configured for RP " + resourceServer.getClientId());
throw new UnauthorizedException("Requires ResourceServer");
}
Optional<SignedJWT> optionalSignedJWT = tokenGenerator.parseAndValidateSignedJWT(accessTokenValue);
if (!optionalSignedJWT.isPresent()) {
LOG.warn("Invalid access_token " + accessTokenValue);
return ResponseEntity.ok(Collections.singletonMap("active", false));
}
SignedJWT signedJWT = optionalSignedJWT.get();
String jwtId = signedJWT.getJWTClaimsSet().getJWTID();
Optional<AccessToken> optionalAccessToken = accessTokenRepository.findByJwtId(jwtId);
if (!optionalAccessToken.isPresent()) {
LOG.warn("No access_token found " + accessTokenValue);
return ResponseEntity.ok(Collections.singletonMap("active", false));
}
AccessToken accessToken = optionalAccessToken.get();
if (accessToken.isExpired(Clock.systemDefaultZone())) {
LOG.warn("Access token is expired " + accessTokenValue);
return ResponseEntity.ok(Collections.singletonMap("active", false));
}
List<String> scopes = accessToken.getScopes();
Map<String, Object> result = new TreeMap<>();
boolean isUserAccessToken = !accessToken.isClientCredentials();
if (isUserAccessToken) {
OpenIDClient openIDClient = openIDClientRepository.findOptionalByClientId(accessToken.getClientId()).orElseThrow(() -> new UnknownClientException(accessToken.getClientId()));
if (!openIDClient.getClientId().equals(resourceServer.getClientId()) && !openIDClient.getAllowedResourceServers().contains(resourceServer.getClientId())) {
throw new UnauthorizedException(String.format("RP %s is not allowed to use the API of resource server %s. Allowed resource servers are %s", accessToken.getClientId(), resourceServer.getClientId(), openIDClient.getAllowedResourceServers()));
}
User user = tokenGenerator.decryptAccessTokenWithEmbeddedUserInfo(signedJWT);
result.put("updated_at", user.getUpdatedAt());
if (resourceServer.isIncludeUnspecifiedNameID()) {
result.put("unspecified_id", user.getUnspecifiedNameId());
}
result.put("authenticating_authority", user.getAuthenticatingAuthority());
result.put("sub", user.getSub());
result.putAll(user.getAttributes());
List<String> acrClaims = user.getAcrClaims();
if (!CollectionUtils.isEmpty(acrClaims)) {
result.put("acr", String.join(" ", acrClaims));
}
boolean validPseudonymisation = validPseudonymisation(result, resourceServer, openIDClient);
if (!validPseudonymisation && enforceEduidResourceServerLinkedAccount) {
LOG.warn(String.format("Pseudonymisation failed. No eduperson_principal_name for RS %s", resourceServer.getClientId()));
return ResponseEntity.ok(Collections.singletonMap("active", false));
}
}
// The following claims can not be overridden by the
result.put("active", true);
result.put("scope", String.join(" ", scopes));
result.put("client_id", accessToken.getClientId());
result.put("exp", accessToken.getExpiresIn().getTime() / 1000L);
result.put("sub", accessToken.getSub());
result.put("iss", issuer);
result.put("token_type", "Bearer");
LOG.debug(String.format("Returning introspect active %s for RS %s", true, resourceServer.getClientId()));
return ResponseEntity.ok(result);
}
use of oidc.model.OpenIDClient in project OpenConext-oidcng by OpenConext.
the class TokenEndpoint method token.
@PostMapping(value = "oidc/token", consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE })
public ResponseEntity token(HttpServletRequest request) throws IOException, ParseException, JOSEException, java.text.ParseException, CertificateException, BadJOSEException {
HTTPRequest httpRequest = ServletUtils.createHTTPRequest(request);
TokenRequest tokenRequest = TokenRequest.parse(httpRequest);
ClientAuthentication clientAuthentication = tokenRequest.getClientAuthentication();
if (clientAuthentication != null && !(clientAuthentication instanceof PlainClientSecret || clientAuthentication instanceof JWTAuthentication)) {
throw new IllegalArgumentException(String.format("Unsupported '%s' findByClientId authentication in token endpoint", clientAuthentication.getClass()));
}
AuthorizationGrant authorizationGrant = tokenRequest.getAuthorizationGrant();
if (clientAuthentication == null && authorizationGrant instanceof AuthorizationCodeGrant && ((AuthorizationCodeGrant) authorizationGrant).getCodeVerifier() == null) {
throw new CodeVerifierMissingException("code_verifier required without client authentication");
}
String clientId = clientAuthentication != null ? clientAuthentication.getClientID().getValue() : tokenRequest.getClientID().getValue();
OpenIDClient client = openIDClientRepository.findOptionalByClientId(clientId).orElseThrow(() -> new UnknownClientException(clientId));
if (clientAuthentication == null && !client.isPublicClient()) {
throw new UnauthorizedException("Non-public client requires authentication");
}
if (clientAuthentication != null) {
if (clientAuthentication instanceof PlainClientSecret && !secretsMatch((PlainClientSecret) clientAuthentication, client)) {
throw new UnauthorizedException("Invalid user / secret");
} else if (clientAuthentication instanceof JWTAuthentication && !verifySignature((JWTAuthentication) clientAuthentication, client, this.tokenEndpoint)) {
throw new UnauthorizedException("Invalid user / signature");
}
}
MDCContext.mdcContext("action", "Token", "rp", clientId, "grant", authorizationGrant.getType().getValue());
if (!client.getGrants().contains(authorizationGrant.getType().getValue())) {
throw new InvalidGrantException("Invalid grant: " + authorizationGrant.getType().getValue());
}
if (authorizationGrant instanceof AuthorizationCodeGrant) {
return handleAuthorizationCodeGrant((AuthorizationCodeGrant) authorizationGrant, client);
} else if (authorizationGrant instanceof ClientCredentialsGrant) {
return handleClientCredentialsGrant(client, tokenRequest);
} else if (authorizationGrant instanceof RefreshTokenGrant) {
return handleRefreshCodeGrant((RefreshTokenGrant) authorizationGrant, client);
}
throw new IllegalArgumentException("Not supported - yet - authorizationGrant " + authorizationGrant.getType().getValue());
}
use of oidc.model.OpenIDClient in project OpenConext-oidcng by OpenConext.
the class TokenController method convertToken.
private Map<String, Object> convertToken(AccessToken token) {
Map<String, Object> result = new HashMap<>();
result.put("id", token.getId());
Optional<OpenIDClient> optionalClient = openIDClientRepository.findOptionalByClientId(token.getClientId());
if (!optionalClient.isPresent()) {
return result;
}
OpenIDClient openIDClient = optionalClient.get();
result.put("clientId", openIDClient.getClientId());
result.put("clientName", openIDClient.getName());
List<OpenIDClient> resourceServers = openIDClient.getAllowedResourceServers().stream().map(rs -> openIDClientRepository.findOptionalByClientId(rs)).filter(Optional::isPresent).map(Optional::get).collect(toList());
result.put("audiences", resourceServers.stream().map(OpenIDClient::getName));
result.put("createdAt", token.getCreatedAt());
result.put("expiresIn", token.getExpiresIn());
result.put("type", token instanceof RefreshToken ? TokenType.REFRESH : TokenType.ACCESS);
Map<String, Scope> allScopes = resourceServers.stream().map(OpenIDClient::getScopes).flatMap(List::stream).filter(distinctByKey(Scope::getName)).collect(toMap(Scope::getName, s -> s));
List<Scope> scopes = token.getScopes().stream().filter(name -> !name.equalsIgnoreCase("openid")).map(allScopes::get).filter(Objects::nonNull).collect(toList());
result.put("scopes", scopes);
return result;
}
Aggregations