커스텀 인증 추가하기

커스텀 인증 추가하기

이 가이드는 LangSmith 애플리케이션에 커스텀 인증을 추가하는 방법을 보여줘요. 이 페이지의 단계는 클라우드셀프 호스팅 배포 모두에 적용돼요. 자체 커스텀 서버에서 LangGraph 오픈 소스 라이브러리를 단독으로 사용하는 경우에는 적용되지 않아요.

출처: 문서

본문

배포에 커스텀 인증 추가하기

배포에서 커스텀 인증을 활용하고 사용자 수준 메타데이터에 접근하려면, 커스텀 인증 핸들러를 통해 config["configurable"]["langgraph_auth_user"] 객체를 자동으로 채우도록 커스텀 인증을 설정하세요. 그런 다음 그래프에서 langgraph_auth_user 키로 이 객체에 접근해 에이전트가 사용자를 대신해 인증된 작업을 수행하도록 할 수 있어요.

  1. 인증을 구현하세요:

    커스텀 @auth.authenticate 핸들러가 없으면 LangGraph는 API 키 소유자(보통 개발자)만 볼 수 있어서 요청이 개별 최종 사용자에게 범위가 한정되지 않아요. 커스텀 토큰을 전파하려면 자체 핸들러를 구현해야 해요.

    from langgraph_sdk import Auth
    import requests
    
    auth = Auth()
    
    def is_valid_key(api_key: str) -> bool:
        is_valid = # your API key validation logic
        return is_valid
    
    @auth.authenticate # (1)!
    async def authenticate(headers: dict) -> Auth.types.MinimalUserDict:
        api_key = headers.get(b"x-api-key")
        if not api_key or not is_valid_key(api_key):
            raise Auth.exceptions.HTTPException(status_code=401, detail="Invalid API key")
    
        # Fetch user-specific tokens from your secret store
        user_tokens = await fetch_user_tokens(api_key)
    
        return { # (2)!
            "identity": api_key,  #  fetch user ID from LangSmith
            "github_token" : user_tokens.github_token
            "jira_token" : user_tokens.jira_token
            # ... custom fields/secrets here
        }
    
  • 이 핸들러는 요청(헤더 등)을 받아 사용자를 검증하고 최소한 identity 필드를 가진 사전을 반환해요.
  • 원하는 커스텀 필드를 추가할 수 있어요 (예: OAuth 토큰, 역할, 조직 ID 등).
  1. langgraph.json에 인증 파일 경로를 추가하세요:

    {
        "dependencies": ["."],
        "graphs": {
        "agent": "./agent.py:graph"
        },
        "env": ".env",
        "auth": {
            "path": "./auth.py:my_auth"
        }
    }
    
  2. 서버에 인증을 설정했다면, 요청은 선택한 방식에 따라 필수 인증 정보를 포함해야 해요. JWT 토큰 인증을 사용한다고 가정하면, 다음 방법 중 하나로 배포에 접근할 수 있어요:

Python Client:

from langgraph_sdk import get_client

my_token = "your-token" # In practice, you would generate a signed token with your auth provider
client = get_client(
    url="http://localhost:2024",
    headers={"Authorization": f"Bearer {my_token}"}
)
threads = await client.threads.search()

Python RemoteGraph:

from langgraph.pregel.remote import RemoteGraph

my_token = "your-token" # In practice, you would generate a signed token with your auth provider
remote-graph = RemoteGraph(
    "agent",
    url="http://localhost:2024",
    headers={"Authorization": f"Bearer {my_token}"}
)
threads = await remote-graph.ainvoke(...)

JavaScript Client:

import { Client } from "@langchain/langgraph-sdk";

const my_token = "your-token"; // In practice, you would generate a signed token with your auth provider
const client = new Client({
apiUrl: "http://localhost:2024",
defaultHeaders: { Authorization: *** ${my_token}` },
});
const threads = await client.threads.search();

JavaScript RemoteGraph:

import { RemoteGraph } from "@langchain/langgraph/remote";

const my_token = "your-token"; // In practice, you would generate a signed token with your auth provider
const remoteGraph = new RemoteGraph({
graphId: "agent",
url: "http://localhost:2024",
headers: { Authorization: *** ${my_token}` },
});
const threads = await remoteGraph.invoke(...);

cURL:

curl -H "Authorization: Bearer ***" http://localhost:2024/threads

RemoteGraph에 대한 자세한 내용은 RemoteGraph 사용하기 가이드를 참고하세요.

에이전트 인증 활성화하기

인증 후 플랫폼은 LangSmith 배포에 전달되는 특수 구성 객체(config)를 만들어요. 이 객체는 @auth.authenticate 핸들러에서 반환한 커스텀 필드를 포함해 현재 사용자에 대한 정보를 담아요.

에이전트가 사용자를 대신해 인증된 작업을 수행하도록 하려면 그래프에서 langgraph_auth_user 키로 이 객체에 접근하세요:

def my_node(state, config):
    user_config = config["configurable"].get("langgraph_auth_user")
    # token was resolved during the @auth.authenticate function
    token = user_config.get("github_token","")
    ...

사용자 자격 증명은 보안 시크릿 스토어에서 가져오세요. 그래프 상태에 시크릿을 저장하는 것은 권장되지 않아요.

Studio 사용자 권한 부여

기본적으로 리소스에 커스텀 권한 부여를 추가하면 이는 Studio에서 이루어지는 상호작용에도 적용돼요. 로그인한 Studio 사용자를 다르게 처리하고 싶다면 is_studio_user()를 확인하면 돼요.

is_studio_user는 langgraph-sdk 버전 0.1.73에서 추가됐어요. 더 오래된 버전이라면 isinstance(ctx.user, StudioUser)를 확인할 수도 있어요.

from langgraph_sdk.auth import is_studio_user, Auth
auth = Auth()

# ... Setup authenticate, etc.

@auth.on
async def add_owner(
    ctx: Auth.types.AuthContext,
    value: dict  # The payload being sent to this access method
) -> dict:  # Returns a filter dict that restricts access to resources
    if is_studio_user(ctx.user):
        return {}

    filters = {"owner": ctx.user.identity}
    metadata = value.setdefault("metadata", {})
    metadata.update(filters)
    return filters

매니지드 LangSmith SaaS에 배포된 그래프에 개발자 접근을 허용하려는 경우에만 이것을 사용하세요.

더 알아보기

더 알아보기 (Learn more)