question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Authorization in GraphQL

See original GitHub issue

Hello,

Is there any way to introduce authorization in GraphQL ?

So i have for example

  @GraphQLMutation(name = "createUser")
    @ValidationGroups(CreateChecks.class)
    public User createUser(@GraphQLArgument(name = "userRequest") @Valid UserRequest userRequest) throws ServiceException 
   
   @GraphQLQuery(name = "getUserById")
    public User getUserById(@GraphQLArgument(name = "id") @NotNull Integer id) throws ServiceException {
 

I want only users with a specific role (CREATE_USEr) can execute createUser.

I have the authorzation in the web tier (JAX-RS), but the entry point for all operation in GraphQL is in a single point, so i can’t do:


    @RolesAllowed(CREATE_USER)
    @POST
    @Path("/gql")
    public Object graphQL(GQLQuery gqlQuery) throws Exception { 
       //Executes the graph (invoques the service)
   }

because then only user with role CREATE_USER could execute getUserById and that’s not what i want- So is there any way to do that with graphQL ?

Thank you!

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
ferguardiolacommented, Jun 25, 2018

Hello again,

Well looking it can be done in guice with Interceptors.

  1. First we need an AuthFilter (I’m usgin JwtAuthFilter (JsonWebToken) in the filter we set the authentication we want. In that authenticator we load the user on a ThreadLocal variable
public class MyAuthenticator implements Authenticator<Map<String, ?>, User> {

 public Optional<User> authenticate(Map<String, ?> params) throws AuthenticationException {
   //Authenticate the user using the params in the map.. then you got the object User
  ActiveUser.set(user);
}


public class ActiveUser {

    private static InheritableThreadLocal<User> userThreadLocal = new InheritableThreadLocal<>();

    public static void set(User user) {
        userThreadLocal.set(user);
    }

    public static User get() {
        return userThreadLocal.get();
    }
}

  1. Create the Interceptor where we will check if the user has the roles we want. The roles are obtained from the annotated method in our service

public class AuthorizerInterceptor implements MethodInterceptor {

    public Object invoke(MethodInvocation invocation) throws Throwable {
        RolesAllowed rolesAllowed = invocation.getMethod().getAnnotation(RolesAllowed.class);
        if (ActiveUser.get().getAuthorizations().stream()
                .anyMatch(authorization -> Arrays.asList(rolesAllowed.value()).contains(authorization.getRole().getName()))) {
            return invocation.proceed();
        } else {
            throw new AuthorizationException("User " + ActiveUser.get().getUserName() + " not authorized");
        }
    }

}

  1. Annotae the service with the annotation we want to check (RolesAllowed) in this case
@RolesAllowed("MyRole")
@GraphQLMutation(name = "createUser")
 public User createUser(@GraphQLArgument(name = "userRequest") @Valid UserRequest userRequest) throws ServiceException {
   
  1. Bind the injector with GUICE

In the AbstractModule in GUICE

bindInterceptor(Matchers.any(), Matchers.annotatedWith(RolesAllowed.class), new AuthorizerInterceptor ());

Then it works!

0reactions
ashifqureshicommented, Aug 2, 2018

Hi Kaqqao,

When are you planning to release Authentication and Authorization support.

Thank you!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Authentication and authorization - Apollo GraphQL Docs
Control access to your GraphQL API · Authentication is determining whether a given user is logged in, and subsequently determining which user someone...
Read more >
Authorization - GraphQL
Authorization is a type of business logic that describes whether a given user/session/context has permission to perform an action or see a piece...
Read more >
Authorization Patterns in GraphQL - Oso
One place to consider building authorization is in the GraphQL resolver layer. GraphQL resolvers are the functions that fetch data for entries ...
Read more >
Handling authorization in GraphQL - Pusher
Authorization occurs after a successful authentication, it checks the access levels or privileges of the user, which will determine what the user can...
Read more >
Everything you need to know about GraphQL Authentication ...
Authorization entails giving users levels of access to a system. For example, in a bank, the bank manager has access to the bank...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found