0Pricing
GraphQL APIs with Spring Boot · 강의

지시문과 컨텍스트를 활용한 인가

GraphQL 지시문과 컨텍스트를 사용해 인가 규칙을 적용하고 필드와 작업에 대한 접근을 제어합니다.

지시문과 컨텍스트를 활용한 인가은(는) CoddyKit의 무료 GraphQL APIs with Spring Boot 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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.

자주 묻는 질문

“지시문과 컨텍스트를 활용한 인가” 강의는 무료인가요?

네 — “지시문과 컨텍스트를 활용한 인가” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 GraphQL APIs with Spring Boot 강의 전체를 잠금 해제할 수 있습니다. GraphQL APIs with Spring Boot 강의에는 총 4개의 강의가 포함되어 있습니다.

“지시문과 컨텍스트를 활용한 인가”에서 뭘 배우나요?

GraphQL 지시문과 컨텍스트를 사용해 인가 규칙을 적용하고 필드와 작업에 대한 접근을 제어합니다. 브라우저에서 직접 실행하는 실습 코드로 GraphQL APIs with Spring Boot을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

GraphQL APIs with Spring Boot을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 GraphQL APIs with Spring Boot은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“지시문과 컨텍스트를 활용한 인가” 강의는 얼마나 걸리나요?

대부분의 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(으)로 돌아가기