org.eclipse.che.api.core.UnauthorizedException Java Examples

The following examples show how to use org.eclipse.che.api.core.UnauthorizedException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Fabric8AuthServiceClient.java    From rh-che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Return account linking url for user. Note that this does not return the fabric8 auth linking
 * URL, but instead makes a request to that url and returns the redirect obtained from there. This
 * is because requests to fabric8 auth need the Authorization header, and a user's browser will
 * not include this header by default, so returning the direct URL does not work.
 */
@Override
public String getAccountLinkingURL(
    String token, String oauthProvider, String redirectAfterLogin) {
  String linkingEndpoint =
      UriBuilder.fromUri(githubLinkEndpoint)
          .queryParam("redirect", redirectAfterLogin)
          .build()
          .toString();
  try {
    String redirectLocationJson = doRequest(linkingEndpoint, HttpMethod.GET, null);
    String redirectLocation =
        gson.<Map<String, String>>fromJson(redirectLocationJson, Map.class)
            .get("redirect_location");
    return redirectLocation;
  } catch (ServerException
      | ForbiddenException
      | NotFoundException
      | UnauthorizedException
      | BadRequestException
      | IOException e) {
    return null;
  }
}
 
Example #2
Source File: KeycloakServiceClient.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets auth token from given identity provider.
 *
 * @param oauthProvider provider name
 * @return KeycloakTokenResponse token response
 * @throws ForbiddenException when HTTP request was forbidden
 * @throws BadRequestException when HTTP request considered as bad
 * @throws IOException when unable to parse error response
 * @throws NotFoundException when requested URL not found
 * @throws ServerException when other error occurs
 * @throws UnauthorizedException when no token present for user or user not linked to provider
 */
public KeycloakTokenResponse getIdentityProviderToken(String oauthProvider)
    throws ForbiddenException, BadRequestException, IOException, NotFoundException,
        ServerException, UnauthorizedException {
  String url =
      UriBuilder.fromUri(keycloakSettings.get().get(AUTH_SERVER_URL_SETTING))
          .path("/realms/{realm}/broker/{provider}/token")
          .build(keycloakSettings.get().get(REALM_SETTING), oauthProvider)
          .toString();
  try {
    String response = doRequest(url, HttpMethod.GET, null);
    // Successful answer is not a json, but key=value&foo=bar format pairs
    return DtoFactory.getInstance()
        .createDtoFromJson(toJson(response), KeycloakTokenResponse.class);
  } catch (BadRequestException e) {
    if (assotiateUserPattern.matcher(e.getMessage()).matches()) {
      // If user has no link with identity provider yet,
      // we should threat this as unauthorized and send to OAuth login page.
      throw new UnauthorizedException(e.getMessage());
    }
    throw e;
  }
}
 
Example #3
Source File: IdentityProviderConfigFactoryTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testRethrowOnUnauthorizedException() throws Exception {
  doThrow(
          new UnauthorizedException(
              DtoFactory.newDto(ServiceError.class).withMessage("Any other message")))
      .when(keycloakServiceClient)
      .getIdentityProviderToken(anyString());
  try {
    configBuilder.buildConfig(defaultConfig, A_WORKSPACE_ID);
  } catch (InfrastructureException e) {
    assertEquals(e.getMessage(), SHOULD_LINK_ERROR_MESSAGE, "The exception message is wrong");
    return;
  }
  fail(
      "Should have thrown an exception with the following message: " + SHOULD_LINK_ERROR_MESSAGE);
}
 
Example #4
Source File: EmbeddedOAuthAPI.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public OAuthToken getToken(String oauthProvider)
    throws NotFoundException, UnauthorizedException, ServerException {
  OAuthAuthenticator provider = getAuthenticator(oauthProvider);
  final Subject subject = EnvironmentContext.getCurrent().getSubject();
  try {
    OAuthToken token = provider.getToken(subject.getUserId());
    if (token == null) {
      token = provider.getToken(subject.getUserName());
    }
    if (token != null) {
      return token;
    }
    throw new UnauthorizedException(
        "OAuth token for user " + subject.getUserId() + " was not found");
  } catch (IOException e) {
    throw new ServerException(e.getLocalizedMessage(), e);
  }
}
 
Example #5
Source File: MicrosoftVstsRestClient.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the list of active pull request in given repository. Generates html url for each pull
 * requests
 *
 * @param repositoryId the id of the repository
 * @throws IOException when any io error occurs
 * @throws ServerException when server responds with unexpected code
 * @throws UnauthorizedException when user in not authorized to call this method
 */
public List<MicrosoftPullRequest> getPullRequests(
    String account, String collection, String project, String repository, String repositoryId)
    throws IOException, ServerException, UnauthorizedException {
  return doGet(
          templates.pullRequestsUrl(account, collection, repositoryId),
          MicrosoftPullRequestList.class)
      .getValue()
      .stream()
      .peek(
          pr ->
              pr.setHtmlUrl(
                  templates.pullRequestHtmlUrl(
                      account,
                      collection,
                      project,
                      repository,
                      String.valueOf(pr.getPullRequestId()))))
      .collect(Collectors.toList());
}
 
Example #6
Source File: MicrosoftVstsService.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@PUT
@Path("/pullrequests/{account}/{collection}/{project}/{repository}/{pullRequest}")
@Consumes(APPLICATION_JSON)
public MicrosoftPullRequest updatePullRequest(
    @PathParam("account") String account,
    @PathParam("collection") String collection,
    @PathParam("project") String project,
    @PathParam("repository") String repository,
    @PathParam("pullRequest") String pullRequestId,
    MicrosoftPullRequest pullRequest)
    throws IOException, ServerException, UnauthorizedException {
  final String repositoryId =
      microsoftVstsRestClient.getRepository(account, collection, project, repository).getId();
  return microsoftVstsRestClient.updatePullRequests(
      account, collection, repositoryId, pullRequestId, pullRequest);
}
 
Example #7
Source File: TestUserServiceClientImpl.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public User getById(String id) throws NotFoundException, ServerException {
  try {
    return requestFactory
        .fromUrl(userServiceEndpoint + id)
        .useGetMethod()
        .request()
        .asDto(UserDto.class);
  } catch (IOException
      | BadRequestException
      | UnauthorizedException
      | ForbiddenException
      | ConflictException ex) {
    throw new ServerException(ex);
  }
}
 
Example #8
Source File: RemoteServiceDescriptor.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
public ServiceDescriptor getServiceDescriptor() throws IOException, ServerException {
  if (serviceDescriptor == null) {
    synchronized (this) {
      if (serviceDescriptor == null) {
        try {
          serviceDescriptor =
              requestFactory
                  .fromUrl(baseUrl)
                  .useOptionsMethod()
                  .request()
                  .as(getServiceDescriptorClass(), null);
        } catch (NotFoundException
            | ConflictException
            | UnauthorizedException
            | BadRequestException
            | ForbiddenException e) {
          throw new ServerException(e.getServiceError());
        }
      }
    }
  }
  return serviceDescriptor;
}
 
Example #9
Source File: EmbeddedOAuthAPI.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void invalidateToken(String oauthProvider)
    throws NotFoundException, UnauthorizedException, ServerException {
  OAuthAuthenticator oauth = getAuthenticator(oauthProvider);
  final Subject subject = EnvironmentContext.getCurrent().getSubject();
  try {
    if (!oauth.invalidateToken(subject.getUserId())) {
      throw new UnauthorizedException(
          "OAuth token for user " + subject.getUserId() + " was not found");
    }
  } catch (IOException e) {
    throw new ServerException(e.getMessage());
  }
}
 
Example #10
Source File: KeycloakServiceClientTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test(
    expectedExceptions = UnauthorizedException.class,
    expectedExceptionsMessageRegExp = "Unauthorized.")
public void shouldThrowUnauthorizedException() throws Exception {
  keycloakService =
      new KeycloakService(null, null, null, new UnauthorizedException("Unauthorized."));
  keycloakServiceClient.getIdentityProviderToken("github");
}
 
Example #11
Source File: KeycloakServiceClientTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test(
    expectedExceptions = UnauthorizedException.class,
    expectedExceptionsMessageRegExp = "User (.+) is not associated with identity provider (.+).")
public void shouldThrowUnauthorizedExceptionWhenNoProviderLink() throws Exception {
  keycloakService =
      new KeycloakService(
          null,
          null,
          null,
          new BadRequestException(
              "User 1234-5678-90 is not associated with identity provider gitlab."));
  keycloakServiceClient.getIdentityProviderToken("github");
}
 
Example #12
Source File: TestService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@POST
@Path("/token")
public void checkAuthorization(@HeaderParam(HttpHeaders.AUTHORIZATION) String token)
    throws UnauthorizedException {
  if (!EnvironmentContext.getCurrent().getSubject().getToken().equals(token)) {
    throw new UnauthorizedException(
        "Token '" + token + "' it is different from token in EnvironmentContext");
  }
}
 
Example #13
Source File: KeycloakTokenProvider.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private String getResponseBody(final String endpoint, final String keycloakToken)
    throws ServerException, UnauthorizedException, ForbiddenException, NotFoundException,
        ConflictException, BadRequestException, IOException {
  HttpJsonResponse request =
      httpJsonRequestFactory
          .fromUrl(endpoint)
          .setMethod("GET")
          .setAuthorizationHeader(keycloakToken)
          .request();
  return request.asString();
}
 
Example #14
Source File: TokenController.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@GET
@Path("/github")
public Response getGitHubToken(@HeaderParam(HttpHeaders.AUTHORIZATION) String keycloakToken)
    throws ForbiddenException, NotFoundException, ConflictException, BadRequestException,
        ServerException, UnauthorizedException, IOException {
  String token = null;
  try {
    validator.validate(keycloakToken);
    token = tokenProvider.obtainGitHubToken(keycloakToken);
  } catch (KeycloakException e) {
    return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
  }
  return Response.ok(token).build();
}
 
Example #15
Source File: TokenController.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@GET
@Path("/oso")
public Response getOpenShiftToken(@HeaderParam(HttpHeaders.AUTHORIZATION) String keycloakToken)
    throws ForbiddenException, NotFoundException, ConflictException, BadRequestException,
        ServerException, UnauthorizedException, IOException {
  String token = null;
  try {
    validator.validate(keycloakToken);
    token = tokenProvider.obtainOsoToken(keycloakToken);
  } catch (KeycloakException e) {
    return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
  }
  return Response.ok(token).build();
}
 
Example #16
Source File: TenantDataCacheLoader.java    From rh-che with Eclipse Public License 2.0 5 votes vote down vote up
private String getResponseBody(final String endpoint, final String keycloakToken)
    throws ServerException, UnauthorizedException, ForbiddenException, NotFoundException,
        ConflictException, BadRequestException, IOException {
  HttpJsonResponse response =
      httpJsonRequestFactory
          .fromUrl(endpoint)
          .setMethod("GET")
          .setAuthorizationHeader("Bearer " + keycloakToken)
          .request();
  return response.asString();
}
 
Example #17
Source File: DefaultHttpJsonRequest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public HttpJsonResponse request()
    throws IOException, ServerException, UnauthorizedException, ForbiddenException,
        NotFoundException, ConflictException, BadRequestException {
  if (method == null) {
    throw new IllegalStateException("Could not perform request, request method was not set.");
  }
  return doRequest(timeout, url, method, body, queryParams, authorizationHeaderValue, headers);
}
 
Example #18
Source File: TestUserServiceClientImpl.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public User findByName(String name)
    throws BadRequestException, NotFoundException, ServerException {
  try {
    return requestFactory
        .fromUrl(userServiceEndpoint + "find")
        .useGetMethod()
        .addQueryParam("name", name)
        .request()
        .asDto(UserDto.class);
  } catch (IOException | UnauthorizedException | ForbiddenException | ConflictException ex) {
    throw new ServerException(ex);
  }
}
 
Example #19
Source File: UserService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@POST
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@GenerateLink(rel = LINK_REL_USER)
@ApiOperation(value = "Create a new user", response = UserDto.class)
@ApiResponses({
  @ApiResponse(
      code = 201,
      message = "User successfully created, response contains created entity"),
  @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
  @ApiResponse(code = 401, message = "Missed token parameter"),
  @ApiResponse(code = 500, message = "Couldn't create user due to internal server error")
})
public Response create(
    @ApiParam("New user") UserDto userDto,
    @ApiParam("Authentication token") @QueryParam("token") String token,
    @ApiParam("User type") @QueryParam("temporary") @DefaultValue("false") Boolean isTemporary)
    throws BadRequestException, UnauthorizedException, ConflictException, ServerException {
  if (userDto != null) {
    // should be generated by userManager
    userDto.setId(null);
  }
  final User newUser = token == null ? userDto : tokenValidator.validateToken(token);
  userValidator.checkUser(newUser);
  return Response.status(CREATED)
      .entity(
          linksInjector.injectLinks(
              asDto(userManager.create(newUser, isTemporary)), getServiceContext()))
      .build();
}
 
Example #20
Source File: SeleniumWebDriver.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
public String getGridNodeContainerId() throws IOException {
  if (!gridMode) {
    throw new UnsupportedOperationException("We can't get grid node container id in local mode.");
  }

  if (gridNodeContainerId == null) {
    String getGridNodeInfoUrl =
        format(
            "http://localhost:%s/grid/api/testsession?session=%s",
            webDriverPort, driver.getSessionId());

    Map<String, String> gridNodeInfo;
    try {
      gridNodeInfo = httpJsonRequestFactory.fromUrl(getGridNodeInfoUrl).request().asProperties();
    } catch (ServerException
        | UnauthorizedException
        | ForbiddenException
        | NotFoundException
        | ConflictException
        | BadRequestException e) {
      throw new IOException(e);
    }

    if (!gridNodeInfo.containsKey("proxyId")) {
      throw new IOException("Proxy ID of grid node wasn't found.");
    }

    URL proxyId = new URL(gridNodeInfo.get("proxyId"));
    gridNodeContainerId = dockerUtil.findGridNodeContainerByIp(proxyId.getHost());
  }

  return gridNodeContainerId;
}
 
Example #21
Source File: ApiExceptionMapper.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Response toResponse(ApiException exception) {

  if (exception instanceof ForbiddenException)
    return Response.status(Response.Status.FORBIDDEN)
        .entity(DtoFactory.getInstance().toJson(exception.getServiceError()))
        .type(MediaType.APPLICATION_JSON)
        .build();
  else if (exception instanceof NotFoundException)
    return Response.status(Response.Status.NOT_FOUND)
        .entity(DtoFactory.getInstance().toJson(exception.getServiceError()))
        .type(MediaType.APPLICATION_JSON)
        .build();
  else if (exception instanceof UnauthorizedException)
    return Response.status(Response.Status.UNAUTHORIZED)
        .entity(DtoFactory.getInstance().toJson(exception.getServiceError()))
        .type(MediaType.APPLICATION_JSON)
        .build();
  else if (exception instanceof BadRequestException)
    return Response.status(Response.Status.BAD_REQUEST)
        .entity(DtoFactory.getInstance().toJson(exception.getServiceError()))
        .type(MediaType.APPLICATION_JSON)
        .build();
  else if (exception instanceof ConflictException)
    return Response.status(Response.Status.CONFLICT)
        .entity(DtoFactory.getInstance().toJson(exception.getServiceError()))
        .type(MediaType.APPLICATION_JSON)
        .build();
  else if (exception instanceof ServerException)
    return Response.serverError()
        .entity(DtoFactory.getInstance().toJson(exception.getServiceError()))
        .type(MediaType.APPLICATION_JSON)
        .build();
  else
    return Response.serverError()
        .entity(DtoFactory.getInstance().toJson(exception.getServiceError()))
        .type(MediaType.APPLICATION_JSON)
        .build();
}
 
Example #22
Source File: TestUserPreferencesServiceClient.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
public void restoreDefaultContributionTabPreference()
    throws ForbiddenException, BadRequestException, IOException, ConflictException,
        NotFoundException, ServerException, UnauthorizedException {
  httpRequestFactory
      .fromUrl(apiEndpoint + "preferences")
      .useDeleteMethod()
      .setBody(ImmutableList.of(ACTIVATE_CONTRIBUTION_TAB_BY_PROJECT_SELECTION_PROPERTY))
      .request();
}
 
Example #23
Source File: TestUserServiceClientImpl.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void create(String name, String email, String password)
    throws BadRequestException, ConflictException, ServerException {
  try {
    requestFactory
        .fromUrl(userServiceEndpoint)
        .usePostMethod()
        .setBody(newDto(UserDto.class).withEmail(email).withName(name).withPassword(password))
        .request();
  } catch (IOException | UnauthorizedException | NotFoundException | ForbiddenException ex) {
    throw new ServerException(ex);
  }
}
 
Example #24
Source File: TestUserServiceClientImpl.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void remove(String id) throws ConflictException, ServerException {
  try {
    requestFactory.fromUrl(userServiceEndpoint + id).useDeleteMethod().request();
  } catch (IOException
      | BadRequestException
      | NotFoundException
      | UnauthorizedException
      | ForbiddenException ex) {
    throw new ServerException(ex);
  }
}
 
Example #25
Source File: TestUserServiceClientImpl.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public User findByEmail(String email)
    throws BadRequestException, NotFoundException, ServerException {
  try {
    return requestFactory
        .fromUrl(userServiceEndpoint + "find")
        .useGetMethod()
        .addQueryParam("email", URLEncoder.encode(email, "UTF-8"))
        .request()
        .asDto(UserDto.class);
  } catch (IOException | UnauthorizedException | ForbiddenException | ConflictException ex) {
    throw new ServerException(ex);
  }
}
 
Example #26
Source File: MicrosoftVstsService.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@POST
@Path("/pullrequests/{account}/{collection}/{repository}")
@Consumes(APPLICATION_JSON)
public MicrosoftPullRequest createPullRequest(
    @PathParam("account") String account,
    @PathParam("collection") String collection,
    @PathParam("repository") String repository,
    NewMicrosoftPullRequest input)
    throws IOException, ServerException, UnauthorizedException {
  return microsoftVstsRestClient.createPullRequest(account, collection, repository, input);
}
 
Example #27
Source File: Fabric8AuthServiceClient.java    From rh-che with Eclipse Public License 2.0 5 votes vote down vote up
/** Return user's {@link GithubToken} from the fabric8 auth github endpoint. */
public GithubToken getGithubToken()
    throws ServerException, ForbiddenException, NotFoundException, UnauthorizedException,
        BadRequestException, IOException {
  String response = doRequest(githubTokenEndpoint, HttpMethod.GET, null);
  return gson.fromJson(response, GithubToken.class);
}
 
Example #28
Source File: Fabric8DelegatedOAuthAPI.java    From rh-che with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public OAuthToken getToken(String oauthProvider)
    throws ForbiddenException, BadRequestException, NotFoundException, ServerException,
        UnauthorizedException {
  try {
    GithubToken token = authServiceClient.getGithubToken();
    return DtoFactory.newDto(OAuthToken.class)
        .withToken(token.getAccessToken())
        .withScope(token.getScope());
  } catch (IOException e) {
    throw new ServerException(e.getMessage());
  }
}
 
Example #29
Source File: ZendeskRedirectServlet.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
private String getName() {
  try {
    Link link =
        DtoFactory.getInstance()
            .createDto(Link.class)
            .withMethod("GET")
            .withHref(UriBuilder.fromUri(apiEndpoint).path("profile").build().toString());
    final ProfileDto profile = HttpJsonHelper.request(ProfileDto.class, link);

    String name = profile.getAttributes().get("firstName");
    String lastName = profile.getAttributes().get("lastName");

    if (null != lastName) {
      name = null != name ? name + " " + lastName : lastName;
    }
    return name;

  } catch (IOException
      | ServerException
      | UnauthorizedException
      | ForbiddenException
      | NotFoundException
      | ConflictException e) {
    LOG.warn(e.getLocalizedMessage());
  }
  return EnvironmentContext.getCurrent().getSubject().getUserId();
}
 
Example #30
Source File: NoUserInteractionTokenHandler.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void handleBadToken(
    HttpServletRequest request, HttpServletResponse response, FilterChain chain, String token)
    throws IOException, ServletException {
  response.setStatus(HttpServletResponse.SC_FORBIDDEN);
  response.setContentType(MediaType.APPLICATION_JSON);
  try (PrintWriter writer = response.getWriter()) {
    writer.write(
        DtoFactory.getInstance()
            .toJson(
                new UnauthorizedException("Provided token " + token + " is invalid")
                    .getServiceError()));
  }
}