@Post
  public Representation token(final Representation entity) throws OAuth2RestletException {

    final OAuth2Request request = requestFactory.create(getRequest());

    try {
      final AccessToken accessToken = accessTokenService.requestAccessToken(request);
      return new JacksonRepresentation<Map<String, Object>>(accessToken.toMap());
    } catch (InvalidGrantException e) {
      throw new OAuth2RestletException(
          e.getStatusCode(),
          e.getError(),
          "Assertion is invalid.",
          request.<String>getParameter("redirect_uri"),
          request.<String>getParameter("state"));
    } catch (ClientAuthenticationFailedException e) {
      getResponse()
          .setChallengeRequests(
              singletonList(
                  new ChallengeRequest(
                      ChallengeScheme.valueOf(
                          SUPPORTED_RESTLET_CHALLENGE_SCHEMES.get(e.getChallengeScheme())),
                      e.getChallengeRealm())));
      throw new OAuth2RestletException(
          e.getStatusCode(), e.getError(), e.getMessage(), request.<String>getParameter("state"));
    } catch (OAuth2Exception e) {
      throw new OAuth2RestletException(
          e.getStatusCode(),
          e.getError(),
          e.getMessage(),
          request.<String>getParameter("redirect_uri"),
          request.<String>getParameter("state"));
    }
  }
  private boolean isEntitled(
      UmaProviderSettings umaProviderSettings,
      PermissionTicket permissionTicket,
      AccessToken authorisationApiToken)
      throws EntitlementException, ServerException {
    String realm = permissionTicket.getRealm();
    String resourceSetId = permissionTicket.getResourceSetId();
    String resourceName = UmaConstants.UMA_POLICY_SCHEME;
    Subject resourceOwnerSubject;
    try {
      ResourceSetStore store =
          oauth2ProviderSettingsFactory
              .get(requestFactory.create(getRequest()))
              .getResourceSetStore();
      Set<ResourceSetDescription> results =
          store.query(
              org.forgerock.util.query.QueryFilter.equalTo(
                  ResourceSetTokenField.RESOURCE_SET_ID, resourceSetId));
      if (results.size() != 1) {
        throw new NotFoundException("Could not find Resource Set, " + resourceSetId);
      }
      resourceName += results.iterator().next().getId();
      resourceOwnerSubject =
          UmaUtils.createSubject(
              createIdentity(results.iterator().next().getResourceOwnerId(), realm));
    } catch (NotFoundException e) {
      debug.message("Couldn't find resource that permission ticket is registered for", e);
      throw new ServerException("Couldn't find resource that permission ticket is registered for");
    }
    Subject requestingPartySubject =
        UmaUtils.createSubject(createIdentity(authorisationApiToken.getResourceOwnerId(), realm));

    // Implicitly grant access to the resource owner
    if (isRequestingPartyResourceOwner(requestingPartySubject, resourceOwnerSubject)) {
      return true;
    }

    List<Entitlement> entitlements =
        umaProviderSettings
            .getPolicyEvaluator(
                requestingPartySubject, permissionTicket.getClientId().toLowerCase())
            .evaluate(realm, requestingPartySubject, resourceName, null, false);

    Set<String> requestedScopes = permissionTicket.getScopes();
    Set<String> requiredScopes = new HashSet<String>(requestedScopes);
    for (Entitlement entitlement : entitlements) {
      for (String requestedScope : requestedScopes) {
        final Boolean actionValue = entitlement.getActionValue(requestedScope);
        if (actionValue != null && actionValue) {
          requiredScopes.remove(requestedScope);
        }
      }
    }

    return requiredScopes.isEmpty();
  }
 protected AccessToken getAuthorisationApiToken() throws ServerException {
   Request req = getRequest();
   ChallengeResponse challengeResponse = req.getChallengeResponse();
   try {
     return oauth2TokenStore.readAccessToken(
         requestFactory.create(req), challengeResponse.getRawValue());
   } catch (InvalidGrantException e) {
     throw new ServerException("Unable to verify client identity.");
   }
 }
  /**
   * Wraps the introspection service in a Restlet API.
   *
   * @param body The body - this is ignored but needs to be present to be made available in the
   *     request.
   * @return A JSON representation of the introspection result.
   * @throws org.forgerock.oauth2.restlet.OAuth2RestletException
   */
  @Post("form")
  @Get
  public Representation introspect(Representation body) throws OAuth2RestletException {

    final OAuth2Request request = requestFactory.create(getRequest());

    try {
      return new JsonRepresentation(tokenIntrospectionService.introspect(request).asMap());
    } catch (OAuth2Exception e) {
      throw new OAuth2RestletException(e.getStatusCode(), e.getError(), e.getMessage(), null);
    }
  }
 private String getResourceOwnerId(String resourceSetId) throws NotFoundException, UmaException {
   OAuth2ProviderSettings providerSettings =
       oauth2ProviderSettingsFactory.get(requestFactory.create(getRequest()));
   ResourceSetDescription resourceSetDescription = getResourceSet(resourceSetId, providerSettings);
   return resourceSetDescription.getResourceOwnerId();
 }