# Java how to specify scopes in calls (without rely on client)

**URL:** <https://forum.keycloak.org/t/java-how-to-specify-scopes-in-calls-without-rely-on-client/2250>\
**Category:** Securing applications\
**Created:** [April 20, 2020, 5:01pm UTC](https://forum.keycloak.org/t/java-how-to-specify-scopes-in-calls-without-rely-on-client/2250 "2020-04-20T17:01:24Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![bssdev](https://avatars.discourse-cdn.com/v4/letter/b/ee7513/32.png) [@bssdev](https://forum.keycloak.org/u/bssdev)\
**Post date:** [April 20, 2020, 5:01pm UTC](https://forum.keycloak.org/t/java-how-to-specify-scopes-in-calls-without-rely-on-client/2250/1 "2020-04-20T17:01:24Z")

</div>

I defined 5 scopes : create,read,update,delete,print.

I have a lot of Java classes exposed as web services that implements the same abstract class.

Suppose I have

```
@Path("orders")
public class OrderController implement AbstractController<Order>{
}

```

and the abstract class has the common methods

```
public abstract AbstractController<T>{

     @Path("read/{id}")
     public T getRecord(@PathParam(value="id") Long id ){
          ....
     }

     @Path("delete/{id}")
     public void deleteRecord(@PathParam(value="id") Long id ){
          ....
     }
}

```

I have created a resource for urls “orders/\*”, let’s call `OrderResource`.  
I have created 2 policies for 2 roles : _role\_manager_, _role\_user_

Now I want to create 2 scope permissions:

1. resource = OrderResource, scope=read, policy=role\_user

2. resource = OrderResource, scope=read,delete, policy=role\_manager

How can i specify that _order/read_ requires the scope “read” and _order/delete_ requires scope “delete” ?

---

<div class="post-metadata">

**Author:** ![Robinyo](https://avatars.discourse-cdn.com/v4/letter/r/dec6dc/32.png) [@Robinyo](https://forum.keycloak.org/u/Robinyo)\
**Post date:** [April 20, 2020, 8:26pm UTC](https://forum.keycloak.org/t/java-how-to-specify-scopes-in-calls-without-rely-on-client/2250/2 "2020-04-20T20:26:40Z")

</div>

If you are using Spring Security then you can use the `@PreAuthorize` annotation, for example:

```auto
  @GetMapping("/individuals/{id}")
  @PreAuthorize("hasAuthority('SCOPE_individual:read')")
  public ResponseEntity<EntityModel<Individual>> findById(
      @PathVariable("id") final Long id) throws ResponseStatusException {
    
    Individual entity = entityService.findById(id).orElseThrow(() -> 
        new ResponseStatusException(HttpStatus.NOT_FOUND));
    
    return ResponseEntity.ok(assembler.toModel(entity));
  }

```

Ref: [Flowable OAuth2 Resource Server](https://robferguson.org/blog/2020/02/05/flowable-oauth2-resource-server/)

---

<div class="post-metadata">

**Author:** ![bssdev](https://avatars.discourse-cdn.com/v4/letter/b/ee7513/32.png) [@bssdev](https://forum.keycloak.org/u/bssdev)\
**Post date:** [April 21, 2020, 8:52am UTC](https://forum.keycloak.org/t/java-how-to-specify-scopes-in-calls-without-rely-on-client/2250/3 "2020-04-21T08:52:34Z")

</div>

> [@Robinyo](#):
>
> @PreAuthorize

I’am sorry but I’am not using Spring.

I’am trying with `javax.ws.rs.container.ContainerRequestFilter`. If it works, i’ll post my solution. I’am using the “picketlink way”, something like the old `org.picketlink.http.authorization.PathAuthorizer`

Anyway if a stardard way exists, I would use it.

---

<div class="post-metadata">

**Author:** ![bssdev](https://avatars.discourse-cdn.com/v4/letter/b/ee7513/32.png) [@bssdev](https://forum.keycloak.org/u/bssdev)\
**Post date:** [April 21, 2020, 11:06am UTC](https://forum.keycloak.org/t/java-how-to-specify-scopes-in-calls-without-rely-on-client/2250/4 "2020-04-21T11:06:38Z")

</div>

I don’t know if I doing it in the right way…

In my methods I have added an annotation (i did it for picketlink)

```
 @RequiredPermission(scope="read")

```

So, i get an url = /webservice/order/get

I search what class match to the url ( @Path(“order”) → OrderController.java ), then I get the method (@Path(“get”)-\> getById(Long id) ) and I read the annotation.

So I know that the method require a read-permission.

```
@Provider
@Priority(value = Priorities.AUTHORIZATION)
public class SecurityFilter implements ContainerRequestFilter {

     @Override
     public void filter(ContainerRequestContext requestContext) throws IOException {
             ... // getting scopes by java reflection
            RefreshableKeycloakSecurityContext keycloakSecurityContext = (RefreshableKeycloakSecurityContext) servletRequest.getAttribute(KeycloakSecurityContext.class.getName());
            if(keycloakSecurityContext != null){
                AuthorizationContext authzContext = keycloakSecurityContext.getAuthorizationContext();
                Boolean result = true;
                if(scopes != null){
                    for(String scope : scopes){
                        result = result && authzContext.hasScopePermission(scope);
                    }
                }
                if(!result)
                    throw new NotAllowedException("Non hai i permessi");
            }

     }
}

```

Problem : supposing I resolve a class cast exception (😛 ), i have refused not allowed request, but how i can allow the other calls?

If it’s the wrong way, are there some headers to add saying “this method is requesting a read scope” ?

I have the url/request/java method, i have the scopes, now I need to match them together
