0Pricing
GraphQL APIs with Spring Boot · 课时

使用指令与上下文进行授权

使用 GraphQL 指令和上下文应用授权规则,控制对字段和操作的访问。

使用指令与上下文进行授权 是 CoddyKit 上的免费 GraphQL APIs with Spring Boot 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 GraphQL APIs with Spring Boot 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 GraphQL APIs with Spring Boot 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What is Authorization?

Welcome! In this lesson, we'll dive into authorization, a critical aspect of API security. Authorization determines what an authenticated user is allowed to do or access.

  • Authentication: Verifies who you are (e.g., username/password).
  • Authorization: Verifies what you can do (e.g., access admin data).

Without proper authorization, even authenticated users might access sensitive data or perform actions they shouldn't.

Authorization Challenges in GraphQL

GraphQL's flexible nature presents unique authorization challenges compared to traditional REST APIs:

  • Field-level access: Clients can request specific fields. You might need to restrict access to individual fields within a type.
  • Nested data: Complex queries can fetch deeply nested data. Authorization checks need to apply throughout the query tree.
  • Dynamic roles: User roles and permissions can vary, requiring dynamic checks.

We need robust mechanisms to enforce these rules effectively.

Introducing GraphQL Directives

GraphQL directives are powerful features that allow you to extend the schema with custom logic. They are denoted by an @ symbol, like @deprecated or @skip.

Think of them as annotations for your schema. They can be attached to fields, types, arguments, and more, allowing you to add metadata or alter the execution behavior of your GraphQL API.

Custom Directive: @hasRole

We can define our own custom directives for authorization. A common example is an @hasRole directive. This directive would allow you to specify required roles directly in your schema.

Here's how you might define it in your Schema Definition Language (SDL):

directive @hasRole(role: String!) on FIELD_DEFINITION

This declares a directive named hasRole that takes a mandatory role argument (a String) and can only be applied to a FIELD_DEFINITION.

Spring Boot Directive Wiring

To make a custom directive functional in Spring Boot, you need to 'wire' it. This involves implementing the SchemaDirectiveWiring interface from graphql-java.

This wiring class intercepts the schema parsing process and allows you to modify how fields or types behave when your directive is encountered. It's where you'll inject your authorization logic.

Implementing Directive Logic

Inside your SchemaDirectiveWiring implementation, you'll override methods like onField. When the GraphQL engine processes a field with your @hasRole directive, this method is called.

Within onField, you can:

  • Extract the required role from the directive's arguments.
  • Get the current user's roles from the GraphQL Context.
  • Compare the roles and, if unauthorized, throw an exception or return null.

GraphQL Context for User Info

The GraphQL Context is a crucial object that accompanies every GraphQL request. It's like a backpack for your request, carrying request-scoped data that resolvers and directive wirings can access.

For authorization, the context is where you'll typically store information about the currently authenticated user, such as their ID, username, and crucially, their roles or permissions.

Integrating User Context (Runnable)

Here's a minimal Spring Boot app demonstrating how to inject user roles into the GraphQLContext. This context can then be accessed by your resolvers and directive wirings.

Try running this and querying myRoles to see the injected roles.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import graphql.kickstart.tools.GraphQLQueryResolver;
import graphql.schema.GraphQLContext;
import graphql.kickstart.servlet.context.GraphQLServletContextBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;
import javax.websocket.server.HandshakeRequest;
import java.util.Arrays;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
public class ContextDemoApp {

    public static void main(String[] args) {
        SpringApplication.run(ContextDemoApp.class, args);
    }

    // Resolver to show context access
    @Bean
    public GraphQLQueryResolver queryResolver() {
        return new GraphQLQueryResolver() {
            public List<String> myRoles(GraphQLContext context) {
                Map<String, Object> user = context.get("user");
                if (user != null && user.containsKey("roles")) {
                    return (List<String>) user.get("roles");
                } 
                return Arrays.asList("GUEST");
            }
        };
    }

    // Custom GraphQLContextBuilder to inject user data
    @Bean
    public GraphQLServletContextBuilder graphQLServletContextBuilder() {
        return new GraphQLServletContextBuilder() {
            @Override
            public GraphQLContext build(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
                Map<String, Object> user = new HashMap<>();
                user.put("id", "user123");
                user.put("name", "Coddy");
                user.put("roles", Arrays.asList("USER", "EDITOR")); // Mock roles
                GraphQLContext context = GraphQLContext.newContext().build();
                context.put("user", user); // Add user to context
                return context;
            }

            @Override
            public GraphQLContext build(Session session, HandshakeRequest handshakeRequest) {
                // Not used in typical HTTP requests, but required for interface
                return GraphQLContext.newContext().build();
            }
        };
    }
}

Applying Directives in Schema

Once your @hasRole directive is defined and wired up, you can apply it directly to your schema fields. This makes authorization rules declarative and easy to see.

For example, to restrict a field called adminDashboard to users with the ADMIN role:

type Query { myRoles: [String] adminDashboard: String @hasRole(role: "ADMIN") }

Now, any attempt to query adminDashboard will trigger your directive's logic, which checks the user's roles from the context.

Authorization Flow: Directive + Context

Let's put it all together. When a client queries a field like adminDashboard:

  1. The Spring Boot GraphQL runtime receives the request.
  2. The GraphQLContextBuilder populates the GraphQLContext with the authenticated user's details, including roles (as shown in the runnable example).
  3. The @hasRole directive wiring intercepts the adminDashboard field.
  4. Inside the directive's logic, it retrieves the required role ("ADMIN") from the directive arguments and the user's roles from the GraphQLContext.
  5. If the user has the required role, the query proceeds to the field's data resolver. Otherwise, an authorization error is returned.

Check Your Understanding

Which of the following best describes the primary purpose of the GraphQL Context in the context of authorization?

Recap: Directives & Context

You've learned how to implement robust authorization in GraphQL with Spring Boot!

  • Authorization controls what an authenticated user can access.
  • GraphQL Directives extend schema behavior, allowing declarative authorization rules like @hasRole.
  • The GraphQL Context is essential for carrying dynamic, request-scoped user information (like roles) to enable these authorization checks.

By combining directives and context, you can build secure and flexible GraphQL APIs.

常见问题解答

「使用指令与上下文进行授权」课时是免费的吗?

是的 — 「使用指令与上下文进行授权」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 GraphQL APIs with Spring Boot 课程的其余内容,请升级到 CoddyKit PRO。 GraphQL APIs with Spring Boot 课程共包含 4 节课。

「使用指令与上下文进行授权」这节课中我会学到什么?

使用 GraphQL 指令和上下文应用授权规则,控制对字段和操作的访问。 你通过在浏览器中直接运行的动手代码来练习 GraphQL APIs with Spring Boot,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 GraphQL APIs with Spring Boot 需要有经验吗?

无需任何先前经验。CoddyKit 上的 GraphQL APIs with Spring Boot 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「使用指令与上下文进行授权」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 GraphQL APIs with Spring Boot 课中编写并运行代码吗?

能。每节 GraphQL APIs with Spring Boot 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. GraphQL 中的自定义错误处理
  2. 使用 Spring Security 进行身份验证
  3. 使用指令与上下文进行授权
  4. 速率限制与查询深度保护
← 返回 GraphQL APIs with Spring Boot