# Hosted OAuth - Authorization Request

> **GET** `https://api.us.nylas.com/v3/connect/auth`

Source: https://developer.nylas.com/docs/reference/api/authentication-apis/get_oauth2_flow/

The initial OAuth 2.0 authorization request. Use this endpoint with the required query parameters to start the OAuth 2.0 process. The query parameters pass details to the Nylas API about how the user should authenticate, and where they should go after authenticating.
This endpoint supports the authorization code flow and optional PKCE settings for client-side only applications. For more information, see the  [Hosted OAuth with access token](/docs/v3/auth/hosted-oauth-accesstoken/) and [Hosted OAuth with access token and PKCE](/docs/v3/auth/hosted-oauth-accesstoken/#create-grants-with-oauth-2.0-and-pkce) documentation.

**Authentication:** ACCESS_TOKEN, NYLAS_API_KEY

## Parameters

### Query parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| `client_id` | string | Yes | Your Nylas application's client ID (or application ID). |
| `provider` | string | No | The connector provider type that you set up with Nylas for this application. If the provider isn't set, the user is directed to the Nylas Hosted login page and prompted to select their provider. Multiple providers can be set as a comma-separated list. |
| `redirect_uri` | string | Yes | Your project's callback URI (used as the OAuth `redirect_uri`). This is where the OAuth provider sends a user after they authenticate using Hosted OAuth. This must be URL-encoded. |
| `response_type` | string | Yes | Specifies the type of response Nylas returns for the authorization flow. Should be set to `code` for the OAuth 2.0 flow, and `adminconsent` for the Microsoft admin consent service flow. |
| `scope` | string | No | A space-delimited list of scopes that identify the resources that your application may access on the user's behalf. If no scopes are set, Nylas uses the default connector scopes. |
| `prompt` | string | No | (Optional) The prompt for the Hosted login page. This parameter can accept multiple values separated by a comma, without spaces in between. The order of the prompts affects the UI of the Hosted login page.  If `provider` is not set, the user is redirected to the provider page directly, and the prompt is ignored. |
| `state` | string | No | (Optional) The state of the grant, returned after authentication. The maximum length is 256 characters. |
| `login_hint` | string | No | Prefill the login name (usually the email address) during the authentication flow. If a grant already exists for the provided email address, Nylas automatically re-authenticates the grant. |
| `access_type` | string | No | Specifies whether Nylas should return a refresh token along with the exchange token. This isn't suitable for client-side or JavaScript applications. |
| `code_challenge` | string | No | Specifies a Base64-encoded `code_verifier` without padding. The verifier is used as a server-side challenge during the authorization code exchange. |
| `code_challenge_method` | string | No | Specifies the method used to encode the `code_verifier`. The verifier is used as a server-side challenge during the authorization code exchange. |
| `credential_id` | string | No | The ID of an existing Nylas connector's credential record. If you set the `response_type` value to `code` then you can use the credential to override an OAuth connector's default settings and create a grant. You need to [create a credential record](/docs/reference/api/connector-credentials/create_credential/) before you can make a credential override request. If not provided, connector's default "active_credential_id" is used. If you set the `response_type` value to `adminconsent`, with provider Microsoft, then this will be the OAuth of Microsoft's Service Account Admin Consent flow. You need to [set up the Microsoft connector with an Admin Consent credential before you can make this request](/docs/v3/auth/bulk-auth-grants/#set-up-microsoft-admin-consent-flow). |
| `options` | string | No | (Google only) Set to `exclude_google_granted_scopes` to exclude Google-granted scopes from the authorization request. |

## Responses

### 302 - Redirects user to provider's authorization page

### 400 - Bad Request

- `request_id` (string) - The request ID.
- `error` (object) - The response error object.
  - `type` (string) - The error type.
  - `message` (string) - The error message.
  - `provider_error` (object) - The error from the provider.

## Code samples

### cURL

```bash
curl --request GET \
  --url 'https://api.us.nylas.com/v3/connect/auth?client_id=<NYLAS_CLIENT_ID>&redirect_uri=https%3A%2F%2Fyourapp.com%2Fcallback&response_type=code&provider=google&login_hint=user@example.com'

```

### Node.js SDK

```javascript
import Nylas from "nylas";

const nylas = new Nylas({
  apiKey: "<NYLAS_API_KEY>",
  apiUri: "<NYLAS_API_URI>",
});

// Build a hosted-authentication URL. Redirect the user to this URL to start
// the OAuth flow; Nylas calls back to your `redirectUri` with an authorization
// code that you exchange for a grant via `nylas.auth.exchangeCodeForToken()`.
const authUrl = nylas.auth.urlForOAuth2({
  clientId: "<NYLAS_CLIENT_ID>",
  provider: "google",
  redirectUri: "http://localhost:3000/oauth/exchange",
  loginHint: "email_to_connect@example.com",
  accessType: "offline",
});

console.log(authUrl);

```

### Python SDK

```python
@app.route("/nylas/auth", methods=["GET"])
def login():
  if session.get("grant_id") is None:
    config = URLForAuthenticationConfig({"client_id": "<NYLAS_CLIENT_ID>", 
        "redirect_uri" : "http://localhost:5000/oauth/exchange"})

    url = nylas.auth.url_for_oauth2(config)
    return redirect(url)
  else:
    return f'{session["grant_id"]}'

@app.route("/oauth/exchange", methods=["GET"])
def authorized():
  if session.get("grant_id") is None:
    code = request.args.get("code")

    exchangeRequest = CodeExchangeRequest({"redirect_uri": "http://localhost:5000/oauth/exchange",
        "code": code, "client_id": "<NYLAS_CLIENT_ID>"})

    exchange = nylas.auth.exchange_code_for_token(exchangeRequest)
    session["grant_id"] = exchange.grant_id

    return redirect(url_for("login"))

```

### Ruby SDK

```ruby
# frozen_string_literal: true

require 'nylas'
require 'sinatra'

nylas = Nylas::Client.new(
  api_key: "<NYLAS_API_KEY>"
)

set :show_exceptions, :after_handler

error 404 do
  'No authorization code returned from Nylas'
end

error 500 do
  'Failed to exchange authorization code for token'
end

# Build the hosted-authentication URL and redirect the user there.
get '/nylas/auth' do
  config = {
    client_id: "<NYLAS_CLIENT_ID>",
    provider: 'google',
    redirect_uri: 'http://localhost:4567/oauth/exchange',
    login_hint: '<email_to_connect>',
    access_type: 'offline'
  }

  url = nylas.auth.url_for_oauth2(config)
  redirect url
end

# Receive the authorization code and exchange it for a grant.
get '/oauth/exchange' do
  code = params[:code]
  status 404 if code.nil?

  begin
    response = nylas.auth.exchange_code_for_token({
      client_id: "<NYLAS_CLIENT_ID>",
      redirect_uri: 'http://localhost:4567/oauth/exchange',
      code: code
    })
  rescue StandardError
    status 500
  else
    "Grant_Id: #{response[:grant_id]} \n Email: #{response[:email]}"
  end
end

```

### Java SDK

```java
import com.nylas.NylasClient;
import com.nylas.models.AccessType;
import com.nylas.models.AuthProvider;
import com.nylas.models.UrlForAuthenticationConfig;

public class HostedAuthUrl {
  public static void main(String[] args) {
    NylasClient nylas = new NylasClient.Builder("<NYLAS_API_KEY>").build();

    // Build a hosted-authentication URL. Redirect the user to this URL to start
    // the OAuth flow; Nylas calls back to your `redirectUri` with an authorization
    // code that you exchange for a grant via `nylas.auth().exchangeCodeForToken()`.
    UrlForAuthenticationConfig config = new UrlForAuthenticationConfig.Builder(
        "<NYLAS_CLIENT_ID>",
        "http://localhost:3000/oauth/exchange")
        .provider(AuthProvider.GOOGLE)
        .accessType(AccessType.OFFLINE)
        .loginHint("email_to_connect@example.com")
        .build();

    String url = nylas.auth().urlForOAuth2(config);

    System.out.println(url);
  }
}

```

### Kotlin SDK

```kotlin
import com.nylas.NylasClient
import com.nylas.models.AccessType
import com.nylas.models.AuthProvider
import com.nylas.models.UrlForAuthenticationConfig

fun main() {
  val nylas = NylasClient.Builder("<NYLAS_API_KEY>").build()

  // Build a hosted-authentication URL. Redirect the user to this URL to start
  // the OAuth flow; Nylas calls back to your `redirectUri` with an authorization
  // code that you exchange for a grant via `nylas.auth().exchangeCodeForToken()`.
  val config = UrlForAuthenticationConfig.Builder(
      "<NYLAS_CLIENT_ID>",
      "http://localhost:3000/oauth/exchange")
      .provider(AuthProvider.GOOGLE)
      .accessType(AccessType.OFFLINE)
      .loginHint("email_to_connect@example.com")
      .build()

  val url = nylas.auth().urlForOAuth2(config)

  println(url)
}

```
