下面列出了怎么用javax.ws.rs.ForbiddenException的API类实例代码及写法,或者点击链接到github查看源代码。
@ResourceSecurity(WEB_UI)
@GET
@Path("{queryId}")
public Response getQueryInfo(@PathParam("queryId") QueryId queryId, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders)
{
requireNonNull(queryId, "queryId is null");
Optional<QueryInfo> queryInfo = dispatchManager.getFullQueryInfo(queryId);
if (queryInfo.isPresent()) {
try {
checkCanViewQueryOwnedBy(extractAuthorizedIdentity(servletRequest, httpHeaders, accessControl, groupProvider), queryInfo.get().getSession().getUser(), accessControl);
return Response.ok(queryInfo.get()).build();
}
catch (AccessDeniedException e) {
throw new ForbiddenException();
}
}
return Response.status(Status.GONE).build();
}
@ResourceSecurity(AUTHENTICATED_USER)
@GET
@Path("{queryId}")
public Response getQueryInfo(@PathParam("queryId") QueryId queryId, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders)
{
requireNonNull(queryId, "queryId is null");
Optional<QueryInfo> queryInfo = dispatchManager.getFullQueryInfo(queryId);
if (queryInfo.isEmpty()) {
return Response.status(Status.GONE).build();
}
try {
checkCanViewQueryOwnedBy(extractAuthorizedIdentity(servletRequest, httpHeaders, accessControl, groupProvider), queryInfo.get().getSession().getUser(), accessControl);
return Response.ok(queryInfo.get()).build();
}
catch (AccessDeniedException e) {
throw new ForbiddenException();
}
}
@ResourceSecurity(AUTHENTICATED_USER)
@DELETE
@Path("{queryId}")
public void cancelQuery(@PathParam("queryId") QueryId queryId, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders)
{
requireNonNull(queryId, "queryId is null");
try {
BasicQueryInfo queryInfo = dispatchManager.getQueryInfo(queryId);
checkCanKillQueryOwnedBy(extractAuthorizedIdentity(servletRequest, httpHeaders, accessControl, groupProvider), queryInfo.getSession().getUser(), accessControl);
dispatchManager.cancelQuery(queryId);
}
catch (AccessDeniedException e) {
throw new ForbiddenException();
}
catch (NoSuchElementException ignored) {
}
}
@Test
public void testCheckPermissionsWithResourceObjectWhenOtherExceptionOccurs() {
when(commonPermissionCheckingUtils.getParameter(any(), any(), any(), any())).thenReturn(new ResourceObjectWithNameAnnotation());
when(resourceBasedCrnProvider.getResourceCrnByResourceName(anyString())).thenReturn(RESOURCE_CRN);
doThrow(new ForbiddenException("some error")).when(commonPermissionCheckingUtils)
.checkPermissionForUserOnResource(any(), anyString(), anyString());
thrown.expect(ForbiddenException.class);
thrown.expectMessage("some error");
underTest.checkPermissions(getAnnotation(), USER_CRN, null, null, 0L);
verify(commonPermissionCheckingUtils).proceed(any(), any(), anyLong());
verify(commonPermissionCheckingUtils).getParameter(any(), any(), eq(ResourceObject.class), eq(Object.class));
verify(commonPermissionCheckingUtils, times(0)).checkPermissionForUser(any(), anyString());
verify(commonPermissionCheckingUtils).checkPermissionForUserOnResource(eq(AuthorizationResourceAction.EDIT_CREDENTIAL), eq(USER_CRN), eq(RESOURCE_CRN));
verify(resourceBasedCrnProvider).getResourceCrnByResourceName(eq("resource"));
}
@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();
}
}
}
public static void checkGradingLanguageAllowed(
String gradingEngine,
String gradingLanguage,
LanguageRestriction restriction) {
boolean allowed;
if (gradingEngine.startsWith(OutputOnlyOverrides.KEY)) {
allowed = gradingLanguage.startsWith(OutputOnlyOverrides.KEY);
} else if (gradingLanguage.startsWith(OutputOnlyOverrides.KEY)) {
allowed = gradingEngine.startsWith(OutputOnlyOverrides.KEY);
} else {
allowed = restriction.isAllowedAll() || restriction.getAllowedLanguages().contains(gradingLanguage);
}
if (!allowed) {
throw new ForbiddenException("Grading language " + gradingLanguage + " is not allowed");
}
}
@GET
@Path("realm")
@Produces(MediaType.APPLICATION_JSON)
public RealmRepresentation exportRealm(@Context final HttpHeaders headers, @Context final UriInfo uriInfo) {
//retrieving the realm should be done before authentication
// authentication overrides the value with master inside the context
// this is done this way to avoid changing the copied code below (authenticateRealmAdminRequest)
RealmModel realm = session.getContext().getRealm();
AdminAuth adminAuth = authenticateRealmAdminRequest(headers, uriInfo);
RealmManager realmManager = new RealmManager(session);
RoleModel roleModel = adminAuth.getRealm().getRole(AdminRoles.ADMIN);
AdminPermissionEvaluator realmAuth = AdminPermissions.evaluator(session, realm, adminAuth);
if (roleModel != null && adminAuth.getUser().hasRole(roleModel)
&& adminAuth.getRealm().equals(realmManager.getKeycloakAdminstrationRealm())
&& realmAuth.realm().canManageRealm()) {
RealmRepresentation realmRep = ExportUtils.exportRealm(session, realm, true, true);
//correct users
if (realmRep.getUsers() != null) {
setCorrectCredentials(realmRep.getUsers(), realm);
}
return realmRep;
} else {
throw new ForbiddenException();
}
}
@Test( expected = ForbiddenException.class )
public void deleteArtifactKarmaFailed()
throws Exception
{
try
{
Artifact artifact = new Artifact();
artifact.setGroupId( "commons-logging" );
artifact.setArtifactId( "commons-logging" );
artifact.setVersion( "1.0.1" );
artifact.setPackaging( "jar" );
artifact.setContext( SOURCE_REPO_ID );
RepositoriesService repositoriesService = getRepositoriesService( null );
repositoriesService.deleteArtifact( artifact );
}
catch ( ForbiddenException e )
{
assertEquals( 403, e.getResponse().getStatus() );
throw e;
}
}
@POST
@Path("login")
public VaultService.AuthResponse login(final VaultService.AuthRequest request) {
if (!"Test-Role".equals(request.getRoleId()) || !"Test-Secret".equals(request.getSecretId())) {
throw new ForbiddenException();
}
final VaultService.Auth auth = new VaultService.Auth();
auth.setClientToken("client-test-token");
auth.setRenewable(true);
auth.setLeaseDuration(800000);
final VaultService.AuthResponse response = new VaultService.AuthResponse();
response.setAuth(auth);
return response;
}
@POST
@Path("decrypt/{tenant}")
public VaultService.DecryptResponse decrypt(@HeaderParam("X-Vault-Token") final String token,
@PathParam("tenant") final String tenant, final VaultService.DecryptRequest request) {
if (!"client-test-token".equals(token) || tenant == null || tenant.isEmpty()
|| "x-talend-tenant-id".equals(tenant)) {
throw new ForbiddenException();
}
if (!"vault:v1:hcccVPODe9oZpcr/sKam8GUrbacji8VkuDRGfuDt7bg7VA=="
.equals(request.getBatchInput().iterator().next().getCiphertext())) {
throw new BadRequestException();
}
final VaultService.DecryptResult result = new VaultService.DecryptResult();
result.setPlaintext(Base64.getEncoder().encodeToString("test".getBytes(StandardCharsets.UTF_8)));
final VaultService.DecryptData data = new VaultService.DecryptData();
data.setBatchResults(singletonList(result));
final VaultService.DecryptResponse response = new VaultService.DecryptResponse();
response.setData(data);
return response;
}
@Test( expected = ForbiddenException.class )
public void pingWithAuthzFailed()
throws Exception
{
try
{
PingResult res = getPingService().pingWithAuthz();
fail( "not in exception" );
}
catch ( ForbiddenException e )
{
assertEquals( 403, e.getResponse().getStatus() );
throw e;
}
}
@Test
void testFilterReadSlashPath() {
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));
when(mockUriInfo.getPath()).thenReturn("container/");
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 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!");
}
@Override
public void onException(final Exception e) {
Throwable root = ExceptionUtils.getRootCause(e);
String message = root.getMessage();
if (root instanceof SyncopeClientException) {
SyncopeClientException sce = (SyncopeClientException) root;
if (!sce.isComposite()) {
message = sce.getElements().stream().collect(Collectors.joining(", "));
}
} else if (root instanceof AccessControlException || root instanceof ForbiddenException) {
Error error = StringUtils.containsIgnoreCase(message, "expired")
? Error.SESSION_EXPIRED
: Error.AUTHORIZATION;
message = getApplication().getResourceSettings().getLocalizer().
getString(error.key(), null, null, null, null, error.fallback());
} else if (root instanceof BadRequestException || root instanceof WebServiceException) {
message = getApplication().getResourceSettings().getLocalizer().
getString(Error.REST.key(), null, null, null, null, Error.REST.fallback());
}
message = getApplication().getResourceSettings().getLocalizer().
getString(message, null, null, null, null, message);
error(message);
}
@Test
void testFilterCustomAppend() {
final Set<IRI> modes = new HashSet<>();
when(mockContext.getMethod()).thenReturn("APPEND");
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 testFilterControl() {
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(mockContext.getHeaderString("Prefer"))
.thenReturn("return=representation; include=\"" + Trellis.PreferAudit.getIRIString() + "\"");
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 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!");
}
private void checkDetailLevel(ContainerRequestContext requestContext, String... detail) throws ForbiddenException {
MCRRequestScopeACL aclProvider = MCRRequestScopeACL.getInstance(requestContext);
List<String> missedPermissions = Stream.of(detail)
.map(d -> "rest-detail-" + d)
.filter(d -> MCRAccessManager.hasRule(MCRAccessControlSystem.POOL_PRIVILEGE_ID, d))
.filter(d -> !aclProvider.checkPermission(d))
.collect(Collectors.toList());
if (!missedPermissions.isEmpty()) {
throw MCRErrorResponse.fromStatus(Response.Status.FORBIDDEN.getStatusCode())
.withErrorCode(MCRErrorCodeConstants.API_NO_PERMISSION)
.withMessage("REST-API action is not allowed.")
.withDetail("Check access right(s) '" + missedPermissions + "' on "
+ MCRAccessControlSystem.POOL_PRIVILEGE_ID + "'!")
.toException();
}
}
@Test
public void create() {
assumeTrue(FlowableDetector.isFlowableEnabledForUserWorkflow(syncopeService));
// 1. self-registration as admin: failure
try {
userSelfService.create(UserITCase.getUniqueSample("[email protected]"));
fail("This should not happen");
} catch (ForbiddenException e) {
assertNotNull(e);
}
// 2. self-registration as anonymous: works
SyncopeClient anonClient = clientFactory.create();
UserTO self = anonClient.getService(UserSelfService.class).
create(UserITCase.getUniqueSample("[email protected]")).
readEntity(new GenericType<ProvisioningResult<UserTO>>() {
}).getEntity();
assertNotNull(self);
assertEquals("createApproval", self.getStatus());
}
@Test
public void shouldFailAsRegularUser() {
BuildClient client = new BuildClient(RestClientConfiguration.asUser());
String buildRecordId = "1";
assertThatThrownBy(() -> client.setBuiltArtifacts(buildRecordId, Collections.emptyList()))
.hasCauseInstanceOf(ForbiddenException.class);
assertThatThrownBy(() -> client.setDependentArtifacts(buildRecordId, Collections.emptyList()))
.hasCauseInstanceOf(ForbiddenException.class);
assertThatThrownBy(() -> client.update(buildRecordId, Build.builder().build()))
.hasCauseInstanceOf(ForbiddenException.class);
}
@Test(expected = ForbiddenException.class)
public void returnsUnauthorizedWhenDenied() throws Exception {
when(aclDAO.getSanitizedSecretFor(client, secret.getName())).thenReturn(Optional.empty());
when(clientDAO.getClientByName(client.getName())).thenReturn(Optional.of(client));
when(secretController.getSecretByName(secret.getName()))
.thenReturn(Optional.of(secret));
secretDeliveryResource.getSecret(secret.getName(), client);
}
private void afterAuthentication(final String username) {
try {
selfTO = client.self().getRight();
} catch (ForbiddenException e) {
LOG.warn("Could not read self(), probably in a {} scenario", IdRepoEntitlement.MUST_CHANGE_PASSWORD, e);
selfTO = new UserTO();
selfTO.setUsername(username);
selfTO.setMustChangePassword(true);
}
// bind explicitly this session to have a stateful behavior during http requests, unless session will
// expire at each request
this.bind();
}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (disableForTests) {
return;
}
if ((PRIVILEGED_METHODS.contains(requestContext.getMethod()) &&
!requestContext.getSecurityContext().isUserInRole(ADMIN)) ||
!requestContext.getSecurityContext().isUserInRole(VIEWER)) {
throw new ForbiddenException(FORBIDDEN_MSG);
}
}
@Override
public void onException(final Exception e) {
Throwable root = ExceptionUtils.getRootCause(e);
String message = root.getMessage();
if (root instanceof SyncopeClientException) {
SyncopeClientException sce = (SyncopeClientException) root;
if (sce.getType() == ClientExceptionType.InvalidSecurityAnswer) {
message = getApplication().getResourceSettings().getLocalizer().
getString("invalid.security.answer", null);
} else if (!sce.isComposite()) {
message = sce.getElements().stream().collect(Collectors.joining(", "));
}
} else if (root instanceof AccessControlException || root instanceof ForbiddenException) {
Error error = StringUtils.containsIgnoreCase(message, "expired")
? Error.SESSION_EXPIRED
: Error.AUTHORIZATION;
message = getApplication().getResourceSettings().getLocalizer().
getString(error.key(), null, null, null, null, error.fallback());
} else if (root instanceof BadRequestException || root instanceof WebServiceException) {
message = getApplication().getResourceSettings().getLocalizer().
getString(Error.REST.key(), null, null, null, null, Error.REST.fallback());
}
message = getApplication().getResourceSettings().getLocalizer().
getString(message, null, null, null, null, message);
error(message);
}
@Override
@UnitOfWork
public Session logIn(Credentials credentials) {
User user = userStore.getUserByUsernameAndPassword(credentials.getUsernameOrEmail(), credentials.getPassword())
.orElseGet(() ->
userStore.getUserByEmailAndPassword(credentials.getUsernameOrEmail(), credentials.getPassword())
.orElseThrow(ForbiddenException::new));
if (!userRegistrationEmailStore.isUserActivated(user.getJid())) {
throw SessionErrors.userNotActivated(user.getEmail());
}
return sessionStore.createSession(SessionTokenGenerator.newToken(), user.getJid());
}
@Test
public void updateAsGroupOwner() {
// 1. read group as admin
GroupTO groupTO = groupService.read("ebf97068-aa4b-4a85-9f01-680e8c4cf227");
// issue SYNCOPE-15
assertNotNull(groupTO.getCreationDate());
assertNotNull(groupTO.getLastChangeDate());
assertEquals("admin", groupTO.getCreator());
assertEquals("admin", groupTO.getLastModifier());
// 2. prepare update
GroupUR groupUR = new GroupUR();
groupUR.setKey(groupTO.getKey());
groupUR.setName(new StringReplacePatchItem.Builder().value("Director").build());
// 3. try to update as verdi, not owner of group 6 - fail
GroupService groupService2 = clientFactory.create("verdi", ADMIN_PWD).getService(GroupService.class);
try {
groupService2.update(groupUR);
fail("This should not happen");
} catch (ForbiddenException e) {
assertNotNull(e);
}
// 4. update as puccini, owner of group 6 - success
GroupService groupService3 = clientFactory.create("puccini", ADMIN_PWD).getService(GroupService.class);
groupTO = groupService3.update(groupUR).readEntity(new GenericType<ProvisioningResult<GroupTO>>() {
}).getEntity();
assertEquals("Director", groupTO.getName());
// issue SYNCOPE-15
assertNotNull(groupTO.getCreationDate());
assertNotNull(groupTO.getLastChangeDate());
assertEquals("admin", groupTO.getCreator());
assertEquals("puccini", groupTO.getLastModifier());
assertTrue(groupTO.getCreationDate().before(groupTO.getLastChangeDate()));
}
public Client check(@Nullable BasicAuthHeader authHeader) {
if (authHeader == null) {
throw new NotAuthorizedException(Response.SC_UNAUTHORIZED);
}
Client client = authHeader.getClient();
if (!clients.contains(client)) {
throw new ForbiddenException();
}
return client;
}
@Test(expected = ForbiddenException.class)
public void nonAdminCantBuiltInImport() throws IOException {
RealmRepresentation fileRepresentation = new ObjectMapper().readValue(new File(TEST_REALM_PATH), RealmRepresentation.class);
Assert.assertNotNull(fileRepresentation);
TestsHelper.importTestRealm(TEST_USER, "password", "/" + TEST_REALM_NAME + "-realm.json");
TestsHelper.deleteRealm("admin", "admin", TEST_REALM_NAME);
}
/**
* Void method that throws a ForbiddenException. View 'hello.jsp' should be ignored.
*/
@GET
@Path("void/forbidden")
@View("hello.jsp")
public void voidForbiddenException() {
throw new ForbiddenException();
}
/**
* Method that throws a ForbiddenException. View 'hello.jsp' should be ignored.
*/
@GET
@Path("string/forbidden")
@View("hello.jsp")
public String stringForbiddenException() {
throw new ForbiddenException();
}