下面列出了javax.ws.rs.NotSupportedException#javax.ws.rs.NotAuthorizedException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public User verifyToken(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(this.engine.getApiSecret());
JWTVerifier verifier =
JWT.require(algorithm).withIssuer(ISSUER).build(); // Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
var user = PersistenceManager.getInstance().getById(User.class, jwt.getSubject());
if (user == null) {
throw new NotAuthorizedException(ERROR_MESSAGE_USER_NOT_FOUND);
}
return user;
} catch (JWTVerificationException ex) {
throw new NotAuthorizedException("Invalid token", ex);
}
}
@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();
}
}
}
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();
}
@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
}
}
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");
};
}
/**
* 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;
}
@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());
}
}
/**
* 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);
}
}
@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
}
}
/**
* 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");
}
@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
}
}
@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
}
}
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;
}
@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!");
}
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);
}
@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!");
}
@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!");
}
@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!");
}
@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!");
}
@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!");
}
@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!");
}
@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));
}
private void checkRealmAdmin() {
if (auth == null) {
throw new NotAuthorizedException("Bearer");
} else if (auth.getToken().getRealmAccess() == null || !auth.getToken().getRealmAccess().isUserInRole("admin")) {
throw new ForbiddenException("Does not have realm admin role");
}
}
@Test(expected = NotAuthorizedException.class)
public void rejectsXfcc_requesterAuthMissing() 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(null);
factory.provide(request);
}
private void checkRealmAdmin() {
if (auth == null) {
throw new NotAuthorizedException("Bearer");
} else if (auth.getToken().getRealmAccess() == null || !auth.getToken().getRealmAccess().isUserInRole("admin")) {
throw new ForbiddenException("Does not have realm admin role");
}
}
@Test(expected = NotAuthorizedException.class)
@InSequence(2)
public void badLogin() throws IOException {
UserDefaultExample user = new UserDefaultExample();
user.setUserId("userId1");
user.setPassword("password11");
target.path("/login").request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(Entity.json(objectMapper.writeValueAsString(user)), TokenResponse.class);
}
public Client provide(ContainerRequest request) {
// Ports must either always send an x-forwarded-client-cert header, or
// never send this header. This also throws an error if a single port
// has multiple configurations.
int requestPort = request.getBaseUri().getPort();
Optional<XfccSourceConfig> possibleXfccConfig =
getXfccConfigForPort(requestPort);
List<String> xfccHeaderValues =
Optional.ofNullable(request.getRequestHeader(XFCC_HEADER_NAME)).orElse(List.of());
if (possibleXfccConfig.isEmpty() != xfccHeaderValues.isEmpty()) {
throw new NotAuthorizedException(format(
"Port %d is configured to %s receive traffic with the %s header set",
requestPort, possibleXfccConfig.isEmpty() ? "never" : "only", XFCC_HEADER_NAME));
}
// Extract information about the requester. This may be a Keywhiz client, or it may be a proxy
// forwarding the real Keywhiz client information in the x-forwarded-client-certs header
Principal requestPrincipal = getPrincipal(request).orElseThrow(
() -> new NotAuthorizedException("Not authorized as Keywhiz client"));
// Extract client information based on the x-forwarded-client-cert header or
// on the security context of this request
if (possibleXfccConfig.isEmpty()) {
// The XFCC header is not used; use the security context of this request to identify the client
return authorizeClientFromCertificate(requestPrincipal);
} else {
return authorizeClientFromXfccHeader(possibleXfccConfig.get(), xfccHeaderValues,
requestPrincipal);
}
}
@Override
public Response toResponse(NotAuthorizedException exception) {
// This is a hack because currently Conjure does not support 401 exception :(
Map<String, String> serializableError = Maps.newHashMap();
serializableError.put("errorCode", "CUSTOM_CLIENT");
serializableError.put("errorName", "Judgels:Unauthorized");
serializableError.put("errorInstanceId", UUID.randomUUID().toString());
return Response
.status(Response.Status.UNAUTHORIZED)
.type(MediaType.APPLICATION_JSON_TYPE)
.entity(serializableError)
.build();
}
@Test(expected = NotAuthorizedException.class)
public void rejectsXfcc_emptyHeader() throws Exception {
when(request.getBaseUri()).thenReturn(
new URI(format("https://localhost:%d", xfccAllowedPort)));
when(securityContext.getUserPrincipal()).thenReturn(xfccPrincipal);
when(request.getRequestHeader(ClientAuthFactory.XFCC_HEADER_NAME)).thenReturn(List.of(""));
factory.provide(request);
}
@Test(expected = NotAuthorizedException.class)
public void rejectsXfcc_portConfigurationInvalid() 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(clientAuthConfig.xfccConfigs()).thenReturn(List.of(xfccSourceConfig, xfccSourceConfig));
factory.provide(request);
}