javax.ws.rs.NotAuthorizedException Java Examples

The following examples show how to use javax.ws.rs.NotAuthorizedException. 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: WebAcFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testFilterAppend() {
    final Set<IRI> modes = new HashSet<>();
    when(mockContext.getMethod()).thenReturn("POST");
    when(mockWebAcService.getAuthorizedModes(any(IRI.class), any(Session.class)))
        .thenReturn(new AuthorizedModes(effectiveAcl, modes));

    final WebAcFilter filter = new WebAcFilter();
    filter.setAccessService(mockWebAcService);
    modes.add(ACL.Append);
    assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Append ability!");

    modes.add(ACL.Write);
    assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Write ability!");

    modes.remove(ACL.Append);
    assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after removing Append ability!");

    modes.clear();
    assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext),
            "No expception thrown when not authorized!");

    when(mockContext.getSecurityContext()).thenReturn(mockSecurityContext);
    assertThrows(ForbiddenException.class, () -> filter.filter(mockContext),
            "No exception thrown!");
}
 
Example #2
Source File: FernetTokenValueParamProvider.java    From fernet-java8 with Apache License 2.0 6 votes vote down vote up
public Function<ContainerRequest, Token> getValueProvider(final Parameter parameter) {
    return request -> {
        if (parameter.getRawType().equals(Token.class) && parameter.isAnnotationPresent(FernetToken.class)) {
            final Token xAuthorizationToken = getTokenHeaderUtility().getXAuthorizationToken(request);
            if (xAuthorizationToken != null) {
                return xAuthorizationToken;
            }
            final Token authorizationToken = getTokenHeaderUtility().getAuthorizationToken(request);
            if (authorizationToken != null) {
                return authorizationToken;
            }
            throw new NotAuthorizedException("Bearer error=\"invalid_token\", error_description=\"no token found in Authorization or X-Authorization header\"");
        }
        throw new IllegalStateException("misconfigured annotation");
    };
}
 
Example #3
Source File: AdminApiTlsAuthTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnauthorizedUserAsOriginalPrincipalProxyIsSuperUser() throws Exception {
    try (PulsarAdmin admin = buildAdminClient("admin")) {
        admin.tenants().createTenant("tenant1",
                                     new TenantInfo(ImmutableSet.of("user1"),
                                                    ImmutableSet.of("test")));
        admin.namespaces().createNamespace("tenant1/ns1");
    }
    WebTarget root = buildWebClient("superproxy");
    try {
        root.path("/admin/v2/namespaces").path("tenant1")
            .request(MediaType.APPLICATION_JSON)
            .header("X-Original-Principal", "user2")
            .get(new GenericType<List<String>>() {});
        Assert.fail("user2 should not be authorized");
    } catch (NotAuthorizedException e) {
        // expected
    }
}
 
Example #4
Source File: TokenHeaderUtility.java    From fernet-java8 with Apache License 2.0 6 votes vote down vote up
/**
 * Extract a Fernet token from an RFC6750 Authorization header.
 *
 * @param request a REST request which may or may not include an RFC6750 Authorization header.
 * @return a Fernet token or null if no RFC6750 Authorization header is provided.
 */
@SuppressWarnings("PMD.AvoidLiteralsInIfCondition")
public Token getAuthorizationToken(final ContainerRequest request) {
    String authorizationString = request.getHeaderString("Authorization");
    if (authorizationString != null && !"".equals(authorizationString)) {
        authorizationString = authorizationString.trim();
        final String[] components = authorizationString.split("\\s");
        if (components.length != 2) {
            throw new NotAuthorizedException(authenticationType);
        }
        final String scheme = components[0];
        if (!authenticationType.equalsIgnoreCase(scheme)) {
            throw new NotAuthorizedException(authenticationType);
        }
        final String tokenString = components[1];
        return Token.fromString(tokenString);
    }
    return null;
}
 
Example #5
Source File: WebAcFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testFilterRead() {
    final Set<IRI> modes = new HashSet<>();
    when(mockContext.getMethod()).thenReturn("GET");
    when(mockWebAcService.getAuthorizedModes(any(IRI.class), any(Session.class)))
        .thenReturn(new AuthorizedModes(effectiveAcl, modes));

    final WebAcFilter filter = new WebAcFilter();
    filter.setAccessService(mockWebAcService);
    modes.add(ACL.Read);
    assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Read ability!");

    verify(mockContext).setProperty(eq(WebAcFilter.SESSION_WEBAC_MODES), modesArgument.capture());
    assertTrue(modesArgument.getValue().getAccessModes().contains(ACL.Read));
    assertEquals(modes.size(), modesArgument.getValue().getAccessModes().size());

    modes.clear();
    assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext),
            "No expception thrown when not authorized!");

    when(mockContext.getSecurityContext()).thenReturn(mockSecurityContext);
    assertThrows(ForbiddenException.class, () -> filter.filter(mockContext),
            "No exception thrown!");

}
 
Example #6
Source File: ClientAuthFactory.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
private Client authorizeClientFromXfccHeader(XfccSourceConfig xfccConfig,
    List<String> xfccHeaderValues, Principal requestPrincipal) {
  // Do not allow the XFCC header to be set by all incoming traffic. This throws a
  // NotAuthorizedException when the traffic is not coming from a source allowed to set the
  // header.
  validateXfccHeaderAllowed(xfccConfig, requestPrincipal);

  // Extract client information from the XFCC header
  X509Certificate clientCert =
      getClientCertFromXfccHeaderEnvoyFormatted(xfccHeaderValues).orElseThrow(() ->
          new NotAuthorizedException(
              format("unable to parse client certificate from %s header", XFCC_HEADER_NAME))
      );

  CertificatePrincipal certificatePrincipal =
      new CertificatePrincipal(clientCert.getSubjectDN().toString(),
          new X509Certificate[] {clientCert});

  return authorizeClientFromCertificate(certificatePrincipal);
}
 
Example #7
Source File: WebAcFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testFilterCustomRead() {
    final Set<IRI> modes = new HashSet<>();
    when(mockContext.getMethod()).thenReturn("READ");
    when(mockWebAcService.getAuthorizedModes(any(IRI.class), any(Session.class)))
        .thenReturn(new AuthorizedModes(effectiveAcl, modes));

    final WebAcFilter filter = new WebAcFilter();
    filter.setAccessService(mockWebAcService);
    modes.add(ACL.Read);
    assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Read ability!");

    modes.clear();
    assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext),
            "No expception thrown when not authorized!");

    when(mockContext.getSecurityContext()).thenReturn(mockSecurityContext);
    assertThrows(ForbiddenException.class, () -> filter.filter(mockContext),
            "No exception thrown!");
}
 
Example #8
Source File: AuthHelper.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
public static boolean isNotAuthorizedError(final Throwable throwable) {
    //We get VssServiceResponseException when token is valid but does not have the required scopes
    //statusCode on VssServiceResponseException is set to 401 but that is not accessible, so we have to check the message
    //If the message gets localized, we won't detect the auth error
    if (throwable != null && (throwable instanceof NotAuthorizedException ||
            (throwable instanceof VssServiceResponseException &&
                    StringUtils.containsIgnoreCase(throwable.getMessage(), "unauthorized")))) {
        return true;
    }

    if (throwable != null && throwable.getCause() != null && (throwable.getCause() instanceof NotAuthorizedException ||
            (throwable.getCause() instanceof VssServiceResponseException &&
                    (StringUtils.containsIgnoreCase(throwable.getMessage(), "unauthorized"))))) {
        return true;
    }

    return false;
}
 
Example #9
Source File: AdminApiTlsAuthTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorizedUserAsOriginalPrincipalButProxyNotAuthorized() throws Exception {
    try (PulsarAdmin admin = buildAdminClient("admin")) {
        admin.tenants().createTenant("tenant1",
                                     new TenantInfo(ImmutableSet.of("user1"),
                                                    ImmutableSet.of("test")));
        admin.namespaces().createNamespace("tenant1/ns1");
    }
    WebTarget root = buildWebClient("proxy");
    try {
        root.path("/admin/v2/namespaces").path("tenant1")
            .request(MediaType.APPLICATION_JSON)
            .header("X-Original-Principal", "user1")
            .get(new GenericType<List<String>>() {});
        Assert.fail("Shouldn't be able to list namespaces");
    } catch (NotAuthorizedException e) {
        // expected
    }
}
 
Example #10
Source File: WebAcFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testFilterWriteWithPreferRead() {
    final Set<IRI> modes = new HashSet<>();
    when(mockContext.getMethod()).thenReturn("PUT");
    when(mockContext.getHeaderString(eq(PREFER))).thenReturn("return=representation");
    when(mockWebAcService.getAuthorizedModes(any(IRI.class), any(Session.class)))
        .thenReturn(new AuthorizedModes(effectiveAcl, modes));

    final WebAcFilter filter = new WebAcFilter();
    filter.setAccessService(mockWebAcService);
    modes.add(ACL.Write);

    assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext),
            "No expception thrown when not authorized!");

    modes.add(ACL.Read);
    assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Write ability!");
}
 
Example #11
Source File: WebAcFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testFilterCustomWrite() {
    final Set<IRI> modes = new HashSet<>();
    when(mockContext.getMethod()).thenReturn("WRITE");
    when(mockWebAcService.getAuthorizedModes(any(IRI.class), any(Session.class)))
        .thenReturn(new AuthorizedModes(effectiveAcl, modes));

    final WebAcFilter filter = new WebAcFilter();
    filter.setAccessService(mockWebAcService);
    modes.add(ACL.Write);
    assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Write ability!");

    modes.clear();
    assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext),
            "No expception thrown when not authorized!");

    when(mockContext.getSecurityContext()).thenReturn(mockSecurityContext);
    assertThrows(ForbiddenException.class, () -> filter.filter(mockContext),
            "No exception thrown!");
}
 
Example #12
Source File: ClientGenerator.java    From pnc with Apache License 2.0 6 votes vote down vote up
private MethodSpec completeMethod(
        MethodSpec.Builder methodBuilder,
        Consumer<MethodSpec.Builder> coreStatementConsumer) {
    methodBuilder = methodBuilder.nextControlFlow("catch ($T e)", NotAuthorizedException.class)
            .beginControlFlow("if (configuration.getBearerTokenSupplier() != null)")
            .beginControlFlow("try")
            .addStatement("bearerAuthentication.setToken(configuration.getBearerTokenSupplier().get())");

    coreStatementConsumer.accept(methodBuilder);

    return methodBuilder.nextControlFlow("catch ($T wae)", WebApplicationException.class)
            .addStatement("throw new RemoteResourceException(readErrorResponse(wae), wae)")
            .endControlFlow()
            .nextControlFlow("else")
            .addStatement("throw new RemoteResourceException(readErrorResponse(e), e)")
            .endControlFlow()
            .nextControlFlow("catch ($T e)", WebApplicationException.class)
            .addStatement("throw new RemoteResourceException(readErrorResponse(e), e)")
            .endControlFlow()
            .build();
}
 
Example #13
Source File: AdminApiTlsAuthTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testProxyUserViaProxy() throws Exception {
    try (PulsarAdmin admin = buildAdminClient("admin")) {
        admin.tenants().createTenant("tenant1",
                                     new TenantInfo(ImmutableSet.of("proxy"),
                                                    ImmutableSet.of("test")));
        admin.namespaces().createNamespace("tenant1/ns1");
    }
    WebTarget root = buildWebClient("superproxy");
    try {
        root.path("/admin/v2/namespaces").path("tenant1")
            .request(MediaType.APPLICATION_JSON)
            .header("X-Original-Principal", "proxy")
            .get(new GenericType<List<String>>() {});
        Assert.fail("proxy should not be authorized");
    } catch (NotAuthorizedException e) {
        // expected
    }
}
 
Example #14
Source File: WebAcFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testFilterControl2() {
    final Set<IRI> modes = new HashSet<>();
    when(mockContext.getMethod()).thenReturn("GET");
    when(mockWebAcService.getAuthorizedModes(any(IRI.class), any(Session.class)))
        .thenReturn(new AuthorizedModes(effectiveAcl, modes));

    final WebAcFilter filter = new WebAcFilter();
    filter.setAccessService(mockWebAcService);
    modes.add(ACL.Read);
    assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Read ability!");

    when(mockQueryParams.getOrDefault(eq("ext"), eq(emptyList()))).thenReturn(singletonList("acl"));

    assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext),
            "No expception thrown when not authorized!");

    modes.add(ACL.Control);
    assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Control ability!");

    modes.clear();
    when(mockContext.getSecurityContext()).thenReturn(mockSecurityContext);
    assertThrows(ForbiddenException.class, () -> filter.filter(mockContext),
            "No exception thrown!");
}
 
Example #15
Source File: RolesAllowedFilter.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) {
    SecurityContext securityContext = requestContext.getSecurityContext();
    boolean isForbidden;
    if (allRolesAllowed) {
        isForbidden = securityContext.getUserPrincipal() == null;
    } else {
        isForbidden = allowedRoles.stream().noneMatch(securityContext::isUserInRole);
    }
    if (isForbidden) {
        if (requestContext.getSecurityContext().getUserPrincipal() == null) {
            throw new NotAuthorizedException("Bearer");
        } else {
            throw new ForbiddenException();
        }
    }
}
 
Example #16
Source File: WebAcFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testFilterChallenges() {
    when(mockContext.getMethod()).thenReturn("POST");
    when(mockWebAcService.getAuthorizedModes(any(IRI.class), any(Session.class)))
        .thenReturn(new AuthorizedModes(effectiveAcl, emptySet()));

    final WebAcFilter filter = new WebAcFilter();
    filter.setAccessService(mockWebAcService);
    filter.setChallenges(asList("Foo realm=\"my-realm\" scope=\"my-scope\"",
                "Bar realm=\"my-realm\" scope=\"my-scope\""));
    filter.setBaseUrl("http://example.com/");

    final List<Object> challenges = assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext),
            "No auth exception thrown with no access modes!").getChallenges();

    assertTrue(challenges.contains("Foo realm=\"my-realm\" scope=\"my-scope\""), "Foo not among challenges!");
    assertTrue(challenges.contains("Bar realm=\"my-realm\" scope=\"my-scope\""), "Bar not among challenges!");
}
 
Example #17
Source File: TokenUtils.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Get token from the authorization header or from the query parameters.
 *
 * @param context The request context
 * @return token
 * @throws NotAuthorizedException if header format is incorrect and the token is not supplied as a query param
 */
public static String getTokenFromAuthHeaderOrQueryParameter(final ContainerRequestContext context)
  throws NotAuthorizedException {

  final String authHeader = getToken(context.getHeaderString(HttpHeaders.AUTHORIZATION));
  if (authHeader != null) {
    return authHeader;
  }

  final String token = getToken(context.getUriInfo().getQueryParameters().getFirst(HttpHeaders.AUTHORIZATION));
  if (token != null) {
    return token;
  }

  throw new NotAuthorizedException("Authorization header or access token must be provided");
}
 
Example #18
Source File: MCRRestAPIAuthentication.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@GET
@Path("/renew")
@MCRRestrictedAccess(MCRRequireLogin.class)
@MCRCacheControl(noTransform = true,
    noStore = true,
    private_ = @MCRCacheControl.FieldArgument(active = true),
    noCache = @MCRCacheControl.FieldArgument(active = true))
public Response renew(@DefaultValue("") @HeaderParam("Authorization") String authorization) throws IOException {
    if (authorization.startsWith("Bearer ")) {
        //login handled by MCRSessionFilter
        Optional<String> jwt = getToken(MCRSessionMgr.getCurrentSession().getUserInformation(),
            MCRFrontendUtil.getRemoteAddr(req));
        if (jwt.isPresent()) {
            return MCRJWTUtil.getJWTRenewSuccessResponse(jwt.get());
        }
    }
    throw new NotAuthorizedException(
        "Login failed. Please provide a valid JSON Web Token for authentication.",
        MCRRestAPIUtil.getWWWAuthenticateHeader("Basic", null, app));
}
 
Example #19
Source File: AdminApiTlsAuthTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuperProxyUserAndNonAdminCannotListTenants() throws Exception {
    try (PulsarAdmin admin = buildAdminClient("admin")) {
        admin.tenants().createTenant("tenant1",
                                     new TenantInfo(ImmutableSet.of("proxy"),
                                                    ImmutableSet.of("test")));
    }
    WebTarget root = buildWebClient("superproxy");
    try {
        root.path("/admin/v2/tenants")
            .request(MediaType.APPLICATION_JSON)
            .header("X-Original-Principal", "user1")
            .get(new GenericType<List<String>>() {});
        Assert.fail("user1 should not be authorized");
    } catch (NotAuthorizedException e) {
        // expected
    }
}
 
Example #20
Source File: JWSOpenCPSTokenFilter.java    From opencps-v2 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
 public void filter(ContainerRequestContext requestContext) throws IOException {

     String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
     // Check if the HTTP Authorization header is present and formatted correctly
     if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
         throw new NotAuthorizedException("Authorization header must be provided");
     }

     String token = authorizationHeader.substring("Bearer".length()).trim();

     try {

         // Validate the token
         Key key = keyGenerator.generateKey();
         Jwts.parser().setSigningKey(key).parseClaimsJws(token);
 
     } catch (Exception e) {
     	_log.debug(e);
//_log.error(e);
         requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
     }
 }
 
Example #21
Source File: ConnectionsApiDelegate.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves all active amqp connections established with the broker.
 *
 * @param subject The authentication subject containing user information of the user that has invoked the API
 * @return list of {@link ConnectionMetadata}
 */
public Response getAllConnections(Subject subject) {
    try {
        authHandler.handle(ResourceAuthScope.CONNECTIONS_GET, subject);
        List<ConnectionMetadata> connections = new ArrayList<>();
        for (AmqpConnectionHandler connectionHandler : connectionManager.getConnections()) {
            connections.add(new ConnectionMetadata().id(connectionHandler.getId())
                                                    .remoteAddress(connectionHandler.getRemoteAddress())
                                                    .channelCount(connectionHandler.getChannelCount())
                                                    .connectedTime(connectionHandler.getConnectedTime()));
        }
        return Response.ok().entity(connections).build();
    } catch (AuthException e) {
        throw new NotAuthorizedException(e.getMessage(), e);
    }
}
 
Example #22
Source File: AppAuthManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts the token string from the Authorization Bearer Header.
 *
 * @param headers
 * @return the token string or {@literal null} of the Authorization header is missing
 * @throws  NotAuthorizedException if the Authorization header is not of type Bearer, or the token string is missing.
 */
public String extractAuthorizationHeaderToken(HttpHeaders headers) {
    String authHeader = headers.getRequestHeaders().getFirst(HttpHeaders.AUTHORIZATION);
    if (authHeader == null) {
        return null;
    }
    String tokenString = extractTokenStringFromAuthHeader(authHeader);
    if (tokenString == null ){
        throw new NotAuthorizedException(BEARER);
    }
    return tokenString;
}
 
Example #23
Source File: ZonkyApiTokenSupplierTest.java    From robozonky with Apache License 2.0 5 votes vote down vote up
@Test
void failsOnLogin2() {
    final Zonky zonky = mock(Zonky.class);
    final OAuth oAuth = mock(OAuth.class);
    doThrow(NotAuthorizedException.class).when(oAuth)
        .refresh(any());
    final ApiProvider api = mockApi(oAuth, zonky);
    final ZonkyApiTokenSupplier t = new ZonkyApiTokenSupplier(api, secrets);
    secrets.setToken(new ZonkyApiTokenImpl(UUID.randomUUID()
        .toString(),
            UUID.randomUUID()
                .toString(),
            199));
    assertThatThrownBy(t::get).isInstanceOf(NotAuthorizedException.class);
}
 
Example #24
Source File: WebAcFilter.java    From trellis with Apache License 2.0 5 votes vote down vote up
protected void verifyCanWrite(final Set<IRI> modes, final Session session, final String path) {
    if (!modes.contains(ACL.Write)) {
        LOGGER.warn("User: {} cannot Write to {}", session.getAgent(), path);
        if (Trellis.AnonymousAgent.equals(session.getAgent())) {
            throw new NotAuthorizedException(challenges.get(0),
                    challenges.subList(1, challenges.size()).toArray());
        }
        throw new ForbiddenException();
    }
    LOGGER.debug("User: {} can write to {}", session.getAgent(), path);
}
 
Example #25
Source File: OAuthFilterTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testFilterGenericNoAuth() {
    final Key key = secretKeyFor(SignatureAlgorithm.HS512);
    final String token = Jwts.builder().claim("webid", WEBID1).signWith(key).compact();
    when(mockContext.getHeaderString(AUTHORIZATION)).thenReturn("Bearer " + token);

    final OAuthFilter filter = new OAuthFilter();
    assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext));
}
 
Example #26
Source File: OAuthFilterTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testFilterExpiredJwt() {
    final Key key = secretKeyFor(SignatureAlgorithm.HS512);
    final String token = Jwts.builder().claim("webid", WEBID1).setExpiration(from(now().minusSeconds(10)))
        .signWith(key).compact();
    when(mockContext.getHeaderString(AUTHORIZATION)).thenReturn("Bearer " + token);

    final OAuthFilter filter = new OAuthFilter();
    filter.setAuthenticator(new JwtAuthenticator(key));
    assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext));
}
 
Example #27
Source File: DigestAuthSupplierSpringTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    WebClient client = WebClient.create("http://localhost:" + port, (String) null);

    assertThrows(NotAuthorizedException.class, () -> client.get(String.class));

    HTTPConduit conduit = WebClient.getConfig(client).getHttpConduit();
    conduit.setAuthSupplier(new DigestAuthSupplier());
    conduit.getAuthorization().setUserName(USER);
    conduit.getAuthorization().setPassword(PWD);

    assertEquals(Controller.RESPONSE, client.get(String.class));
}
 
Example #28
Source File: OAuthFilter.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext) {

    final SecurityContext securityContext = requestContext.getSecurityContext();
    final boolean secure = securityContext != null && securityContext.isSecure();

    final String token = getOAuthToken(requestContext);
    if (token != null) {
        final Principal principal = authenticate(token);
        if (principal == null) throw new NotAuthorizedException(challenge);
        requestContext.setSecurityContext(new OAuthSecurityContext(principal, admins, secure));
    }
}
 
Example #29
Source File: ClientAuthFactory.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
private Client authorizeClientFromCertificate(Principal clientPrincipal) {
  Optional<Client> possibleClient =
      authenticator.authenticate(clientPrincipal, true);
  return possibleClient.orElseThrow(() -> new NotAuthorizedException(
      format("No authorized Client for connection using principal %s",
          clientPrincipal.getName())));
}
 
Example #30
Source File: ClientAuthFactoryTest.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
@Test(expected = NotAuthorizedException.class)
public void rejectsXfcc_requesterSpiffeNotAllowed() throws Exception {
  when(request.getBaseUri()).thenReturn(new URI(format("https://localhost:%d", xfccAllowedPort)));
  when(request.getRequestHeader(ClientAuthFactory.XFCC_HEADER_NAME)).thenReturn(
      List.of(xfccHeader));
  when(securityContext.getUserPrincipal()).thenReturn(xfccPrincipal);

  when(xfccSourceConfig.allowedClientNames()).thenReturn(List.of(xfccName));
  when(xfccSourceConfig.allowedSpiffeIds()).thenReturn(List.of());

  factory.provide(request);
}