> ## Documentation Index
> Fetch the complete documentation index at: https://stytch.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Attach

> Generate an OAuth Attach Token.

Generate an OAuth Attach Token to pre-associate an OAuth flow with an existing Stytch User. Pass the returned `oauth_attach_token` to the same provider's OAuth Start endpoint to treat this OAuth flow as a login for that user instead of a signup for a new user.

Exactly one of `user_id`, `session_token`, or `session_jwt` must be provided to identify the target Stytch User.

<Note>
  This is an optional step in the OAuth flow. Stytch can often determine whether to associate a new OAuth login with an existing User based on verified information (such as an email address) from the identity provider. This endpoint is useful for cases where we can't, such as missing or unverified provider information.
</Note>

See the [OAuth email address behavior guide](/consumer-auth/authentication/oauth/email-behavior) for additional information.


## OpenAPI

````yaml POST /v1/oauth/attach
openapi: 3.0.3
info:
  title: Stytch API
  description: The Stytch API provides endpoints for authentication and user management.
  version: 2.1.1
  contact:
    name: Stytch Support
    url: https://stytch.com/docs
    email: support@stytch.com
servers:
  - url: https://api.stytch.com
    description: Production server
  - url: https://test.stytch.com
    description: Test server
security:
  - basicAuth: []
paths:
  /v1/oauth/attach:
    post:
      tags:
        - Oauth
      summary: Attach
      description: >-
        Generate an OAuth Attach Token to pre-associate an OAuth flow with an
        existing Stytch User. Pass the returned `oauth_attach_token` to the same
        provider's OAuth Start endpoint to treat this OAuth flow as a login for
        that user instead of a signup for a new user.


        Exactly one of `user_id`, `session_token`, or `session_jwt` must be
        provided to identify the target Stytch User.


        **Note**: This is an optional step in the OAuth flow. Stytch can often
        determine whether to associate a new OAuth login with an existing User
        based on verified information (such as an email address) from the
        identity provider. This endpoint is useful for cases where we can't,
        such as missing or unverified provider information.


        See our [OAuth email address
        behavior](https://stytch.com/docs/guides/oauth/email-behavior) resource
        for additional information.
      operationId: api_oauth_v1_Attach
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/api_oauth_v1_AttachRequest'
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/api_oauth_v1_AttachResponse'
        '400':
          description: Bad request
        '401':
          description: Unauthorized
          content:
            application/json:
              example:
                status_code: 401
                request_id: request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141
                error_type: unauthorized_credentials
                error_message: Unauthorized credentials.
                error_url: https://stytch.com/docs/api/errors/401
        '429':
          description: Too Many Requests
          content:
            application/json:
              example:
                status_code: 429
                request_id: request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141
                error_type: too_many_requests
                error_message: Too many requests have been made.
                error_url: https://stytch.com/docs/api/errors/429
        '500':
          description: Internal server error
          content:
            application/json:
              example:
                status_code: 500
                request_id: request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141
                error_type: internal_server_error
                error_message: >-
                  Oops, something seems to have gone wrong, please reach out to
                  support@stytch.com to let us know what went wrong.
                error_url: https://stytch.com/docs/api/errors/500
      x-code-samples:
        - lang: csharp
          label: C#
          source: |-
            // POST /v1/oauth/attach
            const stytch = require('stytch');

            const client = new stytch.Client({
              project_id: '${projectId}',
              secret: '${secret}',
            });

            const params = {
              provider: "microsoft",
              user_id: "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
            };

            client.OAuth.Attach(params)
              .then(resp => { console.log(resp) })
              .catch(err => { console.log(err) });
        - lang: go
          label: Go
          source: "// POST /v1/oauth/attach\npackage main\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"github.com/stytchauth/stytch-go/v18/stytch/consumer/oauth\"\n\t\"github.com/stytchauth/stytch-go/v18/stytch/consumer/stytchapi\"\n)\n\nfunc main() {\n\tclient, err := stytchapi.NewClient(\n\t\t\"${projectId}\",\n\t\t\"${secret}\",\n\t)\n\tif err != nil {\n\t\tlog.Fatalf(\"error instantiating client: %v\", err)\n\t}\n\n\tparams := &oauth.AttachParams{\n\t\tProvider: \"microsoft\",\n\t\tUserID:   \"user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6\",\n\t}\n\n\tresp, err := client.OAuth.Attach(context.Background(), params)\n\tif err != nil {\n\t\tlog.Fatalf(\"error in method call: %v\", err)\n\t}\n\n\tlog.Println(resp)\n}\n"
        - lang: java
          label: Java
          source: |-
            // POST /v1/oauth/attach
            package com.example;

            import com.stytch.java.common.StytchResult;
            import com.stytch.java.consumer.models.oauth.AttachRequest;
            import com.stytch.java.consumer.StytchClient;

            public class Main {
                public static void main(String[] args) {
                    StytchClient.configure("${projectId}", "${secret}");

                    AttachRequest params = new AttachRequest();
                    params.setProvider("microsoft");
                    params.setUserId("user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6");

                    Object result = StytchClient.getOAuth().attach(params);
                    if (result instanceof StytchResult.Success) {
                      System.out.println(((StytchResult.Success) result).getValue());
                    } else {
                      System.out.println(((StytchResult.Error) result).getException());
                    }
                }
            }
        - lang: kotlin
          label: Kotlin
          source: |
            // POST /v1/oauth/attach
            package com.example

            import com.stytch.java.consumer.StytchClient
            import com.stytch.java.consumer.models.oauth.AttachRequest

            fun main() {
                StytchClient.configure(
                    projectId = "${projectId}",
                    secret = "${secret}",
                )

                when (
                    val result =
                        StytchClient.oauth.attach(
                            AttachRequest(
                                provider = "microsoft",
                                userId = "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
                            ),
                        )
                ) {
                    is StytchResult.Success -> println(result.value)
                    is StytchResult.Error -> println(result.exception)
                }
            }
        - lang: javascript
          label: Node.js
          source: |-
            // POST /v1/oauth/attach
            const stytch = require('stytch');

            const client = new stytch.Client({
              project_id: '${projectId}',
              secret: '${secret}',
            });

            const params = {
              provider: "microsoft",
              user_id: "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
            };

            client.oauth.attach(params)
              .then(resp => { console.log(resp) })
              .catch(err => { console.log(err) });
        - lang: php
          label: PHP
          source: |-
            $response = $client->oauth->attach([
                'provider' => 'microsoft',
                'user_id' => 'user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6',
            ]);
        - lang: python
          label: Python
          source: |
            # POST /v1/oauth/attach
            from stytch import Client

            client = Client(
                project_id="${projectId}",
                secret="${secret}",
            )

            resp = client.oauth.attach(
                provider="microsoft",
                user_id="user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
            )

            print(resp)
        - lang: ruby
          label: Ruby
          source: |-
            # frozen_string_literal: true

            # POST /v1/oauth/attach
            require 'stytch'

            client = Stytch::Client.new(
              project_id: "${projectId}",
              secret: "${secret}"
            )

            resp = client.oauth.attach(
              provider: "microsoft",
              user_id: "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6"
              
            )

            puts resp
        - lang: rust
          label: Rust
          source: |-
            // POST /v1/oauth/attach
            use stytch::consumer::client::Client;
            use stytch::consumer::oauth::AttachRequest;

            fn main() {
                let client = Client::new("${projectId}", "${secret}").unwrap();
                let resp = client.oauth.attach(
                    AttachRequest{
                        provider: "microsoft",
                        user_id: Some(String::from("user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6")),
                        ..Default::default()
                    }
                ).await;
                println!("The response is {:?}", resp);
            }
        - lang: bash
          label: cURL
          source: |-
            # POST /v1/oauth/attach
            curl --request POST \
              --url https://test.stytch.com/v1/oauth/attach \
              -u '${projectId}:${secret}' \
              -H 'Content-Type: application/json' \
              -d '{
                "provider": "microsoft",
                "user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6"
              }'
components:
  schemas:
    api_oauth_v1_AttachRequest:
      type: object
      properties:
        provider:
          type: string
          description: The OAuth provider's name.
        user_id:
          type: string
          description: >-
            The unique ID of a specific User. You may use an `external_id` here
            if one is set for the user.
        session_token:
          type: string
          description: The `session_token` associated with a User's existing Session.
        session_jwt:
          type: string
          description: The `session_jwt` associated with a User's existing Session.
      description: Request type
      required:
        - provider
    api_oauth_v1_AttachResponse:
      type: object
      properties:
        request_id:
          type: string
          description: >-
            Globally unique UUID that is returned with every API call. This
            value is important to log for debugging purposes; we may ask for
            this value to help identify a specific API call when helping you
            debug an issue.
        oauth_attach_token:
          type: string
          description: >-
            A single-use token for connecting the Stytch User selection from an
            OAuth Attach request to the corresponding OAuth Start request.
        status_code:
          type: integer
          format: int32
          description: >-
            The HTTP status code of the response. Stytch follows standard HTTP
            response status code patterns, e.g. 2XX values equate to success,
            3XX values are redirects, 4XX are client errors, and 5XX are server
            errors.
      required:
        - request_id
        - oauth_attach_token
        - status_code
  securitySchemes:
    basicAuth:
      type: http
      scheme: basic

````