Include the latest library version in your gradle.build dependency block
kotlin {
//...
sourceSets {
val commonMain by getting {
dependencies {
implementation "com.ingonoka:grpc-endpoint-authentication:<latest>"
}
}
}
//...
}dependencies {
implementation "com.ingonoka:grpc-endpoint-authentication-jvm:<latest>"
}dependencies {
implementation "com.ingonoka:grpc-endpoint-authentication-android:<latest>"
}-
Create a token provider that will generate tokens, using an optional secret value, and a provider of a timestamp (the duration is not used on the client side).
-
Create an authentication service, using the token provider (the token policy is not used on the client side).
-
Create basic authentication credentials using a token that is generated by the authentication sevice
-
Use
.withCallCredentialsto add the credentials to your gRpc call stub.
val tokenProvider = TokenProviderV1Impl("s3cr3t") { Clock.System.now() }
val authenticationService = AuthenticationService(tokenProvider)
val token = authenticationService.generateToken(endpointIdentity).getOrThrow()
val credentials = BasicAuthenticationCallCredentials(token)
val stub = HeartbeatServiceGrpc.newStub(channel).withCallCredentials(credentials)-
Create a token provider using an optional secret, a duration and a time stamp provider.
-
Create an authentication service with the token provider and a token validation policy
-
Create an authentication interceptor with the authentication service
-
Add the authentication interceptor to the gRpc service
val tokenProvider = TokenProviderV1Impl("s3cr3t", 10.seconds) { Clock.System.now() }
val authenticationService = AuthenticationService(tokenProvider, TokenPolicy.REQUIRED)
val authenticationInterceptor = AuthenticationInterceptor(authenticationService)
val service = ServerBuilder.intercept(authenticationInterceptor)The token provider implementation Version 1 encrypts a timestamp on the client side and checks on the server side whether the timestamp is the same as the current time plus/minus the duration provided in the constructor.
If the provided duration is zero, no timestamp checks are performed.
The token policy determines whether the token is verified and whether a call with the wrong token will be rejected.
If the token policy is REQUIRED, then the token must be included in the call, and it must be correct for the call to be accepted.
If the token policy is OPTIONAL, then the token can be omitted, but it must be correct if it is included. This can be useful when authentication is rolled out to endpoints, i.e. some endpoints send a token and other do not.