如何使用Keycloak authzClient评估权限?

时间:2020-11-12 11:29:29

标签: java keycloak

我在通过远程API使用以下代码创建的Keycloak上拥有受保护的资源:

    private fun ProtectedEntity.protect(location: URI, principal: Principal) {
        val newResource = ResourceRepresentation()
        newResource.name = this.id
        newResource.displayName = this.name
        newResource.type = "urn:$appName:resources:${this.javaClass.simpleName.toLowerCase().replace("entity", "")}"
        newResource.owner = ResourceOwnerRepresentation(this.creator)
        newResource.ownerManagedAccess = true
        newResource.uris = setOf(location.path.toString())
        authzClient.protection().resource().create(newResource)
    }

资源所有者是调用该方法的用户,他可以管理自己的资源。

现在,我必须检查用户是否具有访问资源的权限,如果没有,我想我应该在用户想要访问资源的情况下退还票证。我尝试了此操作,但是authorize()抛出“创建权限票证时出错”。

override fun read(id: ID, principal: Principal): Mono<ResponseEntity<E>> {
        val currentUserToken = principal!!.getCurrentUserToken()
        val resource = authzClient.protection().resource().findByName(id.toString(), currentUserToken.getUsername())
        val token = currentUserToken.tokenValue
        val request = AuthorizationRequest()
        request.addPermission(resource.id)
        request.setRpt(token)

        // This returns Error creating permission ticket !?
        val response = authzClient.authorization().authorize(request)
        val result = authzClient.protection().introspectRequestingPartyToken(response.token)
        println(result.active)
        if (result.active) {
           return super.read(id, principal)
        } else throw RuntimeException("Result token RPT is not active!")
}

如何使用authzClient委托Keycloak权限评估?

1 个答案:

答案 0 :(得分:0)

解决方案是将.findByUri()替换为.findByUri()。该端点未考虑资源所有者。我创建了要点,以防其他人需要它:ResourceAccessKeycloakWebFilter