Skip to content

Initial version including multiple language code #10523

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions articles/quickstart/native/n2w/01-login.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
---
title: Enable Native to Web SSO for iOS and Android Apps
description: Learn how to configure Auth0 Native to Web SSO in your iOS or Android apps using the Auth0 CLI and SDKs.
seo_alias: native-to-web-sso
budicon: 448
topics:
- quickstarts
- native
- web
- ios
- android
github:
path: native-to-web-sso
contentType: tutorial
useCase: quickstart
---

<!-- markdownlint-disable MD002 MD041 -->

## Configure Auth0

You will need both a **Native** application (for iOS or Android) and a **Web** or **Single Page Application (SPA)** registered in your Auth0 tenant. If you don’t have them already, <a href="/get-started/auth0-overview/create-applications/native-apps" target="_blank" rel="noreferrer">create one</a> before continuing.

### Enable Session Transfer in the Native Application

Use the Auth0 CLI to allow your native app to create session transfer tokens:

```bash
auth0 apps session-transfer set ${account.clientId} \
--can-create-token=true \
--enforce-device-binding=asn
```

### Enable Session Transfer in the Web Application

Configure your web or SPA app to accept session transfer tokens via cookie or query string:

```bash
auth0 apps session-transfer set ${account.clientId} \
--allowed-authentication-methods=cookie,query
```

::: note
To support cookie injection, use a WebView that allows setting secure cookies such as WKWebView on iOS or Android WebView. If not supported, you can use the query string method.
:::

## Exchange a Refresh Token for a Session Transfer Token

This action should happen right before you launch a WebView or external browser.

```swift
Auth0
.authentication()
.ssoExchange(withRefreshToken: refreshToken)
.start { result in
switch result {
case .success(let ssoCredentials):
DispatchQueue.main.async {
let cookie = HTTPCookie(properties: [
.domain: "${account.namespace}",
.path: "/",
.name: "auth0_session_transfer_token",
.value: ssoCredentials.sessionTransferToken,
.expires: ssoCredentials.expiresIn,
.secure: true
])!

let webView = WKWebView()
let store = webView.configuration.websiteDataStore.httpCookieStore
store.setCookie(cookie) {
let url = URL(string: "https://yourWebApplicationLoginURI")!
let request = URLRequest(url: url)
webView.load(request)

let vc = UIViewController()
vc.view = webView
UIApplication.shared.windows.first?.rootViewController?.present(vc, animated: true)
}
}
case .failure(let error):
print("Failed to get SSO token: \(error)")
}
}
```

## Handle Session Transfer in the Web Application

In cookie-based flows, your app doesn’t need to change. Just make sure your <strong>Application Login URI</strong> points to a route that redirects to Auth0’s `/authorize` endpoint.

If using query string method:

```javascript
const { auth } = require('express-openid-connect');

const config = {
authRequired: false,
auth0Logout: true,
authorizationParams: {
response_type: 'code',
scope: 'openid profile email',
}
};

app.use((req, res, next) => {
const { session_transfer_token } = req.query;

if (session_transfer_token) {
config.authorizationParams.session_transfer_token = session_transfer_token;
}

auth(config)(req, res, next);
});
```

::: note
You can configure your Application Login URI in your application's settings in the Auth0 Dashboard.
:::
20 changes: 20 additions & 0 deletions articles/quickstart/native/n2w/download.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!-- markdownlint-disable MD041 -->

> On every step, if you have a <a href="https://auth0.com/docs/customize/custom-domains" target="_blank" rel="noreferrer">custom domain</a>, replace the `YOUR_AUTH0_DOMAIN` placeholder with your custom domain instead of the value from the settings page.

## 1. Configure the associated domain

> **This requires Xcode 15.3+ and a paid Apple Developer account**. If you do not have a paid Apple Developer account, skip this step, and comment out the two `useHTTPS()` calls in `MainView.swift`.

Open `SwiftSample.xcodeproj` in Xcode and go to the settings of the app target you want to run. There are two app targets available: **SwiftSample (iOS)** and **SwiftSample (macOS)**. Change the bundle identifier from the default `com.auth0.samples.SwiftSample` to another value of your choosing. Then, make sure the **Automatically manage signing** box is checked, and that your Apple Team is selected.

Next, go to the **Signing & Capabilities** tab of the app's target settings. Find the `webcredentials:YOUR_AUTH0_DOMAIN` entry under **Associated Domains**, and replace the `YOUR_AUTH0_DOMAIN` placeholder with the domain of your Auth0 application.

Finally, open the settings page of your Auth0 application, scroll to the end, and open **Advanced Settings > Device Settings**. In the **iOS** section, set **Team ID** to your <a href="https://developer.apple.com/help/account/manage-your-team/locate-your-team-id/" target="_blank" rel="noreferrer">Apple Team ID</a>, and **App ID** to the app's bundle identifier.

## 2. Configure the Auth0 application

Open the settings page of your Auth0 application and add the following URLs to **Allowed Callback URLs** and **Allowed Logout URLs**, depending on the app target you want to run.

- **SwiftSample (iOS)**: `https://YOUR_AUTH0_DOMAIN/ios/YOUR_BUNDLE_IDENTIFIER/callback,YOUR_BUNDLE_IDENTIFIER://YOUR_AUTH0_DOMAIN/ios/YOUR_BUNDLE_IDENTIFIER/callback`
- **SwiftSample (macOS)**: `https://YOUR_AUTH0_DOMAIN/macos/YOUR_BUNDLE_IDENTIFIER/callback,YOUR_BUNDLE_IDENTIFIER://YOUR_AUTH0_DOMAIN/macos/YOUR_BUNDLE_IDENTIFIER/callback`
37 changes: 37 additions & 0 deletions articles/quickstart/native/n2w/files/NativeApplication_Kotlin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
name: android.kt
language: kotlin
---

```kotlin
import android.app.Activity
import android.util.Log
import android.webkit.CookieManager
import android.webkit.WebView

fun launchWebSSO(context: Activity) {
authentication
.ssoExchange("refresh_token")
.start(object : Callback<SSOCredentials, AuthenticationException> {
override fun onSuccess(result: SSOCredentials) {
val cookieManager = CookieManager.getInstance()
val cookieValue = "auth0_session_transfer_token=" + result.sessionTransferToken +
"; Path=/; Secure; HttpOnly; SameSite=None"
cookieManager.setAcceptCookie(true)
cookieManager.setCookie("${account.namespace}", cookieValue)

val webView = WebView(context)
webView.settings.javaScriptEnabled = true
webView.loadUrl("https://yourWebApplicationLoginURI")

context.runOnUiThread {
context.setContentView(webView)
}
}

override fun onFailure(exception: AuthenticationException) {
Log.e("Auth0", "Failed to get session transfer token", exception)
}
})
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
name: reactivenative.js
language: javascript
---

```javascript
// React Native - Placeholder for Native to Web SSO
// SDK support is not available yet. This is a conceptual guide only.

import { WebView } from 'react-native-webview';

/**
* Concept:
* - Use your Auth0 refresh_token to call a backend that performs the session_transfer_token exchange
* - Receive the short-lived session_transfer_token
* - Inject it into a WebView via a cookie header or query param (if cookies aren't supported)
* - Load the web login URI
*/


```
51 changes: 51 additions & 0 deletions articles/quickstart/native/n2w/files/NativeApplication_Swift.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
---
name: swift.swift
language: swift
---

```swift
import SwiftUI
import Auth0
import WebKit

struct MainView: View {
var body: some View {
Button("Open Web Session", action: self.launchWebSSO)
}

func launchWebSSO() {
Auth0
.authentication()
.ssoExchange(withRefreshToken: refreshToken)
.start { result in
switch result {
case .success(let ssoCredentials):
DispatchQueue.main.async {
let cookie = HTTPCookie(properties: [
.domain: "${account.namespace}",
.path: "/",
.name: "auth0_session_transfer_token",
.value: ssoCredentials.sessionTransferToken,
.expires: ssoCredentials.expiresIn,
.secure: true
])!

let webView = WKWebView()
let store = webView.configuration.websiteDataStore.httpCookieStore
store.setCookie(cookie) {
let url = URL(string: "https://yourWebApplicationLoginURI")!
let request = URLRequest(url: url)
webView.load(request)

let vc = UIViewController()
vc.view = webView
UIApplication.shared.windows.first?.rootViewController?.present(vc, animated: true)
}
}
case .failure(let error):
print("Failed to get SSO token: \(error)")
}
}
}
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
name: react.jsx
language: javascript
---

```javascript
import { useAuth0 } from "@auth0/auth0-react";
import React, { useEffect } from "react";
import { useSearchParams } from "react-router-dom";

const LoginButton = () => {
const { loginWithRedirect } = useAuth0();
const [searchParams] = useSearchParams();

useEffect(() => {
const sessionTransferToken = searchParams.get("session_transfer_token");

// Automatically trigger the login when receiving session transfer token
if (sessionTransferToken) {
loginWithRedirect({
authorizationParams: {
session_transfer_token: sessionTransferToken,
},
});
}
}, [loginWithRedirect, searchParams]);

return <button onClick={() => loginWithRedirect()}>Log In</button>;
};

export default LoginButton;
```
28 changes: 28 additions & 0 deletions articles/quickstart/native/n2w/files/WebApplication_Node.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
name: node.js
language: javascript
---

```javascript
const { auth } = require('express-openid-connect');

const config = {
authRequired: false,
auth0Logout: true,
authorizationParams: {
response_type: 'code',
scope: 'openid profile email',
}
};

// Middleware that supports session_transfer_token via query parameter
app.use((req, res, next) => {
const { session_transfer_token } = req.query;

if (session_transfer_token) {
config.authorizationParams.session_transfer_token = session_transfer_token;
}

auth(config)(req, res, next);
});
```
32 changes: 32 additions & 0 deletions articles/quickstart/native/n2w/index.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
title: Native to Web SSO
# TODO remove 'image' once new QS page is live. Then only use 'logo'.
image: /media/platforms/ios.png
logo: auth0
alias:
- ios
- macos
- swift
hybrid: false
author:
name: Nelson Matias
email: [email protected]
community: false
topics:
- quickstart
contentType: tutorial
useCase: quickstart
seo_alias: swift
show_releases: true
show_steps: true
requirements:
- iOS 13+ or macOS 11+
- Xcode 14.x
default_article: 01-login
articles:
- 01-login
hidden_articles:
- interactive
github:
org: auth0-samples
repo: auth0-ios-swift-sample
branch: master
Loading