private Pair<SessionId, AuthorizationGrant> endSession(
      String idTokenHint,
      String sessionId,
      HttpServletRequest httpRequest,
      HttpServletResponse httpResponse,
      SecurityContext sec) {

    EndSessionParamsValidator.validateParams(idTokenHint, errorResponseFactory);

    AuthorizationGrant authorizationGrant =
        authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
    if (authorizationGrant == null) {
      log.info("Failed to find out authorization grant for id_token_hing '{0}'", idTokenHint);
      errorResponseFactory.throwUnauthorizedException(EndSessionErrorResponseType.INVALID_GRANT);
    }

    boolean isExternalLogoutPresent = false;
    boolean externalLogoutResult = false;
    SessionId ldapSessionId = removeSessionId(sessionId, httpRequest, httpResponse);

    isExternalLogoutPresent = externalApplicationSessionService.isEnabled();
    if (isExternalLogoutPresent) {
      externalLogoutResult =
          externalApplicationSessionService.executeExternalEndSessionMethods(
              httpRequest, authorizationGrant);
      log.info(
          "End session result for '{0}': '{1}'",
          authorizationGrant.getUser().getUserId(), "logout", externalLogoutResult);
    }

    boolean isGrantAndExternalLogoutSuccessful = isExternalLogoutPresent && externalLogoutResult;
    if (isExternalLogoutPresent && !isGrantAndExternalLogoutSuccessful) {
      errorResponseFactory.throwUnauthorizedException(EndSessionErrorResponseType.INVALID_GRANT);
    }

    authorizationGrant.revokeAllTokens();

    return new Pair<SessionId, AuthorizationGrant>(ldapSessionId, authorizationGrant);
  }
  @POST
  @Consumes({UmaConstants.JSON_MEDIA_TYPE})
  @Produces({UmaConstants.JSON_MEDIA_TYPE})
  @ApiOperation(
      value = "Registers permission using the POST method",
      consumes = UmaConstants.JSON_MEDIA_TYPE,
      produces = UmaConstants.JSON_MEDIA_TYPE,
      notes =
          "The resource server uses the POST method at the endpoint. The body of the HTTP request message contains a JSON object providing the requested permission, using a format derived from the scope description format specified in [OAuth-resource-reg], as follows. The object has the following properties:")
  @ApiResponses(
      value = {
        @ApiResponse(code = 401, message = "Unauthorized"),
        @ApiResponse(code = 400, message = "Bad Request")
      })
  public Response registerResourceSetPermission(
      @Context HttpServletRequest request,
      @HeaderParam("Authorization") String authorization,
      @HeaderParam("Host") String amHost,
      @ApiParam(
              value =
                  "The identifier for a resource set to which this client is seeking access. The identifier MUST correspond to a resource set that was previously registered.",
              required = true)
          RegisterPermissionRequest resourceSetPermissionRequest) {
    try {
      umaValidationService.validateAuthorizationWithProtectScope(authorization);
      String validatedAmHost = umaValidationService.validateAmHost(amHost);
      umaValidationService.validateAuthorizationWithProtectScope(authorization);
      umaValidationService.validateResourceSet(resourceSetPermissionRequest);

      return registerResourceSetPermissionImpl(
          request, authorization, validatedAmHost, resourceSetPermissionRequest);
    } catch (Exception ex) {
      if (ex instanceof WebApplicationException) {
        throw (WebApplicationException) ex;
      }

      log.error("Exception happened", ex);
      throw new WebApplicationException(
          Response.status(Response.Status.INTERNAL_SERVER_ERROR)
              .entity(
                  errorResponseFactory.getUmaJsonErrorResponse(UmaErrorResponseType.SERVER_ERROR))
              .build());
    }
  }
Esempio n. 3
0
  private void handleExternalScopes(List<String> p_scopeUrls, List<String> result)
      throws LDAPException {
    for (String scopeUrl : p_scopeUrls) {
      final Filter filter = Filter.create(String.format("&(oxUrl=%s)", scopeUrl));
      final List<ScopeDescription> entries =
          ldapEntryManager.findEntries(baseDn(), ScopeDescription.class, filter);
      if (entries != null && !entries.isEmpty()) {
        result.add(entries.get(0).getDn());
      } else { // scope is not in ldap, add it dynamically

        final Boolean addAutomatically =
            ConfigurationFactory.instance().getConfiguration().getUmaAddScopesAutomatically();

        if (addAutomatically != null && addAutomatically) {
          final String inum = inumService.generateInum();
          final ScopeDescription newScope = new ScopeDescription();
          newScope.setInum(inum);
          newScope.setUrl(scopeUrl);
          newScope.setDisplayName(
              scopeUrl); // temp solution : need extract info from scope description on resource
                         // server
          newScope.setId(
              UmaScopeType.EXTERNAL_AUTO
                  .getValue()); // dummy id : not sure what to put right now as id is required by
                                // @NotNull annotation
          newScope.setType(InternalExternal.EXTERNAL_AUTO);

          final boolean persisted = persist(newScope);
          if (persisted) {
            result.add(newScope.getDn());
          }
        } else {
          throw new WebApplicationException(
              Response.status(Response.Status.BAD_REQUEST)
                  .entity(
                      errorResponseFactory.getUmaJsonErrorResponse(
                          UmaErrorResponseType.INVALID_RESOURCE_SET_SCOPE))
                  .build());
        }
      }
    }
  }
  @Override
  public Response requestEndSession(
      String idTokenHint,
      String postLogoutRedirectUri,
      String state,
      String sessionId,
      HttpServletRequest httpRequest,
      HttpServletResponse httpResponse,
      SecurityContext sec) {

    log.debug(
        "Attempting to end session, idTokenHint: {0}, postLogoutRedirectUri: {1}, sessionId: {2}, Is Secure = {3}",
        idTokenHint, postLogoutRedirectUri, sessionId, sec.isSecure());

    EndSessionParamsValidator.validateParams(
        idTokenHint, postLogoutRedirectUri, errorResponseFactory);

    final Pair<SessionId, AuthorizationGrant> pair =
        endSession(idTokenHint, sessionId, httpRequest, httpResponse, sec);

    // Validate redirectUri
    String redirectUri =
        redirectionUriService.validatePostLogoutRedirectUri(
            pair.getSecond().getClient().getClientId(), postLogoutRedirectUri);

    if (StringUtils.isNotBlank(redirectUri)) {
      RedirectUri redirectUriResponse = new RedirectUri(redirectUri);
      if (StringUtils.isNotBlank(state)) {
        redirectUriResponse.addResponseParameter(EndSessionResponseParam.STATE, state);
      }

      return RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest).build();
    } else {
      errorResponseFactory.throwBadRequestException(EndSessionErrorResponseType.INVALID_REQUEST);
    }
    return Response.ok().build();
  }
  @Override
  public Response requestEndSession(
      String idTokenHint,
      String postLogoutRedirectUri,
      String state,
      String sessionId,
      HttpServletRequest httpRequest,
      HttpServletResponse httpResponse,
      SecurityContext sec) {
    log.debug(
        "Attempting to end session, idTokenHint: {0}, postLogoutRedirectUri: {1}, sessionId: {2}, Is Secure = {3}",
        idTokenHint, postLogoutRedirectUri, sessionId, sec.isSecure());
    Response.ResponseBuilder builder = Response.ok();

    if (!EndSessionParamsValidator.validateParams(idTokenHint, postLogoutRedirectUri)) {
      builder = Response.status(400);
      builder.entity(
          errorResponseFactory.getErrorAsJson(EndSessionErrorResponseType.INVALID_REQUEST));
    } else {
      AuthorizationGrant authorizationGrant =
          authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
      boolean isExternalAuthenticatorLogoutPresent = false;
      boolean externalLogoutResult = false;
      if (authorizationGrant != null) {
        removeSessionId(sessionId, httpRequest, httpResponse);

        isExternalAuthenticatorLogoutPresent = externalApplicationSessionService.isEnabled();
        if (isExternalAuthenticatorLogoutPresent) {
          externalLogoutResult =
              externalApplicationSessionService.executeExternalEndSessionMethods(
                  httpRequest, authorizationGrant);
          log.info(
              "End session result for '{0}': '{1}'",
              authorizationGrant.getUser().getUserId(), "logout", externalLogoutResult);
        }
      }
      boolean isGrantAndNoExternalLogout =
          authorizationGrant != null && !isExternalAuthenticatorLogoutPresent;
      boolean isGrantAndExternalLogoutSuccessful =
          authorizationGrant != null
              && isExternalAuthenticatorLogoutPresent
              && externalLogoutResult;
      if (isGrantAndNoExternalLogout || isGrantAndExternalLogoutSuccessful) {
        authorizationGrant.revokeAllTokens();

        // Validate redirectUri
        String redirectUri =
            redirectionUriService.validatePostLogoutRedirectUri(
                authorizationGrant.getClient().getClientId(), postLogoutRedirectUri);

        if (StringUtils.isNotBlank(redirectUri)) {
          RedirectUri redirectUriResponse = new RedirectUri(redirectUri);
          if (StringUtils.isNotBlank(state)) {
            redirectUriResponse.addResponseParameter(EndSessionResponseParam.STATE, state);
          }

          builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
        } else {
          builder = Response.status(400);
          builder.entity(
              errorResponseFactory.getErrorAsJson(EndSessionErrorResponseType.INVALID_REQUEST));
        }
      } else {
        builder = Response.status(401);
        builder.entity(
            errorResponseFactory.getErrorAsJson(EndSessionErrorResponseType.INVALID_GRANT));
      }
    }
    return builder.build();
  }