Java Code Examples for javax.ws.rs.core.SecurityContext#isUserInRole()
The following examples show how to use
javax.ws.rs.core.SecurityContext#isUserInRole() .
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: SecurityConstraint.java From everrest with Eclipse Public License 2.0 | 6 votes |
/** * Check does <tt>method</tt> contains one on of security annotations PermitAll, DenyAll, RolesAllowed. * * @see PermitAll * @see DenyAll * @see RolesAllowed */ @Override public void accept(GenericResourceMethod method, Object[] params) throws WebApplicationException { for (Annotation annotation : method.getAnnotations()) { Class<?> annotationType = annotation.annotationType(); if (annotationType == PermitAll.class) { return; } else if (annotationType == DenyAll.class) { throw new WebApplicationException(Response.status(FORBIDDEN) .entity("User not authorized to call this method").type(TEXT_PLAIN) .build()); } else if (annotationType == RolesAllowed.class) { SecurityContext security = ApplicationContext.getCurrent().getSecurityContext(); for (String role : ((RolesAllowed)annotation).value()) { if (security.isUserInRole(role)) { return; } } throw new WebApplicationException(Response.status(FORBIDDEN) .entity("User not authorized to call this method").type(TEXT_PLAIN) .build()); } } }
Example 2
Source File: PipelineStoreResource.java From datacollector with Apache License 2.0 | 6 votes |
@Path("/pipeline/{pipelineId}") @DELETE @ApiOperation(value = "Delete Pipeline Configuration by name", authorizations = @Authorization(value = "basic")) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ AuthzRole.CREATOR, AuthzRole.ADMIN, AuthzRole.CREATOR_REMOTE, AuthzRole.ADMIN_REMOTE }) public Response deletePipeline( @PathParam("pipelineId") String name, @Context SecurityContext context ) throws PipelineException { PipelineInfo pipelineInfo = store.getInfo(name); RestAPIUtils.injectPipelineInMDC(pipelineInfo.getTitle(), pipelineInfo.getPipelineId()); if (store.isRemotePipeline(name, "0") && !context.isUserInRole(AuthzRole.ADMIN) && !context.isUserInRole(AuthzRole.ADMIN_REMOTE)) { throw new PipelineException(ContainerError.CONTAINER_01101, "DELETE_PIPELINE", name); } store.deleteRules(name); store.delete(name); return Response.ok().build(); }
Example 3
Source File: ViewableWithPermissions.java From Bats with Apache License 2.0 | 6 votes |
private static Map<String, Object> createModel(final boolean authEnabled, final SecurityContext sc, final boolean showControls, final Object pageModel) { final boolean isAdmin = !authEnabled /* when auth is disabled every user is an admin user */ || (showControls && sc.isUserInRole(DrillUserPrincipal.ADMIN_ROLE)); final boolean isUserLoggedIn = AuthDynamicFeature.isUserLoggedIn(sc); final ImmutableMap.Builder<String, Object> mapBuilder = ImmutableMap.<String, Object>builder() .put("showStorage", isAdmin) .put("showOptions", isAdmin) .put("showThreads", isAdmin) .put("showLogs", isAdmin) .put("showLogin", authEnabled && showControls && !isUserLoggedIn) .put("showLogout", authEnabled && showControls && isUserLoggedIn) .put("loggedInUserName", authEnabled && showControls && isUserLoggedIn ? sc.getUserPrincipal().getName() : DrillUserPrincipal.ANONYMOUS_USER).put("showControls", showControls); if (pageModel != null) { mapBuilder.put("model", pageModel); } return mapBuilder.build(); }
Example 4
Source File: RolesEndpoint.java From microprofile-jwt-auth with Apache License 2.0 | 5 votes |
/** * This endpoint requires a Tester role, and also validates that the caller has the role Echoer by calling * {@linkplain SecurityContext#isUserInRole(String)}. * * @return principal name or FORBIDDEN error */ @GET @Path("/checkIsUserInRole") @RolesAllowed("Tester") public Response checkIsUserInRole(@Context SecurityContext sec) { Principal user = sec.getUserPrincipal(); Response response; if(!sec.isUserInRole("Echoer")) { response = Response.status(new Response.StatusType() { @Override public int getStatusCode() { return Response.Status.FORBIDDEN.getStatusCode(); } @Override public Response.Status.Family getFamily() { return Response.Status.FORBIDDEN.getFamily(); } @Override public String getReasonPhrase() { return "SecurityContext.isUserInRole(Echoer) was false"; } }).build(); } else { response = Response.ok(user.getName(), MediaType.TEXT_PLAIN).build(); } return response; }
Example 5
Source File: SaslTest.java From rest-utils with Apache License 2.0 | 5 votes |
@GET @Path("/role/{role}") @PerformanceMetric("role") public boolean hello( @PathParam("role") String role, @Context SecurityContext context ) { return context.isUserInRole(role); }
Example 6
Source File: AuthorizationFilter.java From iaf with Apache License 2.0 | 5 votes |
private boolean doAuth(SecurityContext securityContext, final Set<String> rolesSet) { for (String role : rolesSet) { if(securityContext.isUserInRole(role)) { return true; } } return false; }
Example 7
Source File: ManagerResource.java From datacollector with Apache License 2.0 | 5 votes |
@Path("/pipeline/{pipelineId}/stop") @POST @ApiOperation(value = "Stop Pipeline", response = PipelineStateJson.class, authorizations = @Authorization(value = "basic")) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ AuthzRole.MANAGER, AuthzRole.ADMIN, AuthzRole.MANAGER_REMOTE, AuthzRole.ADMIN_REMOTE }) public Response stopPipeline( @PathParam("pipelineId") String pipelineId, @QueryParam("rev") @DefaultValue("0") String rev, @Context SecurityContext context ) throws PipelineException { PipelineInfo pipelineInfo = store.getInfo(pipelineId); RestAPIUtils.injectPipelineInMDC(pipelineInfo.getTitle(), pipelineInfo.getPipelineId()); if (manager.isRemotePipeline(pipelineId, rev) && !context.isUserInRole(AuthzRole.ADMIN) && !context.isUserInRole(AuthzRole.ADMIN_REMOTE)) { throw new PipelineException(ContainerError.CONTAINER_01101, "STOP_PIPELINE", pipelineId); } Runner runner = manager.getRunner(pipelineId, rev); Utils.checkState(runner.getState().getExecutionMode() != ExecutionMode.SLAVE, "This operation is not supported in SLAVE mode"); runner.stop(user); return Response.ok() .type(MediaType.APPLICATION_JSON) .entity(BeanHelper.wrapPipelineState(runner.getState())).build(); }
Example 8
Source File: AclStoreResource.java From datacollector with Apache License 2.0 | 5 votes |
@Path("/{pipelineId}") @POST @ApiOperation(value ="Update Pipeline ACL", authorizations = @Authorization(value = "basic")) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @PermitAll @SuppressWarnings("unchecked") public Response saveAcl( @PathParam("pipelineId") String name, @Context SecurityContext context, AclJson aclJson ) throws PipelineException, URISyntaxException { PipelineInfo pipelineInfo = store.getInfo(name); RestAPIUtils.injectPipelineInMDC(pipelineInfo.getTitle(), pipelineInfo.getPipelineId()); Acl existingAcl = aclStore.getAcl(name); if (existingAcl != null) { // Only owner of the resource and admin is allowed to save the ACL if (!existingAcl.getResourceOwner().equals(currentUser.getName()) && !context.isUserInRole(AuthzRole.ADMIN) && !context.isUserInRole(AuthzRole.ADMIN_REMOTE)) { throw new PipelineException(ContainerError.CONTAINER_01201, name); } } else { // If there is no ACL info stored, only owner of pipeline and admin is allowed save ACL if (!pipelineInfo.getCreator().equals(currentUser.getName()) && !context.isUserInRole(AuthzRole.ADMIN) && !context.isUserInRole(AuthzRole.ADMIN_REMOTE)) { throw new PipelineException(ContainerError.CONTAINER_01201, name); } } aclStore.saveAcl(name, AclDtoJsonMapper.INSTANCE.asAclDto(aclJson)); return Response.ok().build(); }
Example 9
Source File: AclStoreResource.java From datacollector with Apache License 2.0 | 5 votes |
@Path("/{pipelineId}") @GET @ApiOperation(value ="Get Pipeline ACL", authorizations = @Authorization(value = "basic")) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @PermitAll @SuppressWarnings("unchecked") public Response getAcl( @PathParam("pipelineId") String name, @Context SecurityContext context ) throws PipelineException, URISyntaxException { PipelineInfo pipelineInfo = store.getInfo(name); RestAPIUtils.injectPipelineInMDC(pipelineInfo.getTitle(), pipelineInfo.getPipelineId()); Acl acl = aclStore.getAcl(name); if (acl == null && currentUser != null && (pipelineInfo.getCreator().equals(currentUser.getName()) || context.isUserInRole(AuthzRole.ADMIN) || context.isUserInRole(AuthzRole.ADMIN_REMOTE))) { // If no acl, only owner of the pipeline will have all permission acl = new Acl(); acl.setResourceId(name); acl.setResourceOwner(pipelineInfo.getCreator()); acl.setResourceType(ResourceType.PIPELINE); acl.setResourceCreatedTime(pipelineInfo.getCreated().getTime()); acl.setLastModifiedBy(pipelineInfo.getCreator()); acl.setLastModifiedOn(System.currentTimeMillis()); Permission ownerPermission = new Permission(); ownerPermission.setSubjectId(pipelineInfo.getCreator()); ownerPermission.setSubjectType(SubjectType.USER); ownerPermission.setLastModifiedOn(pipelineInfo.getCreated().getTime()); ownerPermission.setLastModifiedBy(pipelineInfo.getCreator()); ownerPermission.getActions().addAll(ResourceType.PIPELINE.getActions()); acl.getPermissions().add(ownerPermission); } return Response.ok(AclDtoJsonMapper.INSTANCE.toAclJson(acl)).build(); }
Example 10
Source File: MPJWTSecurityAnnotationsInterceptor.java From tomee with Apache License 2.0 | 5 votes |
@Override public void filter(final ContainerRequestContext requestContext) throws IOException { if (permitAll.contains(resourceInfo.getResourceMethod())) { return; } if (denyAll.contains(resourceInfo.getResourceMethod())) { forbidden(requestContext); return; } final Set<String> roles = rolesAllowed.get(resourceInfo.getResourceMethod()); if (roles != null && !roles.isEmpty()) { final SecurityContext securityContext = requestContext.getSecurityContext(); boolean hasAtLeasOneValidRole = false; for (String role : roles) { if (securityContext.isUserInRole(role)) { hasAtLeasOneValidRole = true; break; } } if (!hasAtLeasOneValidRole) { forbidden(requestContext); } } }
Example 11
Source File: RolesEndpoint.java From microprofile-jwt-auth with Apache License 2.0 | 5 votes |
/** * This endpoint requires a role that is mapped to the group1 role * @return principal name */ @GET @Path("/needsGroup1Mapping") @RolesAllowed("Group1MappedRole") public String needsGroup1Mapping(@Context SecurityContext sec) { Principal user = sec.getUserPrincipal(); sec.isUserInRole("group1"); return user.getName(); }
Example 12
Source File: RolesEndpoint.java From quarkus with Apache License 2.0 | 5 votes |
/** * This endpoint requires a role that is mapped to the group1 role * * @return principal name */ @GET @Path("/needsGroup1Mapping") @RolesAllowed("Group1MappedRole") public String needsGroup1Mapping(@Context SecurityContext sec) { Principal user = sec.getUserPrincipal(); if (sec.isUserInRole("group1")) { return user.getName(); } else { return "User not in role group1"; } }
Example 13
Source File: ClientRegistrationService.java From cxf-fediz with Apache License 2.0 | 5 votes |
private void checkSecurityContext() { SecurityContext sc = mc.getSecurityContext(); if (sc == null || sc.getUserPrincipal() == null) { throw ExceptionUtils.toNotAuthorizedException(null, null); } if (userRole != null && !sc.isUserInRole(userRole)) { throw ExceptionUtils.toForbiddenException(null, null); } }
Example 14
Source File: JwtResource.java From boost with Eclipse Public License 1.0 | 5 votes |
@GET @RolesAllowed({ "admin" }) @Path("/customClaim") public Response getCustomClaim(@Context SecurityContext securityContext) { if (securityContext.isUserInRole("admin")) { String customClaim = jwtPrincipal.getClaim("customClaim"); return Response.ok(customClaim).build(); } else { System.out.println("Error user is not in role admin"); return Response.status(Response.Status.FORBIDDEN).build(); } }
Example 15
Source File: ThreadLocalSecurityContext.java From tomee with Apache License 2.0 | 5 votes |
public boolean isUserInRole(final String role) { if (service().isCallerInRole(role)) { return true; } final SecurityContext sc = get(); return sc != null && sc.isUserInRole(role); }
Example 16
Source File: InfoResource.java From datacollector with Apache License 2.0 | 4 votes |
@GET @Path("/info/currentUser") @ApiOperation(value = "Returns User Info", response = Map.class, authorizations = @Authorization(value = "basic")) @Produces(MediaType.APPLICATION_JSON) @PermitAll public Response getUserInfo(@Context SecurityContext context) throws PipelineException, IOException { Map<String, Object> map = new HashMap<>(); String user; List<String> roles = new ArrayList<>(); List<String> groups = new ArrayList<>(); Principal principal = context.getUserPrincipal(); if(principal != null) { user = principal.getName(); if (context.isUserInRole(AuthzRole.GUEST) || context.isUserInRole(AuthzRole.GUEST_REMOTE)) { roles.add(AuthzRole.GUEST); } if (context.isUserInRole(AuthzRole.MANAGER) || context.isUserInRole(AuthzRole.MANAGER_REMOTE)) { roles.add(AuthzRole.MANAGER); } if (context.isUserInRole(AuthzRole.CREATOR) || context.isUserInRole(AuthzRole.CREATOR_REMOTE)) { roles.add(AuthzRole.CREATOR); } if (context.isUserInRole(AuthzRole.ADMIN) || context.isUserInRole(AuthzRole.ADMIN_REMOTE)) { roles.add(AuthzRole.ADMIN); } else if (context.isUserInRole(AuthzRole.ADMIN_ACTIVATION)) { roles.add(AuthzRole.ADMIN_ACTIVATION); } if (context.isUserInRole(DisconnectedAuthentication.DISCONNECTED_MODE_ROLE)) { roles.add(DisconnectedAuthentication.DISCONNECTED_MODE_ROLE); } } else { //In case of http.authentication=none user = "admin"; roles.add(AuthzRole.ADMIN); } UserJson userJson = userGroupManager.getUser(principal); map.put("user", user); map.put("roles", roles); map.put("groups", userJson != null ? userJson.getGroups() : null); return Response.status(Response.Status.OK).entity(map).build(); }
Example 17
Source File: PipelineStoreResource.java From datacollector with Apache License 2.0 | 4 votes |
@Path("/pipelines/deleteByFiltering") @POST @ApiOperation(value = "Deletes filtered Pipelines", response = PipelineInfoJson.class, responseContainer = "List", authorizations = @Authorization(value = "basic")) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ AuthzRole.CREATOR, AuthzRole.ADMIN, AuthzRole.CREATOR_REMOTE, AuthzRole.ADMIN_REMOTE }) public Response deletePipelinesByFiltering( @QueryParam("filterText") @DefaultValue("") String filterText, @QueryParam("label") String label, @Context SecurityContext context ) throws PipelineException { RestAPIUtils.injectPipelineInMDC("*"); List<PipelineInfo> pipelineInfoList = store.getPipelines(); List<String> deletepipelineIds = new ArrayList<>(); for(PipelineInfo pipelineInfo: pipelineInfoList) { if (filterText != null && !pipelineInfo.getPipelineId().toLowerCase().contains(filterText.toLowerCase())) { continue; } if (label != null) { Map<String, Object> metadata = pipelineInfo.getMetadata(); if (metadata != null && metadata.containsKey("labels")) { List<String> labels = (List<String>) metadata.get("labels"); if (!labels.contains(label)) { continue; } } else { continue; } } if (store.isRemotePipeline(pipelineInfo.getPipelineId(), "0") && !context.isUserInRole(AuthzRole.ADMIN) && !context.isUserInRole(AuthzRole.ADMIN_REMOTE)) { continue; } store.deleteRules(pipelineInfo.getPipelineId()); store.delete(pipelineInfo.getPipelineId()); deletepipelineIds.add(pipelineInfo.getPipelineId()); } return Response.ok().entity(deletepipelineIds).build(); }
Example 18
Source File: ClusterResource.java From datacollector with Apache License 2.0 | 4 votes |
@GET @Path("/redirectToSlave") @PermitAll public Response redirectToSlaveInstance( @QueryParam("name") String name, @QueryParam("rev") @DefaultValue("0") String rev, @QueryParam("sdcURL") String sdcURL, @Context final HttpServletResponse response, @Context SecurityContext context) throws IOException, PipelineException { Runner runner = manager.getRunner(name, rev); Collection<CallbackInfo> callbackInfoCollection = runner.getSlaveCallbackList(CallbackObjectType.METRICS); CallbackInfo slaveCallbackInfo = null; for(CallbackInfo callbackInfo : callbackInfoCollection) { if(sdcURL.equals(callbackInfo.getSdcURL())) { slaveCallbackInfo = callbackInfo; } } if(slaveCallbackInfo != null) { String user; List<String> authTokens = new ArrayList<>(); Principal principal = context.getUserPrincipal(); if(principal != null) { user = principal.getName(); if (context.isUserInRole(AuthzRole.GUEST) || context.isUserInRole(AuthzRole.GUEST_REMOTE)) { authTokens.add(slaveCallbackInfo.getGuestToken()); } if (context.isUserInRole(AuthzRole.MANAGER) || context.isUserInRole(AuthzRole.MANAGER_REMOTE)) { authTokens.add(slaveCallbackInfo.getManagerToken()); } if (context.isUserInRole(AuthzRole.CREATOR) || context.isUserInRole(AuthzRole.CREATOR_REMOTE)) { authTokens.add(slaveCallbackInfo.getCreatorToken()); } if (context.isUserInRole(AuthzRole.ADMIN) || context.isUserInRole(AuthzRole.ADMIN_REMOTE)) { authTokens.add(slaveCallbackInfo.getAdminToken()); } } else { //In case of http.authentication=none user = "admin"; authTokens.add(slaveCallbackInfo.getAdminToken()); } Joiner joiner = Joiner.on( "," ).skipNulls(); String slaveURL = slaveCallbackInfo.getSdcURL() + "/collector/pipeline/" + name + "?auth_user=" + user + "&auth_token=" + joiner.join(authTokens); response.sendRedirect(slaveURL); } else { throw new RuntimeException("No Slave Instance found with URL - " + sdcURL); } return Response.ok().build(); }
Example 19
Source File: SecurityContextFilter.java From quarkus with Apache License 2.0 | 4 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { SecurityContext modified = requestContext.getSecurityContext(); if (modified instanceof ServletSecurityContext || modified instanceof QuarkusResteasySecurityContext) { //an original security context, it has not been modified return; } Set<Credential> oldCredentials = old.getCredentials(); Map<String, Object> oldAttributes = old.getAttributes(); SecurityIdentity newIdentity = new SecurityIdentity() { @Override public Principal getPrincipal() { return modified.getUserPrincipal(); } @Override public boolean isAnonymous() { return modified.getUserPrincipal() == null; } @Override public Set<String> getRoles() { throw new UnsupportedOperationException( "retrieving all roles not supported when JAX-RS security context has been replaced"); } @Override public boolean hasRole(String role) { return modified.isUserInRole(role); } @Override public <T extends Credential> T getCredential(Class<T> credentialType) { for (Credential cred : getCredentials()) { if (credentialType.isAssignableFrom(cred.getClass())) { return (T) cred; } } return null; } @Override public Set<Credential> getCredentials() { return oldCredentials; } @Override public <T> T getAttribute(String name) { return (T) oldAttributes.get(name); } @Override public Map<String, Object> getAttributes() { return oldAttributes; } @Override public Uni<Boolean> checkPermission(Permission permission) { return Uni.createFrom().nullItem(); } }; currentIdentityAssociation.setIdentity(newIdentity); }
Example 20
Source File: ManagerResource.java From datacollector with Apache License 2.0 | 4 votes |
@Path("/pipelines/stop") @POST @ApiOperation(value = "Stop multiple Pipelines", response = MultiStatusResponseJson.class, authorizations = @Authorization(value = "basic")) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ AuthzRole.MANAGER, AuthzRole.ADMIN, AuthzRole.MANAGER_REMOTE, AuthzRole.ADMIN_REMOTE }) public Response stopPipelines( List<String> pipelineIds, @Context SecurityContext context ) throws StageException, PipelineException { List<PipelineState> successEntities = new ArrayList<>(); List<String> errorMessages = new ArrayList<>(); for (String pipelineId: pipelineIds) { if (pipelineId != null) { PipelineInfo pipelineInfo = store.getInfo(pipelineId); RestAPIUtils.injectPipelineInMDC(pipelineInfo.getTitle(), pipelineInfo.getPipelineId()); if (manager.isRemotePipeline(pipelineId, "0") && !context.isUserInRole(AuthzRole.ADMIN) && !context.isUserInRole(AuthzRole.ADMIN_REMOTE)) { errorMessages.add("Cannot stop a remote pipeline: " + pipelineId); continue; } Runner runner = manager.getRunner(pipelineId, "0"); try { Utils.checkState(runner.getState().getExecutionMode() != ExecutionMode.SLAVE, "This operation is not supported in SLAVE mode"); runner.stop(user); successEntities.add(runner.getState()); } catch (Exception ex) { errorMessages.add("Failed stopping pipeline: " + pipelineId + ". Error: " + ex.getMessage()); } } } return Response.status(207) .type(MediaType.APPLICATION_JSON) .entity(new MultiStatusResponseJson<>(successEntities, errorMessages)).build(); }