GithubHelp home page GithubHelp logo

authzed / authzed-java Goto Github PK

View Code? Open in Web Editor NEW
19.0 5.0 6.0 3.99 MB

Official SpiceDB client library for JVM languages

Home Page: https://docs.authzed.com/reference/api

License: Apache License 2.0

Java 100.00%
java permissions authorization authzed zanzibar sdk clojure java-library fine-grained-authorization fine-grained-access-control

authzed-java's Introduction

Authzed Java Client

Maven Metadata License Build Status Discord Server Twitter

This repository houses the Java client library for SpiceDB.

SpiceDB is a database and service that stores, computes, and validates your application's permissions.

Developers create a schema that models their permissions requirements and use a client library, such as this one, to apply the schema to the database, insert data into the database, and query the data to efficiently check permissions in their applications.

Supported client API versions:

You can find more info on each API on the SpiceDB API reference documentation. Additionally, Protobuf API documentation can be found on the Buf Registry SpiceDB API repository. Documentation for the latest Java client release is available as Javadoc.

See CONTRIBUTING.md for instructions on how to contribute and perform common tasks like building the project and running tests.

Getting Started

We highly recommend following the Protecting Your First App guide to learn the latest best practice to integrate an application with SpiceDB.

If you're interested in examples for a specific version of the API, they can be found in their respective folders in the examples directory.

Basic Usage

Installation

This project is packaged as the artifact authzed under the com.authzed.api group on Maven Central. You can find the commands for installing the jar for various JVM toolchains on the Maven Central Artifact Page.

Most commonly, if you are using Maven you can add the following to your pom.xml:

<dependencies>
    <dependency>
        <groupId>com.authzed.api</groupId>
        <artifactId>authzed</artifactId>
        <version>0.8.0</version>
    </dependency>
    <dependency>
        <groupId>io.grpc</groupId>
        <artifactId>grpc-protobuf</artifactId>
        <version>1.62.2</version>
    </dependency>
    <dependency>
        <groupId>io.grpc</groupId>
        <artifactId>grpc-stub</artifactId>
        <version>1.62.2</version>
    </dependency>
</dependencies>

If you are using Gradle then add the following to your build.gradle file:

dependencies {
    implementation "com.authzed.api:authzed:0.7.0"
    implementation 'io.grpc:grpc-protobuf:1.62.2'
    implementation 'io.grpc:grpc-stub:1.62.2'
}

Initializing a client

Because of how grpc-java is designed, there is little in terms of abstraction over the gRPC APIs underpinning Authzed. A ManagedChannel will establish a connection to Authzed that can be shared with stubs for each gRPC service. In order to successfully authenticate with the API, you will have to provide a Bearer Token with your own API Token from the Authzed dashboard or your local SpiceDB instance in place of t_your_token_here_1234567deadbeef as CallCredentials for each stub:

package org.example;

import com.authzed.api.v1.PermissionsServiceGrpc;
import com.authzed.grpcutil.BearerToken;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class PermissionServiceExample {
    public static void main(String[] args) {
        ManagedChannel channel = ManagedChannelBuilder
                .forTarget("grpc.authzed.com:443")
                .useTransportSecurity()
                .build();

        BearerToken bearerToken = new BearerToken("t_your_token_here_1234567deadbeef");
        PermissionsServiceGrpc.PermissionsServiceBlockingStub permissionsService = PermissionsServiceGrpc
                .newBlockingStub(channel)
                .withCallCredentials(bearerToken);
    }
}

In case of a local development instance of SpiceDB without TLS, configure your ManagedChannel as follows:

ManagedChannel channel = ManagedChannelBuilder
    .forTarget("localhost:50051")
    .usePlaintext()
    .build();

Performing an API call

Request and Response types are located in their respective gRPC Service packages and common types can be found in the Core package. Referring to the Authzed ProtoBuf Documentation is useful for discovering these APIs.

Because of the verbosity of these types, we recommend writing your own functions/methods to create these types from your existing application's models.

The following example initializes a permission client, performs a CheckPermission call and prints the result

package org.example;

import com.authzed.api.v1.Core;
import com.authzed.api.v1.PermissionService;
import com.authzed.api.v1.PermissionsServiceGrpc;
import com.authzed.grpcutil.BearerToken;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class ClientExample {
    public static void main(String[] args) {
        ManagedChannel channel = ManagedChannelBuilder
                .forTarget("localhost:50051")
                .usePlaintext()
                .build();

        BearerToken bearerToken = new BearerToken("t_your_token_here_1234567deadbeef");
        PermissionsServiceGrpc.PermissionsServiceBlockingStub permissionsService = PermissionsServiceGrpc
                .newBlockingStub(channel)
                .withCallCredentials(bearerToken);


        PermissionService.CheckPermissionRequest request = PermissionService.CheckPermissionRequest.newBuilder()
                .setConsistency(
                        PermissionService.Consistency.newBuilder()
                                .setMinimizeLatency(true)
                                .build())
                .setResource(
                        Core.ObjectReference.newBuilder()
                                .setObjectType("blog/post")
                                .setObjectId("1")
                                .build())
                .setSubject(
                        Core.SubjectReference.newBuilder()
                                .setObject(
                                        Core.ObjectReference.newBuilder()
                                                .setObjectType("blog/user")
                                                .setObjectId("emilia")
                                                .build())
                                .build())
                .setPermission("read")
                .build();

        // Is Emilia in the set of users that can read post #1?
        try {
            PermissionService.CheckPermissionResponse response = permissionsService.checkPermission(request);
            System.out.println("result: " + response.getPermissionship().getValueDescriptor().getName());
        } catch (Exception e) {
            System.out.println("Failed to check permission: " + e.getMessage());
        }
    }
}

authzed-java's People

Contributors

authzedbot avatar dependabot[bot] avatar jasonyao avatar josephschorr avatar jzelinskie avatar samkim avatar vroldanbet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

authzed-java's Issues

Publish Javadoc for Generated Java Bindings for Protobuf API

At the time of writing, it seems the only way to get the Javadoc for the generated bindings from the protobuf API -- that is, everything from the com.authzed.api.v1 package -- is to check out the repo and build them locally. While this works, it's a somewhat tedious flow for users who do not intend to make changes and only want to use the published library from public repos (i.e. Maven).

It would make transitioning from the provided examples to self-written code a little smoother if the Javadoc were more readily available.

How to squelch Netty debug Logs? (Set Log Level)

How do I disable noisy DEBUG logs like these:

│ 11:33:51.444 [grpc-nio-worker-ELG-1-2] DEBUG i.g.n.s.i.g.netty.NettyClientHandler - [id: 0x4ecdf329, L:/127.0.0.1:62354 - R:localhost/127.0.0.1:50051] INBOUND HEADERS: streamId=109 headers=GrpcHttp2ResponseHeaders[grpc-status: 0, grpc-message: , io.spicedb.respmeta.cachedoperationscount: 0, io.spicedb.respmeta.dispatchedoperationscount: 7] padding=0 endStream=true
│ 11:33:51.446 [grpc-nio-worker-ELG-1-2] DEBUG i.g.n.s.i.g.netty.NettyClientHandler - [id: 0x4ecdf329, L:/127.0.0.1:62354 - R:localhost/127.0.0.1:50051] OUTBOUND HEADERS: streamId=111 headers=GrpcHttp2OutboundHeaders[:authority: localhost:50051, :path: /authzed.api.v1.PermissionsService/ExpandPermissionTree, :method: POST, :scheme: http, content-type: application/grpc, te: trailers, user-agent: grpc-java-netty/1.55.1, grpc-accept-encoding: gzip, authorization: Bearer spicedb] streamDependency=0 weight=16 exclusive=false padding=0 endStream=false
│ 11:33:51.446 [grpc-nio-worker-ELG-1-2] DEBUG i.g.n.s.i.g.netty.NettyClientHandler - [id: 0x4ecdf329, L:/127.0.0.1:62354 - R:localhost/127.0.0.1:50051] OUTBOUND DATA: streamId=111 padding=0 endStream=true length=42 bytes=00000000250a02200112170a06736572766572120d6e6f742d6d792d7365727665721a067265626f6f74
│ 11:33:51.447 [grpc-nio-worker-ELG-1-2] DEBUG i.g.n.s.i.g.netty.NettyClientHandler - [id: 0x4ecdf329, L:/127.0.0.1:62354 - R:localhost/127.0.0.1:50051] INBOUND WINDOW_UPDATE: streamId=0 windowSizeIncrement=42

I'm using the Java AuthZed client from Clojure. I see that authzed-java uses java.util.logging.Logger, which according to this answer on SO supports a logging.properties file, but then you have to pass an argument to the Java call. I'm not sure how to do this.

Unable to Provide Bearer Token in PermissionsServiceGrpc.PermissionsServiceBlockingStub

Hello,

The README says that to provide Bearer Tokens to PermissionsServiceBlockingStub, the withCallCredentials() method is to be called on that object (as below):

import com.authzed.api.v1.PermissionsServiceGrpc;
import com.authzed.grpcutil.BearerToken;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

...

ManagedChannel channel = ManagedChannelBuilder
      .forTarget("grpc.authzed.com:443")
      .useTransportSecurity()
      .build();
PermissionsServiceGrpc.PermissionsServiceBlockingStub permissionsService = PermissionsServiceGrpc.newBlockingStub(channel)
      .withCallCredentials(new BearerToken("t_your_token_here_1234567deadbeef"));

However, on inspecting the code for PermissionsServiceBlockingStub, no such method exists. As such, there doesn't seem to be a way of providing this.

The same issue applies to similar classes like SchemaServiceBlockingStub

BearerToken not present in com.authzed.api maven import

Hi, thanks for making this great repo.

The readme instructions say to add the following maven dependency:

<dependency>
  <groupId>com.authzed.api</groupId>
  <artifactId>authzed</artifactId>
  <version>0.0.1</version>
</dependency>

and to import the following libraries:

import com.authzed.api.v0.ACLServiceGrpc;
import com.authzed.grpcutil.BearerToken;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

As far as I can tell, com.authzed.grpcutil.BearerToken is not present in the com.authzed.api jar so the only option is to get the source code and add it to the project manually.

If I have missed something please let me know, but otherwise I think it would be a lot more convenient if BearerToken was included in either com.authzed.api or its own maven dependency. I also looked for a com.authzed.grpcutil on maven but could not find anything.

gRPC version is out of sync in readme documentation, causing `NAME_RESOLUTION_DELAYED` errors

The problem

When pulling in the library versions described in the README.md file, trying to make rpcs will result in errors that look like the following:

java.lang.NoSuchFieldError: NAME_RESOLUTION_DELAYED
	at io.grpc.internal.ManagedChannelImpl$RealChannel$PendingCall.reprocess(ManagedChannelImpl.java:1089) ~[grpc-core-1.55.1.jar:1.55.1]
	at io.grpc.internal.ManagedChannelImpl$RealChannel.updateConfigSelector(ManagedChannelImpl.java:1019) ~[grpc-core-1.55.1.jar:1.55.1]
	at io.grpc.internal.ManagedChannelImpl$NameResolverListener$1NamesResolved.run(ManagedChannelImpl.java:1816) ~[grpc-core-1.55.1.jar:1.55.1]
	at io.grpc.SynchronizationContext.drain(SynchronizationContext.java:95) ~[grpc-api-1.54.1.jar:1.54.1]
	at io.grpc.SynchronizationContext.execute(SynchronizationContext.java:127) ~[grpc-api-1.54.1.jar:1.54.1]
	at io.grpc.internal.ManagedChannelImpl$NameResolverListener.onResult(ManagedChannelImpl.java:1868) ~[grpc-core-1.55.1.jar:1.55.1]
	at io.grpc.internal.RetryingNameResolver$RetryingListener.onResult(RetryingNameResolver.java:98) ~[grpc-core-1.55.1.jar:1.55.1]
	at io.grpc.internal.DnsNameResolver$Resolve.run(DnsNameResolver.java:333) ~[grpc-core-1.55.1.jar:1.55.1]
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144) ~[na:na]
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642) ~[na:na]
	at java.base/java.lang.Thread.run(Thread.java:1589) ~[na:na]

Steps to reproduce

  1. Pull in these dependencies
dependencies {
    implementation "com.authzed.api:authzed:0.5.0"
    implementation 'io.grpc:grpc-protobuf:1.54.1'
    implementation 'io.grpc:grpc-stub:1.54.1'
}
  1. Make a CheckPermissionRequest rpc

Solution

Update the README.md to point to the grpc version in https://github.com/authzed/authzed-java/blob/main/build.gradle#L80-L97 from the above to the following:

dependencies {
    implementation "com.authzed.api:authzed:0.5.0"
    implementation 'io.grpc:grpc-protobuf:1.55.1'
    implementation 'io.grpc:grpc-stub:1.55.1'
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.