diff --git a/articles/quickstart/backend/acul/files/auth_config.md b/articles/quickstart/backend/acul/files/auth_config.md new file mode 100644 index 0000000000..63471fea63 --- /dev/null +++ b/articles/quickstart/backend/acul/files/auth_config.md @@ -0,0 +1,12 @@ +--- +name: auth_config.json +language: json +--- + +```json +//auth0-react-samples/Sample-01/src/auth_config.json +{ + "domain": "${account.namespace}", + "clientId": "${account.clientId}" +} +``` diff --git a/articles/quickstart/backend/acul/files/index.md b/articles/quickstart/backend/acul/files/index.md new file mode 100644 index 0000000000..25b8cf231b --- /dev/null +++ b/articles/quickstart/backend/acul/files/index.md @@ -0,0 +1,47 @@ +--- +name: index.tsx +language: javascript +--- + +```javascript +import { LoginId } from '@auth0/auth0-acul-js'; +import { useState } from 'react'; + +export const LoginIdScreen = () => { + const loginManager = new LoginId(); + const [email, setEmail] = useState(''); + + return ( +
`
+ +## Configure Auth0 + + +To use Auth0 services, you’ll need to have an application set up in the Auth0 Dashboard. The Auth0 application is where you will configure how you want authentication to work for the project you are developing.
Use the interactive selector to create a new Auth0 application or select an existing application that represents the project you want to integrate with. Every application in Auth0 is assigned an alphanumeric, unique client ID that your application code will use to call Auth0 APIs through the SDK.
Any settings you configure using this quickstart will automatically update for your Application in the Dashboard, which is where you can manage your Applications in the future.
If you would rather explore a complete configuration, you can view a sample application instead.
A callback URL is a URL in your application that you would like Auth0 to redirect users to after they have authenticated. If not set, users will not be returned to your application after they log in.
If you are following along with our sample project, set this to http://localhost:3000
.
A logout URL is a URL in your application that you would like Auth0 to redirect users to after they have logged out. If not set, users will not be able to log out from your application and will receive an error.
If you are following along with our sample project, set this to http://localhost:3000
.
An Allowed Web Origin is a URL that you want to be allowed to access to your authentication flow. This must contain the URL of your project. If not properly set, your project will be unable to silently refresh authentication tokens, so your users will be logged out the next time they visit your application or refresh a page.
If you are following along with our sample project, set this to http://localhost:3000
.
Use Auth0 CLI to enable ACLU Login ID screen in your tenant. + + + +In the root directory of your project, save the settings.json file.
Enable ACUL by running the following command in your terminal:
auth0 ul customize --rendering-mode advanced --prompt login-id --screen login-id --settings-file ./settings.json
+
+
+
+Development Setup: This example is using localhost (127.0.0.1:8080) for development.
For production, you will need to update these URLs to point to your CDN or static hosting service.
Use one of the sample apps provided by Auth0 to initiate Universal Login
In the root folder of your project, clone the Auth0 sample application using the following command: + + + +
git clone https://github.com/auth0-samples/auth0-react-samples
+
+
+
+Change directory to the auth0-react-samples/Sample-01
folder and install the sample application using the following command:
cd auth0-react-samples/Sample-01
+
+npm install
+
+
+
+Change directory to the auth0-react-samples/Sample-01/src
folder and add the auth_config.json
file. Edit the file to add your tenant's Custom Domain.
Run the application
npm run dev
+
+
+
+Open your application (default: http://localhost:3000)
Select the Log In button on the sample app
You should be redirected to your Auth0 domain
After selecting Log In, you should see a blank page.
This is expected! It means Auth0 is trying to load your custom UI assets, which we have not created yet.
If you see the default Auth0 page instead of a blank page:
Check if your custom domain is properly configured.
Ensure your application is using the custom domain.
+ +
+ +
+ +## Build a custom interface for login-id screen {{{ data-action="code" data-code="index.tsx" }}} + + +Run a single-page application to build custom login screens.
1. In the root folder of your project, open a new terminal and clone the Auth0 boilerplate application using the following command:
git clone https://github.com/auth0-samples/auth0-acul-react-boilerplate
+
+
+
+2. Change directory to the auth0-acul-react-boilerplate
folder and install the application and the ACUL JS SDK.
// open the directory where you git clone the boilerplate
+
+cd auth0-acul-react-boilerplate && npm i
+
+
+
+// Install the ACUL JS SDK
+
+npm install @auth0/auth0-acul-js
+
+
+
+3. Build the application
npm run build
+
+
+
+4. Serve the assets
npx http-server dist -p 8080
+
+
+
+The assets are served from localhost during development.
For production, you'll need to serve these assets from a CDN or static hosting service.
After selecting Log In, you are greeted with a “Hello World”
page.
Make sure to have installed the ACUL JS SDK after installing the boilerplate application.
Change directory to the auth0-acul-react-boilerplate/src/screens/loginId/
and edit the index.tsx
file.
Rebuild the application with the following command:
npm run build
+
+
+
+Select Log In.
You should now see a customized login page as shown below:
Auth0 allows you to add authentication and access user profile information in almost any application type quickly. This guide demonstrates how to integrate Auth0 with any new or existing ASP.NET Web API application using the Microsoft.AspNetCore.Authentication.JwtBearer
package.
If you haven't created an API in your Auth0 dashboard yet, you can use the interactive selector to create a new Auth0 API or select an existing API that represents the project you want to integrate with.
Alternatively, you can read our getting started guide, which will help you set up your first API through the Auth0 Dashboard.
Note that every API in Auth0 is configured using an API Identifier; your application code will use the API Identifier as the Audience to validate the access token.
New to Auth0? Learn how Auth0 works and read about implementing API authentication and authorization using the OAuth 2.0 framework.
Permissions let you define how resources can be accessed on behalf of the user with a given access token. For example, you might choose to grant read access to the messages
resource if users have the manager access level, and grant write access to that resource if they have the administrator access level.
You can define allowed permissions in the Permissions view of the Auth0 Dashboard's APIs section. The following example uses the read:messages
scope.
To allow your application to validate access tokens, add a reference to the Microsoft.AspNetCore.Authentication.JwtBearer
NuGet package:
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer
-## Configure the middleware {{{ data-action=code data-code="Startup.cs" }}}
+
-Set up the authentication middleware by configuring it in your application's `Program.cs` file:
+
-1. Register the authentication services by making a call to the `AddAuthentication` method. Configure `JwtBearerDefaults.AuthenticationScheme` as the default scheme.
-
-2. Register the JWT Bearer authentication scheme by making a call to the `AddJwtBearer` method. Configure your Auth0 domain as the authority and your Auth0 API Identifier as the audience, and be sure that your Auth0 domain and API Identifier are set in your application's **appsettings.json** file.
+## Configure the middleware {{{ data-action="code" data-code="Program.cs" }}}
-:::note
-In some cases, the access token will not have a `sub` claim; in this case, the `User.Identity.Name` will be `null`. If you want to map a different claim to `User.Identity.Name`, add it to `options.TokenValidationParameters` within the `AddJwtBearer()` call.
-:::
-3. Add the authentication and authorization middleware to the middleware pipeline by adding calls to the `UseAuthentication` and `UseAuthorization` methods under the `var app = builder.Build();` method.
+Set up the authentication middleware by configuring it in your application's Program.cs
file:
Register the authentication services by making a call to the AddAuthentication
method. Configure JwtBearerDefaults.AuthenticationScheme
as the default scheme.
Register the JWT Bearer authentication scheme by making a call to the AddJwtBearer
method. Configure your Auth0 domain as the authority and your Auth0 API Identifier as the audience, and be sure that your Auth0 domain and API Identifier are set in your application's appsettings.json file.
-## Validate scopes {{{ data-action=code data-code="HasScopeHandler.cs" }}}
+
In some cases, the access token will not have a sub
claim; in this case, the User.Identity.Name
will be null
. If you want to map a different claim to User.Identity.Name
, add it to options.TokenValidationParameters
within the AddJwtBearer()
call.
Add the authentication and authorization middleware to the middleware pipeline by adding calls to the UseAuthentication
and UseAuthorization
methods under the var app = builder.Build();
method.
To ensure that an access token contains the correct scopes, use Policy-Based Authorization in the ASP.NET Core:
Create a new authorization requirement called HasScopeRequirement
, which will check whether the scope
claim issued by your Auth0 tenant is present, and if so, will check that the claim contains the requested scope.
Under your Program.cs
file's var builder = WebApplication.CreateBuilder(args);
method, add a call to the app.AddAuthorization
method.
Add policies for scopes by calling AddPolicy
for each scope.
Register a singleton for the HasScopeHandler
class.
The JWT middleware integrates with the standard ASP.NET Core Authentication and Authorization mechanisms.
To secure an endpoint, add the [Authorize]
attribute to your controller action (or the entire controller if you want to protect all of its actions).
When securing endpoints that require specific scopes, make sure that the correct scope is present in the access_token
. To do so, add the Authorize
attribute to the Scoped
action and pass read:messages
as the policy
parameter.
This guide demonstrates how to integrate Auth0 with any new or existing Python API built with Django.
If you haven't created an API in your Auth0 Dashboard yet, you can use the interactive selector to create a new Auth0 API or select an existing API that represents the project you want to integrate with.
Alternatively, you can read our getting started guide, which will help you set up your first API through the Auth0 Dashboard.
Every API in Auth0 is configured using an API Identifier that your application code will use as the Audience to validate the Access Token.
New to Auth0? Learn how Auth0 works and read about implementing API authentication and authorization using the OAuth 2.0 framework.
Permissions let you define how resources can be accessed on behalf of the user with a given access token. For example, you might choose to grant read access to the messages
resource if users have the manager access level, and grant write access to that resource if they have the administrator access level.
You can define allowed permissions in the Permissions view of the Auth0 Dashboard's APIs section. The following example uses the read:messages
scope.
Add the following dependencies to your requirements.txt
:
-```shell
-django-admin startproject apiexample
-cd apiexample
-```
+
Run pip install -r requirements.txt
Next, you'll create three API views in apiexample/views.py
:
/api/public
: A public endpoint that requires no authentication.
/api/private
: A private endpoint that requires a valid Access Token JWT.
/api/private-scoped
: A private endpoint that requires a valid Access Token JWT containing the given scope
.
The protected routes will have a require_auth
decorator, which is a ResourceProtector
that uses the Auth0JWTBearerTokenValidator
you created earlier.
To create the Auth0JWTBearerTokenValidator
, you'll pass it to your tenant's domain and the API Identifier of the API you created earlier.
The require_auth
decorator on the private_scoped
route accepts an additional argument "read:messages"
, which checks the Access Token for the Permission (Scope) you created earlier.
In previous steps, you added methods to the views.py
file. Next, map those methods to URLs using Django's URL dispatcher, which lets you map URL patterns to views.
Add the URL patterns to your apiexample/urls.py
file.
To make calls to your API, you will need an access token. You can retrieve an access token for testing purposes from the Test view in your API settings.
Provide the access token as an Authorization
header in your requests.
curl --request get \
+
+ --url 'http:///${account.namespace}.com/api_path' \
+
+ --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
var client = new RestClient("http:///${account.namespace}.com/api_path");
+
+var request = new RestRequest(Method.GET);
+
+request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE");
+
+IRestResponse response = client.Execute(request);
package main
+
+
+
+import (
+
+ "fmt"
+
+ "net/http"
+
+ "io/ioutil"
+
+)
+
+
+
+func main() {
+
+
+
+ url := "http:///${account.namespace}.com/api_path"
+
+
+
+ req, _ := http.NewRequest("get", url, nil)
+
+
+
+ req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")
+
+
+
+ res, _ := http.DefaultClient.Do(req)
+
+
+
+ defer res.Body.Close()
+
+ body, _ := ioutil.ReadAll(res.Body)
+
+
+
+ fmt.Println(res)
+
+ fmt.Println(string(body))
+
+
+
+}
HttpResponse<String> response = Unirest.get("http:///${account.namespace}.com/api_path")
+
+ .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")
+
+ .asString();
var axios = require("axios").default;
+
+
+
+var options = {
+
+ method: 'get',
+
+ url: 'http:///${account.namespace}.com/api_path',
+
+ headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'}
+
+};
+
+
+
+axios.request(options).then(function (response) {
+
+ console.log(response.data);
+
+}).catch(function (error) {
+
+ console.error(error);
+
+});
#import <Foundation/Foundation.h>
+
+
+
+NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" };
+
+
+
+NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///${account.namespace}.com/api_path"]
+
+ cachePolicy:NSURLRequestUseProtocolCachePolicy
+
+ timeoutInterval:10.0];
+
+[request setHTTPMethod:@"get"];
+
+[request setAllHTTPHeaderFields:headers];
+
+
+
+NSURLSession *session = [NSURLSession sharedSession];
+
+NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
+
+ completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
+
+ if (error) {
+
+ NSLog(@"%@", error);
+
+ } else {
+
+ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
+
+ NSLog(@"%@", httpResponse);
+
+ }
+
+ }];
+
+[dataTask resume];
$curl = curl_init();
+
+
+
+curl_setopt_array($curl, [
+
+ CURLOPT_URL => "http:///${account.namespace}.com/api_path",
+
+ CURLOPT_RETURNTRANSFER => true,
+
+ CURLOPT_ENCODING => "",
+
+ CURLOPT_MAXREDIRS => 10,
+
+ CURLOPT_TIMEOUT => 30,
+
+ CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+
+ CURLOPT_CUSTOMREQUEST => "get",
+
+ CURLOPT_HTTPHEADER => [
+
+ "authorization: Bearer YOUR_ACCESS_TOKEN_HERE"
+
+ ],
+
+]);
+
+
+
+$response = curl_exec($curl);
+
+$err = curl_error($curl);
+
+
+
+curl_close($curl);
+
+
+
+if ($err) {
+
+ echo "cURL Error #:" . $err;
+
+} else {
+
+ echo $response;
+
+}
import http.client
+
+
+
+conn = http.client.HTTPConnection("")
+
+
+
+headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" }
+
+
+
+conn.request("get", "/${account.namespace}.com/api_path", headers=headers)
+
+
+
+res = conn.getresponse()
+
+data = res.read()
+
+
+
+print(data.decode("utf-8"))
require 'uri'
+
+require 'net/http'
+
+
+
+url = URI("http:///${account.namespace}.com/api_path")
+
+
+
+http = Net::HTTP.new(url.host, url.port)
+
+
+
+request = Net::HTTP::Get.new(url)
+
+request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE'
+
+
+
+response = http.request(request)
+
+puts response.read_body
import Foundation
+
+
+
+let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"]
+
+
+
+let request = NSMutableURLRequest(url: NSURL(string: "http:///${account.namespace}.com/api_path")! as URL,
+
+ cachePolicy: .useProtocolCachePolicy,
+
+ timeoutInterval: 10.0)
+
+request.httpMethod = "get"
+
+request.allHTTPHeaderFields = headers
+
+
+
+let session = URLSession.shared
+
+let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
+
+ if (error != nil) {
+
+ print(error)
+
+ } else {
+
+ let httpResponse = response as? HTTPURLResponse
-Next, you'll create three API views in `apiexample/views.py`:
+ print(httpResponse)
-- `/api/public`: A public endpoint that requires no authentication.
-- `/api/private`: A private endpoint that requires a valid Access Token JWT.
-- `/api/private-scoped`: A private endpoint that requires a valid Access Token JWT containing the given `scope`.
+ }
-The protected routes will have a `require_auth` decorator, which is a `ResourceProtector` that uses the `Auth0JWTBearerTokenValidator` you created earlier.
+})
-To create the `Auth0JWTBearerTokenValidator`, you'll pass it your tenant's domain and the API Identifier of the API you created earlier.
-The `require_auth` decorator on the `private_scoped` route accepts an additional argument `"read:messages"`, which checks the Access Token for the Permission (Scope) you created earlier.
-## Add URL mappings {{{ data-action=code data-code="apiexample/urls.py#8:10" }}}
+dataTask.resume()
This guide demonstrates how to integrate Auth0 with any new or existing Go API application using the go-jwt-middleware package.
If you have not created an API in your Auth0 dashboard yet, use the interactive selector to create a new Auth0 API or select an existing API for your project.
To set up your first API through the Auth0 dashboard, review our getting started guide.
Each Auth0 API uses the API Identifier, which your application needs to validate the access token.
New to Auth0? Learn how Auth0 works and read about implementing API authentication and authorization using the OAuth 2.0 framework.
Permissions let you define how resources can be accessed on behalf of the user with a given access token. For example, you might choose to grant read access to the messages
resource if users have the manager access level, and a write access to that resource if they have the administrator access level.
You can define allowed permissions in the Permissions view of the Auth0 Dashboard's APIs section. The following example uses the read:messages
scope.
Add a go.mod
file to list all the necessary dependencies.
// go.mod
+
+
module 01-Authorization-RS256
+
+
go 1.21
+
+
require (
+
github.com/auth0/go-jwt-middleware/v2 v2.2.0
+
github.com/joho/godotenv v1.5.1
+
)
-```
-Download dependencies by running the following shell command:
+
+
+Download dependencies by running the following shell command:
go mod download
-```shell
-go mod download
-```
+
+
+
## Configure your application
-Create a `.env` file within the root of your project directory to store the app configuration, and fill in the
-environment variables:
-```sh
-# The URL of our Auth0 Tenant Domain.
+Create a .env
file within the root of your project directory to store the app configuration. Then, fill in the environment variables:
# The URL of our Auth0 Tenant Domain.
+
# If you're using a Custom Domain, be sure to set this to that value instead.
+
AUTH0_DOMAIN='${account.namespace}'
+
+
# Our Auth0 API's Identifier.
+
AUTH0_AUDIENCE='${apiIdentifier}'
-```
-## Create a middleware to validate access tokens {{{ data-action=code data-code="middleware/jwt.go" }}}
+
+
+
+
+## Create a middleware to validate access tokens {{{ data-action="code" data-code="middleware/jwt.go" }}}
+
+
+The EnsureValidToken
middleware function validates the access token. You can apply this function to any endpoints you wish to protect. If the token is valid, the endpoint releases the resources. If the token is not valid, the API returns a 401 Authorization
error.
Set up the go-jwt-middleware middleware to verify access tokens from incoming requests.
By default, your API will be set up to use RS256 as the algorithm for signing tokens. Since RS256 works by using a private/public keypair, tokens can be verified against the public key for your Auth0 account. This public key is accessible at https://${account.namespace}/.well-known/jwks.json
.
Include a mechanism to check that the token has sufficient scope to access the requested resources.
Create a function HasScope
to check and ensure the access token has the correct scope before returning a successful response.
In this example, create an /api/public
endpoint that does not use the EnsureToken
middleware as it is accessible to non-authenticated requests.
Create an /api/private
endpoint that requires the EnsureToken
middleware as it is only available to authenticated requests containing an access token with no additional scope.
Create an /api/private-scoped
endpoint that requires the EnsureToken
middleware and HasScope
as it is only available for authenticated requests containing an access token with the read:messages
scope granted.
Only the read:messages
scope is checked by the HasScope
function. You may want to extend it or make it a standalone middleware that accepts multiple scopes to fit your use case.
To make calls to your API, you need an Access Token. You can get an Access Token for testing purposes from the Test view in your API settings.
Provide the Access Token as an Authorization
header in your requests.
curl --request get \
+
+ --url 'http:///${account.namespace}/api_path' \
+
+ --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
var client = new RestClient("http:///${account.namespace}/api_path");
+
+var request = new RestRequest(Method.GET);
+
+request.AddHeader("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE");
+
+IRestResponse response = client.Execute(request);
package main
+
+
+
+import (
+
+ "fmt"
+
+ "net/http"
+
+ "io/ioutil"
+
+)
+
+
+
+func main() {
+
+
+
+ url := "http:///${account.namespace}/api_path"
+
+
+
+ req, _ := http.NewRequest("get", url, nil)
+
+
+
+ req.Header.Add("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")
+
+
+
+ res, _ := http.DefaultClient.Do(req)
+
+
+
+ defer res.Body.Close()
+
+ body, _ := ioutil.ReadAll(res.Body)
+
+
+
+ fmt.Println(res)
+
+ fmt.Println(string(body))
+
+
+
+}
HttpResponse<String> response = Unirest.get("http:///${account.namespace}/api_path")
+
+ .header("authorization", "Bearer YOUR_ACCESS_TOKEN_HERE")
+
+ .asString();
var axios = require("axios").default;
+
+
+
+var options = {
+
+ method: 'get',
+
+ url: 'http:///${account.namespace}/api_path',
+
+ headers: {authorization: 'Bearer YOUR_ACCESS_TOKEN_HERE'}
+
+};
+
+
+
+axios.request(options).then(function (response) {
+
+ console.log(response.data);
+
+}).catch(function (error) {
+
+ console.error(error);
+
+});
#import <Foundation/Foundation.h>
+
+
+
+NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_ACCESS_TOKEN_HERE" };
+
+
+
+NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http:///${account.namespace}/api_path"]
+
+ cachePolicy:NSURLRequestUseProtocolCachePolicy
+
+ timeoutInterval:10.0];
+
+[request setHTTPMethod:@"get"];
+
+[request setAllHTTPHeaderFields:headers];
+
+
+
+NSURLSession *session = [NSURLSession sharedSession];
+
+NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
+
+ completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
+
+ if (error) {
+
+ NSLog(@"%@", error);
+
+ } else {
+
+ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
+
+ NSLog(@"%@", httpResponse);
+
+ }
+
+ }];
+
+[dataTask resume];
$curl = curl_init();
+
+
+
+curl_setopt_array($curl, [
+
+ CURLOPT_URL => "http:///${account.namespace}/api_path",
+
+ CURLOPT_RETURNTRANSFER => true,
+
+ CURLOPT_ENCODING => "",
+
+ CURLOPT_MAXREDIRS => 10,
+
+ CURLOPT_TIMEOUT => 30,
+
+ CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+
+ CURLOPT_CUSTOMREQUEST => "get",
+
+ CURLOPT_HTTPHEADER => [
+
+ "authorization: Bearer YOUR_ACCESS_TOKEN_HERE"
+
+ ],
+
+]);
+
+
+
+$response = curl_exec($curl);
+
+$err = curl_error($curl);
+
+
+
+curl_close($curl);
+
+
+
+if ($err) {
+
+ echo "cURL Error #:" . $err;
+
+} else {
+
+ echo $response;
+
+}
import http.client
+
+
+
+conn = http.client.HTTPConnection("")
+
+
+
+headers = { 'authorization': "Bearer YOUR_ACCESS_TOKEN_HERE" }
+
+
+
+conn.request("get", "/${account.namespace}/api_path", headers=headers)
+
+
+
+res = conn.getresponse()
+
+data = res.read()
+
+
+
+print(data.decode("utf-8"))
require 'uri'
+
+require 'net/http'
+
+
+
+url = URI("http:///${account.namespace}/api_path")
+
+
+
+http = Net::HTTP.new(url.host, url.port)
+
+
+
+request = Net::HTTP::Get.new(url)
+
+request["authorization"] = 'Bearer YOUR_ACCESS_TOKEN_HERE'
+
+
+
+response = http.request(request)
+
+puts response.read_body
import Foundation
+
+
+
+let headers = ["authorization": "Bearer YOUR_ACCESS_TOKEN_HERE"]
+
+
+
+let request = NSMutableURLRequest(url: NSURL(string: "http:///${account.namespace}/api_path")! as URL,
+
+ cachePolicy: .useProtocolCachePolicy,
+
+ timeoutInterval: 10.0)
+
+request.httpMethod = "get"
+
+request.allHTTPHeaderFields = headers
+
+
+
+let session = URLSession.shared
+
+let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
+
+ if (error != nil) {
-The `EnsureValidToken` middleware function validates the access token. You can apply this function to any endpoints you wish to protect.
-If the token is valid, the endpoint releases the resources. If the token is not valid, the API returns a `401 Authorization` error.
+ print(error)
-Setup the **go-jwt-middleware** middleware to verify access tokens from incoming requests.
+ } else {
-<%= include('../_includes/_api_jwks_description_no_link') %>
+ let httpResponse = response as? HTTPURLResponse
-Include a mechanism to check that the token has sufficient **scope** to access the requested resources.
+ print(httpResponse)
+ }
-Create a function `HasScope` to check and ensure the access token has the correct scope before returning a successful response.
+})
-## Protect API endpoints {{{ data-action=code data-code="main.go" }}}
-In this example, create an `/api/public` endpoint that does not use the `EnsureToken` middleware as it is accessible to non-authenticated requests.
-Create an `/api/private` endpoint that requires the `EnsureToken` middleware as it is only available to authenticated requests containing an access token with no additional scope.
+dataTask.resume()
Now that you have configured your application, run your application and verify that:
GET /api/public
is available for non-authenticated requests.
GET /api/private
is available for authenticated requests.
GET /api/private-scoped
is available for authenticated requests containing an access token with the read:messages
scope.
If your application did not start successfully:
Verify you added the token as the Authorization
header
Ensure the token has the correct scopes. Verify with jwt.io.
Still having issues? Check out our documentation or visit our community page to get more help.
Auth0 allows you to quickly add authorization to your application. This guide demonstrates how to integrate Auth0 with any new or existing Spring Boot application.
If you have not created an API in your Auth0 dashboard yet, use the interactive selector to create a new Auth0 API or select an existing API that represents the project you want to integrate with.
Review our getting started guide to set up your first API through the Auth0 dashboard.
Each Auth0 API uses the API Identifier, which your application needs to validate the access token.
New to Auth0? Learn how Auth0 works and read about implementing API authentication and authorization using the OAuth 2.0 framework.
Permissions let you define how resources can be accessed on behalf of the user with a given access token. For example, you might choose to grant read access to the messages
resource if users have the manager access level, and a write access to that resource if they have the administrator access level.
You can define allowed permissions in the Permissions view of the Auth0 Dashboard's APIs section.
This example uses the read:messages
scope.
The sample project uses a /src/main/resources/application.yml
file, which configures it to use the correct Auth0 domain and API Identifier for your API. If you download the code from this page it will be automatically configured. If you clone the example from GitHub, you will need to fill it in yourself.
If you are using Gradle, you can add the required dependencies using the Spring Boot Gradle Plugin and the Dependency Management Plugin to resolve dependency versions:
// build.gradle
-```groovy
-// build.gradle
-plugins {
- id 'java'
- id 'org.springframework.boot' version '3.1.5'
- id 'io.spring.dependency-management' version '1.1.3'
-}
-dependencies {
- implementation 'org.springframework.boot:spring-boot-starter-web'
- implementation 'com.okta.spring:okta-spring-boot-starter:3.0.5'
-}
-```
+ plugins {
-If you are using Maven, add the Spring dependencies to your `pom.xml` file:
+ id 'java'
-```xml
-// pom.xml
+ id 'org.springframework.boot'
-
- org.springframework.boot
- spring-boot-starter-parent
- 3.1.5
-
-
+ version '3.1.5'
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
- com.okta.spring
- okta-spring-boot-starter
- 3.0.5
-
-
-```
+ id 'io.spring.dependency-management'
+ version '1.1.3'
-## Configure the resource server {{{ data-action=code data-code="SecurityConfig.java" }}}
+ }
-To configure the application as a Resource Server and validate the JWTs, create a class that will provide an instance of `SecurityFilterChain`, and add the `@Configuration` annotation.
-### Protect API endpoints
-<%= include('../_includes/_api_endpoints') %>
+ dependencies {
-The example below shows how to secure API methods using the `HttpSecurity` object provided in the `filterChain()` method of the `SecurityConfig` class. Route matchers restrict access based on the level of authorization required.
+ implementation 'org.springframework.boot:spring-boot-starter-web'
-::: note
-By default, Spring Security creates a `GrantedAuthority` for each scope in the `scope` claim of the JWT. This scope enables using the `hasAuthority("SCOPE_read:messages")` method to restrict access to a valid JWT that contains the `read:messages` scope.
-:::
+ implementation 'com.okta.spring:okta-spring-boot-starter:3.0.5'
-## Create the Domain Object {{{ data-action=code data-code="Message.java#1:11" }}}
+ }
-To make your endpoint return a JSON, you can use a Java record. The member variables of this object is serialized into the key value for your JSON. Create a new record named `Message` as an example domain object to return during the API calls.
+
-## Create the API controller {{{ data-action=code data-code="APIController.java" }}}
+If you are using Maven, add the Spring dependencies to your pom.xml
file:
// pom.xml
-Create a new class named `APIController` to handle requests to the endpoints. The `APIController` has three routes as defined in the [Protect API Endpoints](/quickstart/backend/java-spring-security5/interactive/#configure-the-resource-server) section. For this example, allow all origins through `@CrossOrigin` annotation. Real applications should configure `CORS` for their use case.
-## Run the application {{{ data-action=code data-code="APIController.java" }}}
-To build and run the sample project, execute the `bootRun` Gradle task.
+<parent>
+
+ <groupId>org.springframework.boot</groupId>
+
+ <artifactId>spring-boot-starter-parent</artifactId>
+
+ <version>3.1.5</version>
+
+ <relativePath/>
+
+</parent>
+
+<dependencies>
+
+ <dependency>
+
+ <groupId>org.springframework.boot</groupId>
-Linux or macOS:
+ <artifactId>spring-boot-starter-web</artifactId>
-```bash
-./gradlew bootRun
-```
+ </dependency>
-Windows:
+ <dependency>
-```bash
-gradlew.bat bootRun
-```
+ <groupId>com.okta.spring</groupId>
-If you are configuring your own application using Maven and the Spring Boot Maven Plugin, you can execute the `spring-boot:run` goal.
+ <artifactId>okta-spring-boot-starter</artifactId>
-Linux or macOS:
+ <version>3.0.5</version>
-```bash
-mvn spring-boot:run
-```
+ </dependency>
-Windows:
+</dependencies>
-```bash
-mvn.cmd spring-boot:run
-```
+
+
+
+
+## Configure the resource server {{{ data-action="code" data-code="SecurityConfig.java" }}}
+
+
+To configure the application as a Resource Server and validate the JWTs, create a class that will provide an instance of SecurityFilterChain
, and add the @Configuration
annotation.
The routes shown below are available for the following requests:
GET /api/public
: available for non-authenticated requests
GET /api/private
: available for authenticated requests containing an access token with no additional scopes
GET /api/private-scoped
: available for authenticated requests containing an access token with the read:messages
scope granted
The example below shows how to secure API methods using the HttpSecurity
object provided in the filterChain()
method of the SecurityConfig
class. Route matchers restrict access based on the level of authorization required.
By default, Spring Security creates a GrantedAuthority
for each scope in the scope
claim of the JWT. This scope enables using the hasAuthority("SCOPE_read:messages")
method to restrict access to a valid JWT that contains the read:messages
scope.
To make your endpoint return a JSON, you can use a Java record. The member variables of this object is serialized into the key value for your JSON. Create a new record named Message
as an example domain object to return during the API calls.
To build and run the sample project, execute the bootRun
Gradle task.
Linux or macOS:
./gradlew bootRun
Windows:
gradlew.bat bootRun
If you are configuring your own application using Maven and the Spring Boot Maven Plugin, you can execute the spring-boot:run
goal.
Linux or macOS:
mvn spring-boot:run
Windows:
mvn.cmd spring-boot:run
The sample application will be available at http://localhost:3010/
. Read about how to test and use your API in the Using Your API article.
If your application did not launch successfully:
Use the Troubleshooting section to check your configuration.
Still having issues? Check out our documentation or visit our community page to get more help.
Auth0's Laravel SDK allows you to quickly add token-based authorization and route access control to your Laravel application. This guide demonstrates how to integrate Auth0 with a new (or existing) Laravel 9 or 10 application.
Backend applications differ from traditional web applications in that they do not handle user authentication or have a user interface. They provide an API that other applications can interact with. They accept access tokens from Authorization
headers in requests to control access to routes.
Separate front-end applications are usually built to interact with these types of backends. These can be anything from single-page applications or native or mobile apps (all of which Auth0 also provides SDKs for!)
When users need to interact with your backend application, they first authenticate with Auth0 using the frontend application. The frontend application then retrieves an access token from Auth0, which it can use to make requests to your backend application on behalf of the user.
As their name implies, access tokens are designed to address matters of access control (authorization), and do not contain information about the user. Backend applications work exclusively with access tokens. You can retrieve information about the user who created the token using the Management API, which we will demonstrate later.
-**Backend applications differ from traditional web applications in that they do not handle user authentication or have a user interface. They provide an API that other applications can interact with. They accept access tokens from `Authorization` headers in requests to control access to routes.** +## Laravel Installation -Separate front-end applications are usually built to interact with these types of backends. These can be anything from single-page applications or native or mobile apps (all of which Auth0 also provides SDKs for!) -When users need to interact with your backend application, they first authenticate with Auth0 using the frontend application. The frontend application then retrieves an access token from Auth0, which it can use to make requests to your backend application on behalf of the user. +If you do not already have a Laravel application set up, open a shell to a suitable directory for a new project and run the following command:
composer create-project --prefer-dist laravel/laravel auth0-laravel-api ^9.0
-As their name implies, access tokens are designed to address matters of access control (authorization), and do not contain information about the user. **Backend applications work exclusively with access tokens.** You can retrieve information about the user who created the token using the Management API, which we will demonstrate later.
+
-## Laravel Installation
+All the commands in this guide assume you are running them from the root of your Laravel project, directory so you should cd
into the new project directory:
cd auth0-laravel-api
-**If you do not already have a Laravel application set up**, open a shell to a suitable directory for a new project and run the following command:
+
-```shell
-composer create-project --prefer-dist laravel/laravel auth0-laravel-api ^9.0
-```
+
-All the commands in this guide assume you are running them from the root of your Laravel project, directory so you should `cd` into the new project directory:
+## SDK Installation
-```shell
-cd auth0-laravel-api
-```
-## SDK Installation
+Run the following command within your project directory to install the Auth0 Laravel SDK:
composer require auth0/login:^7.8 --update-with-all-dependencies
-Run the following command within your project directory to install the Auth0 Laravel SDK:
+
-```shell
-composer require auth0/login:^7.8 --update-with-all-dependencies
-```
+Then generate an SDK configuration file for your application:
php artisan vendor:publish --tag auth0
-Then generate an SDK configuration file for your application:
+
-```shell
-php artisan vendor:publish --tag auth0
-```
+
## SDK Configuration
-Run the following command from your project directory to download the Auth0 CLI:
-```shell
-curl -sSfL https://raw.githubusercontent.com/auth0/auth0-cli/main/install.sh | sh -s -- -b .
-```
+Run the following command from your project directory to download the Auth0 CLI:
curl -sSfL https://raw.githubusercontent.com/auth0/auth0-cli/main/install.sh | sh -s -- -b .
+
+
+
+Then authenticate the CLI with your Auth0 account, choosing "as a user" when prompted:
./auth0 login
+
+
+
+Next, create a new application with Auth0:
./auth0 apps create \
+
+--name "My Laravel Backend" \
+
+--type "regular" \
+
+--auth-method "post" \
+
+--callbacks "http://localhost:8000/callback" \
+
+--logout-urls "http://localhost:8000" \
+
+--reveal-secrets \
+
+--no-input \
+
+--json > .auth0.app.json
+
+
+
+You should also create a new API:
./auth0 apis create \
+
+--name "My Laravel Backend API" \
+
+--identifier "https://github.com/auth0/laravel-auth0" \
+
+--offline-access \
+
+--no-input \
+
+--json > .auth0.api.json
+
+
+
+This produces two files in your project directory that configure the SDK.
As these files contain credentials it's important to treat these as sensitive. You should ensure you do not commit these to version control. If you're using Git, you should add them to your .gitignore
file:
echo ".auth0.*.json" >> .gitignore
-Then authenticate the CLI with your Auth0 account, choosing "as a user" when prompted:
+
-```shell
-./auth0 login
-```
+
-Next, create a new application with Auth0:
+## Access Control {{{ data-action="code" data-code="routes/api.php#6:16" }}}
-```shell
-./auth0 apps create \
- --name "My Laravel Backend" \
- --type "regular" \
- --auth-method "post" \
- --callbacks "http://localhost:8000/callback" \
- --logout-urls "http://localhost:8000" \
- --reveal-secrets \
- --no-input \
- --json > .auth0.app.json
-```
-You should also create a new API:
+The SDK automatically registers its authorization guard with your Laravel application for use with the api
middleware, which by default Laravel applies to all routes in your application's routes/api.php
file.
For the SDK to work as expected without additional configuration, you should define your routes in the routes/api.php
file.
You can use the Auth0 SDK's authorization guard to restrict access to your application's routes.
To reject requests that do not contain a valid access token in the Authorization
header, you can use Laravel's auth
middleware:
Route::get('/private', function () {
-```shell
-./auth0 apis create \
- --name "My Laravel Backend API" \
- --identifier "https://github.com/auth0/laravel-auth0" \
- --offline-access \
- --no-input \
- --json > .auth0.api.json
-```
+ return response()->json([
-This produces two files in your project directory that configure the SDK.
+ 'message' \=> 'Your token is valid; you are authorized.',
-As these files contain credentials it's important to treat these as sensitive. You should ensure you do not commit these to version control. If you're using Git, you should add them to your `.gitignore` file:
+ ]);
-```bash
-echo ".auth0.*.json" >> .gitignore
-```
+})->middleware('auth');
-## Access Control {{{ data-action=code data-code="routes/api.php#6:16" }}}
+
-The SDK automatically registers its authorization guard with your Laravel application for use with the `api` middleware, which by default Laravel applies to all routes in your application's `routes/api.php` file.
+You can also require the provided token to have specific permissions by combining this with Laravel's can
middleware:
Route::get('/scope', function () {
-::: warning
-For the SDK to work as expected without additional configuration, **you should define your routes in the `routes/api.php` file.**
-:::
+ return response()->json([
-You can use the Auth0 SDK's authorization guard to restrict access to your application's routes.
+ 'message' => 'Your token is valid and has the `read:messages` permission; you are authorized.',
-To reject requests that do not contain a valid access token in the `Authorization` header, you can use Laravel's `auth` middleware:
+ ]);
-```php
-Route::get('/private', function () {
- return response()->json([
- 'message' => 'Your token is valid; you are authorized.',
- ]);
-})->middleware('auth');
-```
+})->middleware('auth')->can('read:messages');
-You can also require the provided token to have specific permissions by combining this with Laravel's `can` middleware:
+
-```php
-Route::get('/scope', function () {
- return response()->json([
- 'message' => 'Your token is valid and has the `read:messages` permission; you are authorized.',
- ]);
-})->middleware('auth')->can('read:messages');
-```
+
-## Token Information {{{ data-action=code data-code="routes/api.php#18:30" }}}
+## Token Information {{{ data-action="code" data-code="routes/api.php#18:30" }}}
-Information about the provided access token is available through Laravel's `Auth` Facade, or the `auth()` helper function.
-For example, to retrieve the user's identifier and email address:
+Information about the provided access token is available through Laravel's Auth
Facade, or the auth()
helper function.
For example, to retrieve the user's identifier and email address:
Route::get('/', function () {
-```php
-Route::get('/', function () {
- if (! auth()->check()) {
- return response()->json([
- 'message' => 'You did not provide a valid token.',
- ]);
- }
+ if (! auth()->check()) {
+
+ return response()->json([
+
+ 'message' => 'You did not provide a valid token.',
+
+ ]);
+
+ }
+
+
+
+ return response()->json([
+
+ 'message' => 'Your token is valid; you are authorized.',
+
+ 'id' => auth()->id(),
+
+ 'token' => auth()?->user()?->getAttributes(),
+
+ ]);
- return response()->json([
- 'message' => 'Your token is valid; you are authorized.',
- 'id' => auth()->id(),
- 'token' => auth()?->user()?->getAttributes(),
- ]);
});
-```
-## Retrieve User Information {{{ data-action=code data-code="routes/api.php#32:51" }}}
+
-You can retrieve information about the user who created the access token from Auth0 using the Auth0 Management API. The SDK provides a convenient wrapper for this API, accessible through the SDK's `management()` method.
+
-**Before making Management API calls you must enable your application to communicate with the Management API.** This can be done from the Auth0 Dashboards API page, choosing `Auth0 Management API`, and selecting the 'Machine to Machine Applications' tab. Authorize your Laravel application, and then click the down arrow to choose the scopes you wish to grant.
+## Retrieve User Information {{{ data-action="code" data-code="routes/api.php#32:51" }}}
+
+
+You can retrieve information about the user who created the access token from Auth0 using the Auth0 Management API. The SDK provides a convenient wrapper for this API, accessible through the SDK's management()
method.
Before making Management API calls you must enable your application to communicate with the Management API. This can be done from the Auth0 Dashboard's API page, choosing Auth0 Management API
, and selecting the 'Machine to Machine Applications' tab. Authorize your Laravel application, and then click the down arrow to choose the scopes you wish to grant.
For the following example, you should grant the read:users
scope. A list of API endpoints and the required scopes can be found in the Management API documentation.
use Auth0\Laravel\Facade\Auth0;
-For the following example, you should grant the `read:users` scope. A list of API endpoints and the required scopes can be found in the Management API documentation.
-```php
-use Auth0\Laravel\Facade\Auth0;
Route::get('/me', function () {
- $user = auth()->id();
- $profile = cache()->get($user);
- if (null === $profile) {
- $endpoint = Auth0::management()->users();
- $profile = $endpoint->get($user);
- $profile = Auth0::json($profile);
+ $user = auth()->id();
- cache()->put($user, $profile, 120);
- }
+ $profile = cache()->get($user);
- $name = $profile['name'] ?? 'Unknown';
- $email = $profile['email'] ?? 'Unknown';
- return response()->json([
- 'name' => $name,
- 'email' => $email,
- ]);
-})->middleware('auth');
-```
-::: note
-**You should cache user information in your application for brief periods.** This reduces the number of requests your application makes to Auth0, and improves performance. You should avoid storing user information in your application for long periods as this can lead to stale data. You should also avoid storing user information beyond the user's identifier in persistent databases.
-:::
+ if (null === $profile) {
-## Run the Application
+ $endpoint = Auth0::management()->users();
-You are now ready to start your Laravel application, so it can accept requests:
+ $profile = $endpoint->get($user);
-```shell
-php artisan serve
-```
+ $profile = Auth0::json($profile);
-## Retrieve a Test Token
-You can learn more about retrieving access tokens here. For this quickstart, however, you can simply use an access token from your API settings "test" view.
-::: note
-The `/me` route we created above will not work with a test token as there is no actual user associated with it.
-:::
+ cache()->put($user, $profile, 120);
+
+ }
+
+
+
+ $name = $profile['name'] ?? 'Unknown';
+
+ $email = $profile['email'] ?? 'Unknown';
+
-::::checkpoint
-:::checkpoint-default
-Open a shell and try issuing requests to your application.
-Begin by requesting the public route:
+ return response()->json([
-```shell
-curl --request GET \
- --url http://localhost:8000/api \
- --header 'Accept: application/json'
-```
+ 'name' => $name,
-Next, use your access token in an `Authorization` header to request a protected route:
+ 'email' => $email,
-```shell
-curl --request GET \
- --url http://localhost:8000/api/private \
- --header 'Accept: application/json' \
- --header 'Authorization: Bearer YOUR_ACCESS_TOKEN'
-```
+ ]);
-Finally, try requesting the scope-protected route, which will only succeed if the access token has the `read:messages` scope granted:
+})->middleware('auth');
-```shell
-curl --request GET \
- --url http://localhost:8000/api/scope \
- --header 'Accept: application/json' \
- --header 'Authorization: Bearer YOUR_ACCESS_TOKEN'
-```
+
-:::
+You should cache user information in your application for brief periods. This reduces the number of requests your application makes to Auth0, and improves performance. You should avoid storing user information in your application for long periods as this can lead to stale data. You should also avoid storing user information beyond the user's identifier in persistent databases.
You are now ready to start your Laravel application, so it can accept requests:
php artisan serve
+
+
+
+
+
+## Retrieve a Test Token
-- Try running `php artisan optimize:clear` to clear Laravel's cache.
-- Ensure your `.auth0.app.json` and `.auth0.api.json` files are at the root of your project.
-- Ensure you have enabled your Laravel application as a Machine-to-Machine application and granted it all the necessary scopes for the `Auth0 Management API` from the Auth0 Dashboard.
-Encountering problems? Check the SDK's documentation or our documentation hub. You should also consider visiting the community where our team and other community members can help answer your questions.
+You can learn more about retrieving access tokens here. For this quickstart, however, you can simply use an access token from your API settings' "test" view.
The /me
route we created above will not work with a test token as there is no actual user associated with it.
Open a shell and try issuing requests to your application.
Begin by requesting the public route:
curl --request GET \ --url http://localhost:8000/api \ --header 'Accept: application/json'
Next, use your access token in an Authorization
header to request a protected route:
curl --request GET \ --url http://localhost:8000/api/private \ --header 'Accept: application/json' \ --header 'Authorization: Bearer YOUR_ACCESS_TOKEN'
Finally, try requesting the scope-protected route, which will only succeed if the access token has the read:messages
scope granted:
curl --request GET \ --url http://localhost:8000/api/scope \ --header 'Accept: application/json' \ --header 'Authorization: Bearer YOUR_ACCESS_TOKEN'
Here are a couple of things to try:
Try running php artisan optimize:clear
to clear Laravel's cache.
Ensure your .auth0.app.json
and .auth0.api.json
files are at the root of your project.
Ensure you have enabled your Laravel application as a Machine-to-Machine application and granted it all the necessary scopes for the Auth0 Management API
from the Auth0 Dashboard.
Encountering problems? Check the SDK's documentation or our documentation hub. You should also consider visiting the community where our team and other community members can help answer your questions.
User Repositories and Models extends the Auth0 Laravel SDK to use custom user models, and how to store and retrieve users from a database.
Hooking Events covers how to listen for events raised by the Auth0 Laravel SDK, to fully customize the behavior of your integration.
Management API support is built into the Auth0 Laravel SDK, allowing you to interact with the Management API from your Laravel application.
This guide demonstrates how to integrate Auth0 with any new or existing Express.js API application using the express-oauth2-jwt-bearer
package.
If you have not created an API in your Auth0 dashboard yet, use the interactive selector to create a new Auth0 API or select an existing project API.
To set up your first API through the Auth0 dashboard, review our getting started guide. Each Auth0 API uses the API Identifier, which your application needs to validate the access token.
New to Auth0? Learn how Auth0 works and read about implementing API authentication and authorization using the OAuth 2.0 framework.
Permissions let you define how resources can be accessed on behalf of the user with a given access token. For example, you might choose to grant read access to the messages
resource if users have the manager access level, and a write access to that resource if they have the administrator access level.
You can define allowed permissions in the Permissions view of the Auth0 Dashboard's APIs section.
This example uses the read:messages
scope.
First, install the SDK with npm
.
npm install --save express-oauth2-jwt-bearer
+
+
+
+
-## Configure the middleware {{{ data-action=code data-code="server.js#1:10" }}}
+## Configure the middleware {{{ data-action="code" data-code="server.js#1:10" }}}
-Configure `express-oauth2-jwt-bearer` with your Domain and API Identifier.
-The `checkJwt` middleware shown to the right checks if the user's access token included in the request is valid. If the token is not valid, the user gets a 401 Authorization error when they try to access the endpoints.
+Configure express-oauth2-jwt-bearer
with your Domain and API Identifier.
The checkJwt
middleware shown to the right checks if the user's access token included in the request is valid. If the token is not valid, the user gets a 401 Authorization error when they try to access the endpoints.
The middleware does not check if the token has sufficient scope to access the requested resources.
-The middleware does not check if the token has sufficient scope to access the requested resources. +## Protect API endpoints {{{ data-action="code" data-code="server.js#12:32" }}} -## Protect API endpoints {{{ data-action=code data-code="server.js#12:32" }}} -To protect an individual route by requiring a valid JWT, configure the route with the `checkJwt` middleware constructed from `express-oauth2-jwt-bearer`. +To protect an individual route by requiring a valid JWT, configure the route with the checkJwt
middleware constructed from express-oauth2-jwt-bearer
.
You can configure individual routes to look for a particular scope. To achieve that, set up another middleware with the requiresScope
method. Provide the required scopes and apply the middleware to any routes you want to add authorization to.
Pass the checkJwt
and requiredScopes
middlewares to the route you want to protect.
In this configuration, only access tokens with the read:messages
scope can access the endpoint.
To make calls to your API, you need an Access Token. You can get an Access Token for testing purposes from the Test view in your API settings.
Provide the Access Token as an Authorization
header in your requests.
curl --request GET \
-You can configure individual routes to look for a particular scope. To achieve that, set up another middleware with the `requiresScope` method. Provide the required scopes and apply the middleware to any routes you want to add authorization to.
+ --url http://${account.namespace}/api_path \
-Pass the `checkJwt` and `requiredScopes` middlewares to the route you want to protect.
+ --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
-In this configuration, only access tokens with the `read:messages` scope can access the endpoint.
+
-<%= include('../_includes/_call_api') %>
+Now that you have configured your application, run your application to verify that:
GET /api/public
is available for non-authenticated requests.
GET /api/private
is available for authenticated requests.
GET /api/private-scoped
is available for authenticated requests containing an access token with the read:messages
scope.
If your application did not start successfully:
Verify you added the token as the Authorization
header
Ensure the token has the correct scopes. Verify with jwt.io.
Still having issues? Check out our documentation or visit our community page to get more help.
Auth0 allows you to add token-based endpoint authorization to almost any application type quickly. This guide demonstrates how to integrate Auth0, add token-based authorization, and protect application routes using the Auth0 PHP SDK.
To use this quickstart, you’ll need to:
Sign up for a free Auth0 account or log in to Auth0.
Have a working PHP project that you want to integrate with Auth0. Alternatively, you can view or download a sample application after logging in.
To use Auth0 services, you need to have an application registered in the Auth0 Dashboard. The Auth0 application is where you configure how you want authentication to work for your project.
Use the interactive selector to create a new Auth0 application or select an existing application that represents the project you want to integrate. Every application in Auth0 is assigned an alphanumeric, unique client ID that your application code uses to call Auth0 APIs through the SDK.
Any settings you configure using this quickstart automatically updates for your application in the Dashboard, which is where you can manage your applications in the future.
If you would rather explore a complete configuration, you can view a sample application instead.
Similarly, you need to create a new Auth0 API or use an existing API that represents the project you're integrating from the Dashboard. Choose a unique identifier for the API and make a note of it. You need that identifier to configure your application below.
-Use the interactive selector to create a new Auth0 application or select an existing application that represents the project you want to integrate. Every application in Auth0 is assigned an alphanumeric, unique client ID that your application code uses to call Auth0 APIs through the SDK. +## Install the Auth0 PHP SDK {{{ data-action="code" data-code="index.php" }}} -Any settings you configure using this quickstart automatically updates for your application in the Dashboard, which is where you can manage your applications in the future. -If you would rather explore a complete configuration, you can view a sample application instead. +Auth0 provides a PHP SDK (Auth0-PHP) to simplify the process of implementing Auth0 authentication and authorization in PHP apps.
The Auth0 PHP SDK requires PSR-17 and PSR-18 installed, compatible HTTP libraries for managing network requests. If you don't have libraries available, you can install reliable choices by running the following commands in your terminal:
cd <your-project-directory>
-### Configure an API
+ composer require symfony/http-client nyholm/psr7
-Similarly, you need to create a new Auth0 API or use an existing API that represents the project you're integrating from the Dashboard. Choose a unique identifier for the API and make a note of it. You need that identifier to configure your application below.
+
-## Install the Auth0 PHP SDK {{{ data-action=code data-code="index.php" }}}
+Now, install the Auth0 PHP SDK by running the following command in your terminal:
composer require auth0/auth0-php
-Auth0 provides a PHP SDK (Auth0-PHP) to simplify the process of implementing Auth0 authentication and authorization in PHP apps.
+
-The Auth0 PHP SDK requires PSR-17 and PSR-18 installed, compatible HTTP libraries for managing network requests. If you don't have libraries available, you can install reliable choices by running the following commands in your terminal:
+For the SDK to function properly, you must set the following properties in the Auth0 SDK during initialization:
strategy
: The strategy helps guide the behavior of the SDK for the use case of your app. In this case, you want to set this to the constant
Auth0\SDK\Configuration\SdkConfiguration::STRATEGY_API
domain: The domain of your Auth0 tenant. Generally, you find this in the Auth0 Dashboard under Application's Settings in the Domain field. If you are using a custom domain, set this to the value of your custom domain instead.
clientId: The ID of the Auth0 Application you set up earlier in this quickstart. You can find this in the Auth0 Dashboard under your Application's Settings in the Client ID field.
clientSecret: The secret of the Auth0 application you created earlier in this quickstart. Client secret is in the Auth0 Dashboard under your Application's Settings in the Client Secret field.
audience: The identifier of the Auth0 API you registered above. This must be provided as an array.
Your Auth0 SDK is now properly configured. Run your application to verify that:
The SDK is initializing correctly.
Your application is not throwing any errors related to Auth0.
Sorry about that. Here's a couple things to double check:
Make sure the correct application is selected.
Did you save after entering your URLs?
Make sure the domain and client ID imported correctly.
Still having issues? Check out our documentation or visit our community page to get more help.
Next, expand your application to retrieve and process bearer tokens. Bearer tokens are access tokens provided to your API with requests from clients on a users' behalf. Access tokens approve or deny access to routes in your application. This is referred to as endpoint authorization.
The easiest way to retrieve access tokens from a request is using the PHP SDK's getBearerToken()
method. This method fetches tokens from GET parameters, POST bodies, request headers, and other sources. In this case, the PHP SDK processes tokens passed from GET requests in the token
parameter or from the HTTP Authorization
header.
Now, install a routing library to help direct incoming requests to your application. This isn't a required step, but simplifies the application structure for the purposes of this quickstart.
composer require steampixel/simple-php-router
-:::checkpoint-failure
-Sorry about that. Here's a couple things to double check:
-* Make sure the correct application is selected.
-* Did you save after entering your URLs?
-* Make sure the domain and client ID imported correctly.
+
-Still having issues? Check out our documentation or visit our community page to get more help.
+Create a new file in your application called router.php
to define the routes. Copy in the code from the interactive panel to the right under the router.php tab.
Now that you have configured your Auth0 application, the Auth0 PHP SDK, and you application retrieves bearer tokens from requests, the next step is to set up endpoint authorization for your project. The getBearerToken()
method you implemented above returns a Token
class that includes details on the request's access.
Since the getBearerToken()
method automatically validates and verifies the incoming request, your application determines the details of the access token by evaluating the method's response. When the response is null, no valid token has been provided. Otherwise, inspect the contents of the response to learn more about the request.
In the interactive panel to the right, you can see a check if the response is null or not to filter access to your /api/private
route.
In some cases, you may want to filter access to a specific route based on the requested scopes in an access token. As shown in the interactive panel on the right, evaluate the contents of the 'scope' property from the getBearerToken()
method's response to check the scopes granted by the access token.
This guide demonstrates how to integrate Auth0 with any new or existing Python API built with Flask.
If you haven't created an API in your Auth0 dashboard yet, you can use the interactive selector to create a new Auth0 API or select an existing API that represents the project you want to integrate with.
Alternatively, you can read our getting started guide that helps you set up your first API through the Auth0 dashboard.
Every API in Auth0 is configured using an API Identifier that your application code will use as the Audience to validate the Access Token.
New to Auth0? Learn how Auth0 works and read about implementing API authentication and authorization using the OAuth 2.0 framework.
Permissions let you define how resources can be accessed on behalf of the user with a given access token. For example, you might choose to grant read access to the messages
resource if users have the manager access level, and a write access to that resource if they have the administrator access level.
You can define allowed permissions in the Permissions view of the Auth0 Dashboard's APIs section.
This example uses the read:messages
scope.
Add the following dependencies to your requirements.txt
:
# /requirements.txt
-Add the following dependencies to your `requirements.txt`:
-```python
-# /requirements.txt
-flask
-Authlib
-```
+ flask
-## Create the JWT validator {{{ data-action=code data-code="validator.py" }}}
+ Authlib
-We're going to use a library called Authlib to create a ResourceProtector, which is a type of Flask decorator that protects our resources (API routes) with a given validator.
+
-The validator will validate the Access Token that we pass to the resource by checking that it has a valid signature and claims.
+
-We can use AuthLib's `JWTBearerTokenValidator` validator with a few tweaks to make sure it conforms to our requirements on validating Access Tokens.
+## Create the JWT validator {{{ data-action="code" data-code="validator.py" }}}
-To create our `Auth0JWTBearerTokenValidator` we need to pass it our `domain` and `audience` (API Identifier). It will then get the public key required to verify the token's signature and pass it to the `JWTBearerTokenValidator` class.
-We'll then override the class's `claims_options` to make sure the token's expiry, audience and issue claims are validated according to our requirements.
+We're going to use a library called Authlib to create a ResourceProtector, which is a type of Flask decorator that protects our resources (API routes) with a given validator.
The validator will validate the Access Token that we pass to the resource by checking that it has a valid signature and claims.
We can use AuthLib's JWTBearerTokenValidator
validator with a few tweaks to make sure it conforms to our requirements on validating Access Tokens.
To create our Auth0JWTBearerTokenValidator
we need to pass it our domain
and audience
(API Identifier). It will then get the public key required to verify the token's signature and pass it to the JWTBearerTokenValidator
class.
We'll then override the class's claims_options
to make sure the token's expiry, audience and issue claims are validated according to our requirements.
Next we'll create a Flask application with 3 API routes:
/api/public
A public endpoint that requires no authentication.
/api/private
A private endpoint that requires a valid Access Token JWT.
/api/private-scoped
A private endpoint that requires a valid Access Token JWT that contains the given scope
.
The protected routes will have a require_auth
decorator which is a ResourceProtector
that uses the Auth0JWTBearerTokenValidator
we created earlier.
To create the Auth0JWTBearerTokenValidator
we'll pass it our tenant's domain and the API Identifier of the API we created earlier.
The require_auth
decorator on the private_scoped
route accepts an additional argument "read:messages"
, which checks the Access Token for the Permission (Scope) we created earlier.
To make calls to your API, you need an Access Token. You can get an Access Token for testing purposes from the Test view in your API settings.
Provide the Access Token as an Authorization
header in your requests.
curl --request GET \
-The protected routes will have a `require_auth` decorator which is a `ResourceProtector` that uses the `Auth0JWTBearerTokenValidator` we created earlier.
+ --url http://${account.namespace}/api_path \
-To create the `Auth0JWTBearerTokenValidator` we'll pass it our tenant's domain and the API Identifier of the API we created earlier.
+ --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
-The `require_auth` decorator on the `private_scoped` route accepts an additional argument `"read:messages"`, which checks the Access Token for the Permission (Scope) we created earlier.
+
-<%= include('../_includes/_call_api') %>
+
diff --git a/articles/quickstart/backend/rails/files/app/controllers/application_controller.md b/articles/quickstart/backend/rails/files/app/controllers/application_controller.md
new file mode 100644
index 0000000000..75520386ba
--- /dev/null
+++ b/articles/quickstart/backend/rails/files/app/controllers/application_controller.md
@@ -0,0 +1,12 @@
+---
+name: app/controllers/application_controller.rb
+language: powershell
+---
+
+```powershell
+ # frozen_string_literal: true
+
+ class ApplicationController < ActionController::API
+ include Secured
+ end
+```
diff --git a/articles/quickstart/backend/rails/files/app/controllers/concerns/secured.md b/articles/quickstart/backend/rails/files/app/controllers/concerns/secured.md
new file mode 100644
index 0000000000..c6529ef19b
--- /dev/null
+++ b/articles/quickstart/backend/rails/files/app/controllers/concerns/secured.md
@@ -0,0 +1,67 @@
+---
+name: app/controllers/concerns/secured.rb
+language: powershell
+---
+
+```powershell
+ # frozen_string_literal: true
+
+ module Secured
+ extend ActiveSupport::Concern
+
+ REQUIRES_AUTHENTICATION = { message: 'Requires authentication' }.freeze
+ BAD_CREDENTIALS = {
+message: 'Bad credentials'
+ }.freeze
+ MALFORMED_AUTHORIZATION_HEADER = {
+error: 'invalid_request',
+error_description: 'Authorization header value must follow this format: Bearer access-token',
+message: 'Bad credentials'
+ }.freeze
+ INSUFFICIENT_PERMISSIONS = {
+error: 'insufficient_permissions',
+error_description: 'The access token does not contain the required permissions',
+message: 'Permission denied'
+ }.freeze
+
+ def authorize
+token = token_from_request
+
+return if performed?
+
+validation_response = Auth0Client.validate_token(token)
+
+@decoded_token = validation_response.decoded_token
+
+return unless (error = validation_response.error)
+
+render json: { message: error.message }, status: error.status
+ end
+
+ def validate_permissions(permissions)
+raise 'validate_permissions needs to be called with a block' unless block_given?
+return yield if @decoded_token.validate_permissions(permissions)
+
+render json: INSUFFICIENT_PERMISSIONS, status: :forbidden
+ end
+
+ private
+
+ def token_from_request
+authorization_header_elements = request.headers['Authorization']&.split
+
+render json: REQUIRES_AUTHENTICATION, status: :unauthorized and return unless authorization_header_elements
+
+unless authorization_header_elements.length == 2
+ render json: MALFORMED_AUTHORIZATION_HEADER,
+ status: :unauthorized and return
+end
+
+scheme, token = authorization_header_elements
+
+render json: BAD_CREDENTIALS, status: :unauthorized and return unless scheme.downcase == 'bearer'
+
+token
+ end
+ end
+```
diff --git a/articles/quickstart/backend/rails/files/app/controllers/private_controller.md b/articles/quickstart/backend/rails/files/app/controllers/private_controller.md
new file mode 100644
index 0000000000..336740f6cd
--- /dev/null
+++ b/articles/quickstart/backend/rails/files/app/controllers/private_controller.md
@@ -0,0 +1,13 @@
+---
+name: app/controllers/private_controller.rb
+language: powershell
+---
+
+```powershell
+ # frozen_string_literal: true
+ class PublicController < ApplicationController
+ def public
+render json: { message: 'All good. You don\'t need to be authenticated to call this.' }
+ end
+end
+```
diff --git a/articles/quickstart/backend/rails/files/app/controllers/public_controller.md b/articles/quickstart/backend/rails/files/app/controllers/public_controller.md
new file mode 100644
index 0000000000..f8a6db5aff
--- /dev/null
+++ b/articles/quickstart/backend/rails/files/app/controllers/public_controller.md
@@ -0,0 +1,13 @@
+---
+name: app/controllers/public_controller.rb
+language: powershell
+---
+
+```powershell
+ # frozen_string_literal: true
+ class PublicController < ApplicationController
+ def public
+render json: { message: 'All good. You don\'t need to be authenticated to call this.' }
+ end
+ end
+```
diff --git a/articles/quickstart/backend/rails/files/app/lib/auth0_client.md b/articles/quickstart/backend/rails/files/app/lib/auth0_client.md
new file mode 100644
index 0000000000..079089b4d9
--- /dev/null
+++ b/articles/quickstart/backend/rails/files/app/lib/auth0_client.md
@@ -0,0 +1,66 @@
+---
+name: app/lib/auth0_client.rb
+language: powershell
+---
+
+```powershell
+ # frozen_string_literal: true
+
+ require 'jwt'
+ require 'net/http'
+
+ # Auth0Client class to handle JWT token validation
+ class Auth0Client
+ # Auth0 Client Objects
+ Error = Struct.new(:message, :status)
+ Response = Struct.new(:decoded_token, :error)
+ Token = Struct.new(:token) do
+def validate_permissions(permissions)
+ required_permissions = Set.new permissions
+ scopes = token[0]['scope']
+ token_permissions = scopes.present? ? Set.new(scopes.split(" ")) : Set.new
+ required_permissions <= token_permissions
+end
+ end
+
+ # Helper Functions
+ def self.domain_url
+"https://#{Rails.configuration.auth0.domain}/"
+ end
+
+ def self.decode_token(token, jwks_hash)
+JWT.decode(token, nil, true, {
+ algorithm: 'RS256',
+ iss: domain_url,
+ verify_iss: true,
+ aud: Rails.configuration.auth0.audience,
+ verify_aud: true,
+ jwks: { keys: jwks_hash[:keys] }
+ })
+ end
+
+ def self.get_jwks
+jwks_uri = URI("#{domain_url}.well-known/jwks.json")
+Net::HTTP.get_response jwks_uri
+ end
+
+ # Token Validation
+ def self.validate_token(token)
+jwks_response = get_jwks
+
+unless jwks_response.is_a? Net::HTTPSuccess
+ error = Error.new(message: 'Unable to verify credentials', status: :internal_server_error)
+ return Response.new(nil, error)
+end
+
+jwks_hash = JSON.parse(jwks_response.body).deep_symbolize_keys
+
+decoded_token = decode_token(token, jwks_hash)
+
+Response.new(Token.new(decoded_token), nil)
+ rescue JWT::VerificationError, JWT::DecodeError => e
+error = Error.new('Bad credentials', :unauthorized)
+Response.new(nil, error)
+ end
+ end
+```
diff --git a/articles/quickstart/backend/rails/interactive.md b/articles/quickstart/backend/rails/interactive.md
index 93069f4e7b..5fc5f3a668 100644
--- a/articles/quickstart/backend/rails/interactive.md
+++ b/articles/quickstart/backend/rails/interactive.md
@@ -1,23 +1,17 @@
---
-title: Add authorization to a Ruby on Rails API
-description: This tutorial demonstrates how to add authorization to a Ruby on Rails API.
-topics:
- - quickstart
- - backend
- - rails
-github:
- path: 01-Authentication-RS256
-contentType: tutorial
-useCase: quickstart
-interactive: true
+title: Add Authorization to Your Ruby on Rails API
+description: This tutorial performs access token validation using the jwt Gem within a custom Auth0Client class.
+interactive: true
files:
- - files/application_controller
- - files/auth0_client
- - files/secured
- - files/public
- - files/private
+ - files/app/controllers/application_controller
+ - files/app/lib/auth0_client
+ - files/app/controllers/concerns/secured
+ - files/app/controllers/public_controller
+ - files/app/controllers/private_controller
+github:
+ path: https://github.com/auth0-samples/auth0-rubyonrails-api-samples/tree/master/01-Authentication-RS256
+locale: en-US
---
-
# Add Authorization to Your Ruby on Rails API
This tutorial performs access token validation using the **jwt** Gem within a custom `Auth0Client` class. A Concern called `Secured` is used to authorize endpoints which require authentication through an incoming access token.
@@ -31,66 +25,56 @@ Each Auth0 API uses the API Identifier, which your application needs to validate
<%= include('../../../_includes/_api_auth_intro') %>
## Define permissions
-<%= include('../_includes/_api_scopes_access_resources') %>
+
+
+Permissions let you define how resources can be accessed on behalf of the user with a given access token. For example, you might choose to grant read access to the messages
resource if users have the manager access level, and a write access to that resource if they have the administrator access level.
You can define allowed permissions in the Permissions view of the Auth0 Dashboard's APIs section.
This example uses the read:messages
scope.
Install the jwt Gem.
gem 'jwt'
+
+ bundle install
+
+
+
+
+
+## Create an Auth0Client class {{{ data-action="code" data-code="app/controllers/concerns/secured.rb" }}}
-Create a class called `Auth0Client`. This class decodes and verifies the incoming access token taken from the `Authorization` header of the request.
-The `Auth0Client` class retrieves the public key for your Auth0 tenant and then uses it to verify the signature of the access token. The `Token` struct defines a `validate_permissions` method to look for a particular `scope` in an access token by providing an array of required scopes and check if they are present in the payload of the token.
+Create a class called Auth0Client
. This class decodes and verifies the incoming access token taken from the Authorization
header of the request.
The Auth0Client
class retrieves the public key for your Auth0 tenant and then uses it to verify the signature of the access token. The Token
struct defines a validate_permissions
method to look for a particular scope
in an access token by providing an array of required scopes and check if they are present in the payload of the token.
Create a Concern called Secured
which looks for the access token in the Authorization
header of an incoming request.
If the token is present, the Auth0Client.validate_token
will use the jwt
Gem to verify the token's signature and validate the token's claims.
In addition to verifying that the access token is valid, the Concern also includes a mechanism for confirming the token has the sufficient scope to access the requested resources. In this example we define a validate_permissions
method that receives a block and checks the permissions by calling the Token.validate_permissions
method from the Auth0Client
class.
For the /private-scoped
route, the scopes defined will be intersected with the scopes coming in the payload, to determine if it contains one or more items from the other array.
By adding the Secure
concern to your application controller, you'll only need to use a before_action
filter in the controller that requires authorization.
Create a controller to handle the public endpoint /api/public
.
The /public
endpoint does not require any authorization so no before_action
is needed.
Create a controller to handle the private endpoints: /api/private
and /api/private-scoped
.
/api/private
is available for authenticated requests containing an access token with no additional scopes.
/api/private-scoped
is available for authenticated requests containing an access token with the read:messages
scope granted
The protected endpoints need to call the authorize
method from the Secured
concern, for that you use before_action :authorize
, this ensure the Secured.authorize
method is called before every action in the PrivateController
.
To make calls to your API, you need an Access Token. You can get an Access Token for testing purposes from the Test view in your API settings.
Provide the Access Token as an Authorization
header in your requests.
curl --request GET \
-`/api/private` is available for authenticated requests containing an access token with no additional scopes.
+ --url http://${account.namespace}/api_path \
-`/api/private-scoped` is available for authenticated requests containing an access token with the `read:messages` scope granted
+ --header 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
-The protected endpoints need to call the `authorize` method from the `Secured` concern, for that you use `before_action :authorize`, this ensure the `Secured.authorize` method is called before every action in the `PrivateController`.
+
-<%= include('../_includes/_call_api') %>
+Now that you have configured your application, run your application to verify that:
GET /api/public
is available for non-authenticated requests.
GET /api/private
is available for authenticated requests.
GET /api/private-scoped
is available for authenticated requests containing an Access Token with the read:messages
scope.
If your application did not start successfully:
Verify you added the token as the Authorization
header
Ensure the token has the correct scopes. Verify with jwt.io.
Still having issues? Check out our documentation or visit our community page to get more help.
Auth0 allows you to add authorization to any kind of application. This guide demonstrates how to integrate Auth0 with any new or existing ASP.NET Owin Web API application using the Microsoft.Owin.Security.Jwt
package.
If you have not created an API in your Auth0 dashboard yet, you can use the interactive selector to create a new Auth0 API or select an existing API for your project.
To set up your first API through the Auth0 dashboard, review our getting started guide.
Each Auth0 API uses the API Identifier, which your application needs to validate the access token.
New to Auth0? Learn how Auth0 works and read about implementing API authentication and authorization using the OAuth 2.0 framework.
Permissions let you define how resources can be accessed on behalf of the user with a given access token. For example, you might choose to grant read access to the messages
resource if users have the manager access level, and a write access to that resource if they have the administrator access level.
You can define allowed permissions in the Permissions view of the Auth0 Dashboard's APIs section. The following example uses the read:messages
scope.
Install the Microsoft.Owin.Security.Jwt
NuGetPackage. This package contains the OWIN JWT Middleware necessary to use Auth0 access tokens in the ASP.NET Owin Web API.
Install-Package Microsoft.Owin.Security.Jwt
-## Verifying the token signature {{{ data-action=code data-code="OpenIdConnectSigningKeyResolver.cs" }}}
-The OWIN JWT middleware does not use Open ID Connect Discovery by default, so you must provide a custom `IssuerSigningKeyResolver`. Create the `OpenIdConnectSigningKeyResolver` class and ensure to return the correct `SecurityKey` by implementing `GetSigningKey`.
-This class is then used as `TokenValidationParameters.IssuerSigningKeyResolver` while configuring the middleware in `Startup.cs`.
+
-:::note
-This custom resolver is deprecated and no longer available. You must provider this customer resolver yourself.
-:::
+
-## Validate scopes {{{ data-action=code data-code="ScopeAuthorizeAttribute.cs" }}}
+## Configure the middleware {{{ data-action="code" data-code="Startup.cs" }}}
-The JWT middleware verifies that the access token included in the request is valid; however, it doesn't yet include any mechanism for checking that the token has the sufficient **scope** to access the requested resources.
-Create a class called `ScopeAuthorizeAttribute` which inherits from `System.Web.Http.AuthorizeAttribute`. This attribute will check that the `scope` claim issued by your Auth0 tenant is present, and if so it will ensure that the `scope` claim contains the requested scope.
+Go to the Configuration
method of your Startup
class and add a call to UseJwtBearerAuthentication
passing in the configured JwtBearerAuthenticationOptions
.
The JwtBearerAuthenticationOptions
needs to specify your Auth0 API Identifier in the ValidAudience
property, and the full path to your Auth0 domain as the ValidIssuer
. You will need to configure the IssuerSigningKeyResolver
to use the instance of OpenIdConnectSigningKeyResolver
to resolve the signing key.
Do not forget the trailing slash.
Ensure the URL specified for ValidIssuer
contains a trailing forward slash (/
). This must match exactly with the JWT issuer claim. API calls will not authenticate correctly if you misconfigured this value.
The OWIN JWT middleware does not use Open ID Connect Discovery by default, so you must provide a custom IssuerSigningKeyResolver
.
Create the OpenIdConnectSigningKeyResolver
class and ensure to return the correct SecurityKey
by implementing GetSigningKey
. This class is then used as TokenValidationParameters.IssuerSigningKeyResolver
while configuring the middleware in Startup.cs
.
This custom resolver is deprecated and no longer available. You must provide this custom resolver yourself.
The JWT middleware verifies that the access token included in the request is valid; however, it doesn't yet include any mechanism for checking that the token has the sufficient scope to access the requested resources.
Create a class called ScopeAuthorizeAttribute
which inherits from System.Web.Http.AuthorizeAttribute
. This attribute will check that the scope
claim issued by your Auth0 tenant is present, and if so, it will ensure that the scope
claim contains the requested scope.
The routes shown below are available for the following requests:
GET /api/public
: Available for non-authenticated requests.
GET /api/private
: Available for authenticated requests containing an access token with no additional scopes.
GET /api/private-scoped
: Available for authenticated requests containing an access token with the read:messages
scope granted.
The JWT middleware integrates with the standard ASP.NET authentication and authorization mechanisms, so you only need to decorate your controller action with the [Authorize]
attribute to secure an endpoint.
Update the action with the ScopeAuthorize
attribute and pass the name of the required scope
in the scope
parameter. This ensures the correct scope is available to call a specific API endpoint.
Now that you have configured your application, run your application and verify that:
GET /api/public
is available for non-authenticated requests.
GET /api/private
is available for authenticated requests.
GET /api/private-scoped
is available for authenticated requests containing an access token with the read:messages
scope.
If your application did not start successfully:
Ensure your configured the ValidIssuer
and ValidAudience
values correctly
Verify you added the token as the Authorization
header
Ensure the token has the correct scopes. Verify with jwt.io.
Still having issues? Check out our documentation or visit our community page to get more help.
This tutorial demonstrates how to add user login to an Android application using native Facebook Login. We recommend that you log in to follow this quickstart with examples configured for your account.
Android Studio 3.6.1
Android SDK 25
Emulator - Nexus 5X - Android 6.0
This tutorial describes how to implement login with the Facebook SDK.
Install and configure the Facebook Login SDK. You’ll also go through the process of creating a Facebook app in https://developers.facebook.com. When you finish this step, you should have a mobile app running with Facebook Login integrated.
Configure your Auth0 application in the dashboard to use Facebook Native Sign In. See Add Facebook Login to Native Apps. When you finish this step, your application will be able to implement Facebook Native Login.
+ +## Request Facebook permissions + + +
Your application is already able to sign in with Facebook. However, to ensure you have a rich user profile, you need to update the permissions with which the Facebook Login Button was set up.
Set the requested permissions to public_profile
and email
. This way, the user email will also be included as part of the response, provided the access request is accepted by the user.
loginButton.setPermissions(Arrays.asList("public_profile", "email"));
Now, to kick off the authentication process with Auth0, create a new method in which you will prepare the payload to be sent.
You will make use of a small interface to handle our internal callbacks.
In the sample, the method was named performLogin
and the interface SimpleCallback
. Go ahead and add both.
Now, call the method from the Facebook login callback's onSuccess
method.
When you sign in with Facebook at Auth0, the backend will perform some checks in the background to ensure the user is who they say they are. To achieve this, it needs to be provided with a Session Access Token.
Furthermore, if a user needs to be created on Auth0 to represent this Facebook user, the backend will require some of their information, such as their name, last name, and email. The email, if provided, will be flagged as non-verified on the Auth0 user profile.
To obtain the Session Access Token and the user profile, two additional requests need to be made against the Facebook API.
+ +## Fetch Facebook session Access Token {{{ data-action="code" data-code="fetchSessionToken" }}} + + +Make a new GET request against the Facebook API's /oauth/access_token
endpoint. Use the following query parameters:
grant_type
: fb_attenuate_token
.
fb_exchange_token
: the access token received upon login.
client_id
: your App ID. This value comes from the Facebook Developer's dashboard and should already be in use in your application if you have integrated Facebook Login successfully.
Put the logic from this step in its own method. You will be calling it later from the previously-added method.
The sample uses the Facebook SDK's GraphRequest
class to perform this request.
Now make another GET request, just like in the step above. The endpoint path will be the User ID value from the Facebook login result (for example, /904636746222815
). Use the following parameters:
access_token
: the access token received upon login.
fields
: the fields from the user profile that you'd like to get back in the response. These are directly tied to the Facebook Login Button permissions that were configured at the beginning. When a permission is optional, the user must first consent to give access to it. For the purpose of signing up a user at Auth0, their full name and email will suffice.
Now that the required artifacts have been obtained, you are ready to trade them for Auth0 user credentials, such as the ID and Access Tokens. But first, you must set up the Auth0 SDK to make that last request.
Go to the Applications section of the Auth0 Dashboard and select the existing application in which you enabled Sign in with Facebook. If you need help with this step, please check the requirements section at the top of this article.
Copy the Domain and Client ID values from the application settings page. These are required by the SDK.
Create two new resources in your Android application's strings.xml file to store them. The name of the keys must match the ones used below: + +
<resources>
+
+ <string name="com_auth0_domain">${account.namespace}</string>
+
+ <string name="com_auth0_client_id">${account.clientId}</string>
+
+</resources>
+
+
+
+In your Android application, add this line to the app/build.gradle file:
dependencies {
+
+ implementation 'com.auth0.android:auth0:1.+'
+
+}
+
+
+
+Now is time to run the Gradle Sync task to refresh the project and its dependencies.
If your application does not plan to make use of the Web Authentication module provided by the SDK, you will need to remove the unused activity from the AndroidManifest.xml file to prevent Manifest Placeholder issues. This can be achieved by adding an activity declaration and annotating it with tools:node="remove".
<application>
+
+ <!-- Add the activity declaration line below -->
+
+ <activity
+
+ android:name="com.auth0.android.provider.AuthenticationActivity"
+
+ tools:node="remove" />
+
+
+
+</application>
+
+
+
+However, if you do plan to support Web Authentication, head over here to learn how to declare the Manifest Placeholders.
+ +## Exchange the received data for Auth0 tokens {{{ data-action="code" data-code="exchangeTokens" }}} + + +The SDK must be instantiated before use. Define a field at the class level and initialize it on the onCreate
method. Note how the credentials defined in the step above are passed to the Auth0
constructor and then a new instance of the AuthenticationAPIClient
is created with it.
private AuthenticationAPIClient auth0Client;
+
+
+
+@Override
+
+public void onCreate(Bundle savedInstanceState) {
+
+ super.onCreate(savedInstanceState);
+
+
+
+ setContentView(R.layout.activity_login);
+
+
+
+ Auth0 account = new Auth0(getString(R.string.com_auth0_client_id), getString(R.string.com_auth0_domain));
+
+ auth0Client = new AuthenticationAPIClient(account);
+
+
+
+ //...
+
+}
+
+
+
+Create the method that will hold the logic to exchange the two obtained artifacts for Auth0 user credentials. In the sample, this method is named exchangeTokens
.
The API client declares the method loginWithNativeSocialToken
that receives a token and a subject type. The former corresponds to the session token, and the latter indicates what type of connection the backend will attempt to authenticate with.
For native Facebook Login, you will use the following value: "http://auth0.com/oauth/token-type/facebook-info-session-access-token"
Other values that need to be configured are the user profile (using the user_profile
key) and the scope you request the Auth0 tokens contain.
It's a good practice to keep all the values that you know won't change as constants at the top of the class. The sample makes use of constants for the subject token type, the Facebook permissions, and the Auth0 scopes. You can read more about Auth0 scopes in the dedicated article.
Now that every step is defined in its own method, it's time to put everything together inside the performLogin
method.
If everything went well, you should now be able to authenticate natively with the Facebook Login SDK. This means that if the Facebook app is installed on the device, the authentication will be handled via the application and not a browser app.
diff --git a/articles/quickstart/native/android/files/MainActivity.md b/articles/quickstart/native/android/files/MainActivity.md new file mode 100644 index 0000000000..2e476f1606 --- /dev/null +++ b/articles/quickstart/native/android/files/MainActivity.md @@ -0,0 +1,78 @@ +--- +name: MainActivity.kt +language: kotlin +--- + +```kotlin +import com.auth0.android.Auth0 +import com.auth0.android.provider.WebAuthProvider + +class MainActivity : AppCompatActivity() { + + private lateinit var account: Auth0 + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + // Set up the account object with the Auth0 application details + account = Auth0( + getString(R.string.com_auth0_client_id), + getString(R.string.com_auth0_domain), + ) + } + + private fun loginWithBrowser() { + // Setup the WebAuthProvider, using the custom scheme and scope. + + WebAuthProvider.login(account) + .withScheme("demo") + .withScope("openid profile email") + // Launch the authentication passing the callback where the results will be received + .start(this, object : CallbackTo use Auth0 services, you need to have an application set up in the Auth0 Dashboard. The Auth0 application is where you will configure authentication in your project.
Use the interactive selector to create a new Auth0 application or select an existing application that represents the project you want to integrate with. Every application in Auth0 is assigned an alphanumeric, unique client ID that your application code will use to call Auth0 APIs through the SDK.
Any settings you configure using this quickstart will automatically update for your Application in the Dashboard, which is where you can manage your Applications in the future.
If you would rather explore a complete configuration, you can view a sample application instead.
A callback URL is the application URL that Auth0 will direct your users to once they have authenticated. If you do not set this value, Auth0 will not return users to your application after they log in.
If you are following along with our sample project, set this to demo://{yourDomain}/android/YOUR_APP_PACKAGE_NAME/callback
.
A logout URL is the application URL Auth0 will redirect your users to once they log out. If you do not set this value, users will not be able to log out from your application and will receive an error.
If you are following along with our sample project, set this to demo://{yourDomain}/android/YOUR_APP_PACKAGE_NAME/callback
Add the Auth0 Android SDK into your project. The library will make requests to the Auth0's Authentication and Management APIs.
In your app's build.gradle
dependencies section, add the following:
implementation 'com.auth0.android:auth0:2. '
-A callback URL is the application URL that Auth0 will direct your users to once they have authenticated. If you do not set this value, Auth0 will not return users to your application after they log in.
+
-::: note
-If you are following along with our sample project, set this to `demo://${account.namespace}/android/YOUR_APP_PACKAGE_NAME/callback`.
-:::
+Ensure you target Java 8+ byte code for Android and Kotlin plugins respectively.
-### Configure logout URLs +## Add manifest placeholders {{{ data-action="code" data-code="build.gradle#10:12" }}} -A logout URL is the application URL Auth0 will redirect your users to once they log out. If you do not set this value, users will not be able to log out from your application and will receive an error. -::: note -If you are following along with our sample project, set this to `demo://${account.namespace}/android/YOUR_APP_PACKAGE_NAME/callback`. -::: +The SDK requires manifest placeholders. Auth0 uses placeholders internally to define an intent-filter
, which captures the authentication callback URL. You must set Auth0 tenant domain and the callback URL scheme.
You do not need to declare a specific intent-filter
for your activity, because you have defined the manifest placeholders with your Auth0 Domain and Scheme values and the library will handle the redirection for you.
We've used a value of demo
for auth0Scheme
here, so that a custom URL scheme can be used for the URL that Auth0 redirects to after login. The alternative is https
if you want to use Android App Links. You can read more about setting this value in the Auth0.Android SDK README.
For the SDK to function properly, you must set the following properties in strings.xml
:
com_auth0_domain
: The domain of your Auth0 tenant. Generally, you can find this in the Auth0 Dashboard under your Application's Settings in the Domain field. If you are using a custom domain, you should set this to the value of your custom domain instead.
com_auth0_client_id
: The ID of the Auth0 Application you set up earlier in this quickstart. You can find this in the Auth0 Dashboard under your Application's Settings in the Client ID field.
Ensure that the AndroidManifest.xml
file specifies the android.permissions.INTERNET
permission:
<uses-permission android:name="android.permission.INTERNET" />
-```groovy
-implementation 'com.auth0.android:auth0:2.+'
-```
+
-Ensure you target Java 8+ byte code for Android and Kotlin plugins respectively.
+Run Sync Project with Gradle Files inside Android Studio or execute ./gradlew clean assembleDebug
from the command line.
For more information about using Gradle, check the Gradle official documentation.
Universal Login is the easiest way to set up authentication in your application. We recommend using it for the best experience, best security and the fullest array of features.
In the onCreate
method, create a new instance of the Auth0
class to hold user credentials.
Create a loginWithBrowser
method and use the WebAuthProvider
class to authenticate with any connection you enabled on your application in the Auth0 dashboard. Here, you can pass the scheme value that was used in the auth0Scheme
manifest placeholder as part of the initial configuration.
After you call the WebAuthProvider#start
function, the browser launches and shows the login page. Once the user authenticates, the callback URL is called. The callback URL contains the final result of the authentication process.
Add a button to your application that calls loginWithBrowser
. When you click it, verify that your Android application redirects you to the Auth0 Universal Login page and that you can now log in or sign up using a username and password or a social provider.
Once that's complete, verify that Auth0 redirects back to your app.
If your application did not launch successfully:
Ensure you set the Allowed Callback URLs are correct
Verify you saved your changes after entering your URLs
Make sure the domain and cliend ID values imported correctly
Still having issues? Check out our documentation or visit our community page to get more help.
Use the AuthenticationAPIClient
class to retrieve the user's profile from Auth0. This requires:
The access token returned from the login phase
The WebAuthProvider.login
must contain the profile
scope
You must specify the email
scope if you need to retrieve the user's email address.
This quickstart sets the openid profile email
scopes by default during the login step above.
The following demonstrates a function that can be used to retrieve the user's profile and show it on the screen:
Call the showUserProfile
function after login. Verify the onSuccess
callback returns the user's profile information.
If your application did not return user profile information:
Verify the accessToken
is valid
Still having issues? Check out our documentation or visit our community page to get more help.
This tutorial demonstrates how to call your API from an input-constrained device using the Device Authorization Flow. We recommend that you log in to follow this quickstart with examples configured for your account.
For an interactive experience, you can use the Device Flow Playground.
Ensure the OIDC Conformant toggle is enabled. For more information, read OIDC-Conformant Authentication.
Add Device Code to the Application's grant types. For more information, read Update Grant Types.
Add Refresh Token to the Application’s grant types if you want to enable Refresh Tokens.
Configure and enable at least one connection for the application.
Enable Allow Offline Access if you are using refresh tokens. For more information, read API Settings.
Configure Device User Code Settings to define the character set, format, and length of your randomly-generated user code.
When the user starts the device application and wants to authorize it, your application must request a device code from the Auth0 Authentication API to associate with the user session.
To get the device code, your application must call the Authentication API Device Authorization Flow Authorize endpoint:
+ +curl --request post \
+
+ --url 'https://${account.namespace}/oauth/device/code' \
+
+ --header 'content-type: application/x-www-form-urlencoded'
var client = new RestClient("https://${account.namespace}/oauth/device/code");
+
+var request = new RestRequest(Method.POST);
+
+request.AddHeader("content-type", "application/x-www-form-urlencoded");
+
+IRestResponse response = client.Execute(request);
package main
+
+
+
+import (
+
+ "fmt"
+
+ "net/http"
+
+ "io/ioutil"
+
+)
+
+
+
+func main() {
+
+
+
+ url := "https://${account.namespace}/oauth/device/code"
+
+
+
+ req, _ := http.NewRequest("post", url, nil)
+
+
+
+ req.Header.Add("content-type", "application/x-www-form-urlencoded")
+
+
+
+ res, _ := http.DefaultClient.Do(req)
+
+
+
+ defer res.Body.Close()
+
+ body, _ := ioutil.ReadAll(res.Body)
+
+
+
+ fmt.Println(res)
+
+ fmt.Println(string(body))
+
+
+
+}
HttpResponse<String> response = Unirest.post("https://${account.namespace}/oauth/device/code")
+
+ .header("content-type", "application/x-www-form-urlencoded")
+
+ .asString();
var axios = require("axios").default;
+
+
+
+var options = {
+
+ method: 'post',
+
+ url: 'https://${account.namespace}/oauth/device/code',
+
+ headers: {'content-type': 'application/x-www-form-urlencoded'}
+
+};
+
+
+
+axios.request(options).then(function (response) {
+
+ console.log(response.data);
+
+}).catch(function (error) {
+
+ console.error(error);
+
+});
#import <Foundation/Foundation.h>
+
+
+
+NSDictionary *headers = @{ @"content-type": @"application/x-www-form-urlencoded" };
+
+
+
+NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://${account.namespace}/oauth/device/code"]
+
+ cachePolicy:NSURLRequestUseProtocolCachePolicy
+
+ timeoutInterval:10.0];
+
+[request setHTTPMethod:@"post"];
+
+[request setAllHTTPHeaderFields:headers];
+
+
+
+NSURLSession *session = [NSURLSession sharedSession];
+
+NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
+
+ completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
+
+ if (error) {
+
+ NSLog(@"%@", error);
+
+ } else {
+
+ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
+
+ NSLog(@"%@", httpResponse);
+
+ }
+
+ }];
+
+[dataTask resume];
$curl = curl_init();
+
+
+
+curl_setopt_array($curl, [
+
+ CURLOPT_URL => "https://${account.namespace}/oauth/device/code",
+
+ CURLOPT_RETURNTRANSFER => true,
+
+ CURLOPT_ENCODING => "",
+
+ CURLOPT_MAXREDIRS => 10,
+
+ CURLOPT_TIMEOUT => 30,
+
+ CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+
+ CURLOPT_CUSTOMREQUEST => "post",
+
+ CURLOPT_HTTPHEADER => [
+
+ "content-type: application/x-www-form-urlencoded"
+
+ ],
+
+]);
+
+
+
+$response = curl_exec($curl);
+
+$err = curl_error($curl);
+
+
+
+curl_close($curl);
+
+
+
+if ($err) {
+
+ echo "cURL Error #:" . $err;
+
+} else {
+
+ echo $response;
+
+}
import http.client
+
+
+
+conn = http.client.HTTPSConnection("")
+
+
+
+headers = { 'content-type': "application/x-www-form-urlencoded" }
+
+
+
+conn.request("post", "/${account.namespace}/oauth/device/code", headers=headers)
+
+
+
+res = conn.getresponse()
+
+data = res.read()
+
+
+
+print(data.decode("utf-8"))
require 'uri'
+
+require 'net/http'
+
+require 'openssl'
+
+
+
+url = URI("https://${account.namespace}/oauth/device/code")
+
+
+
+http = Net::HTTP.new(url.host, url.port)
+
+http.use_ssl = true
+
+http.verify_mode = OpenSSL::SSL::VERIFY_NONE
+
+
+
+request = Net::HTTP::Post.new(url)
+
+request["content-type"] = 'application/x-www-form-urlencoded'
+
+
+
+response = http.request(request)
+
+puts response.read_body
import Foundation
+
+
+
+let headers = ["content-type": "application/x-www-form-urlencoded"]
+
+
+
+let request = NSMutableURLRequest(url: NSURL(string: "https://${account.namespace}/oauth/device/code")! as URL,
+
+ cachePolicy: .useProtocolCachePolicy,
+
+ timeoutInterval: 10.0)
+
+request.httpMethod = "post"
+
+request.allHTTPHeaderFields = headers
+
+
+
+let session = URLSession.shared
+
+let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
+
+ if (error != nil) {
+
+ print(error)
+
+ } else {
+
+ let httpResponse = response as? HTTPURLResponse
+
+ print(httpResponse)
+
+ }
+
+})
+
+
+
+dataTask.resume()
The device application should receive an HTTP 200 response and a payload similar to this:
{
+
+ "device_code": "GmRh...k9eS",
+
+ "user_code": "WDJB-MJHT",
+
+ "verification_uri": "https://my-tenant.auth0.com/device",
+
+ "verification_uri_complete": "https://my-tenant.auth0.com/device?user_code=WDJB-MJHT",
+
+ "expires_in": 900,
+
+ "interval": 5
+
+}
+
+
+
+
+
+## Request device activation
+
+
+After your device application receives the device_code
and the user_code
, it should instruct the user to go to the verification_uri
and enter the user_code
.
The device_code
is not intended for the user directly and should not be displayed during the interaction to avoid confusing the user.
When building a CLI, you could skip this step and immediately open the browser with verification_uri_complete
.
While your device application waits for the user to activate it, it should call the Authentication API POST /oauth/token endpoint intermittently and handle the response appropriately.
Ensure your device application waits for the length of the interval
(in seconds) or until it receives a successful response, whichever is longer, to avoid network latency issues.
curl --request POST \
+
+--url 'https://${account.namespace}/oauth/token' \
+
+--header 'content-type: application/x-www-form-urlencoded' \
+
+--data grant_type=urn:ietf:params:oauth:grant-type:device_code \
+
+--data device_code=__AUTH0_SCOPES__ \
+
+--data 'client_id=${account.clientId}'
+
+
+
+
+
+## User authorization
+
+
+The user will either scan the QR code, or else will open the activation page and enter the user code:
A confirmation page will be shown to have the user confirm that this is the right device:
The user will complete the transaction by signing in. This step may include one or more of the following processes:
Authenticating the user
Redirecting the user to an Identity Provider to handle authentication
Checking for active SSO sessions
Obtaining user consent for the device, unless consent has been previously given
Upon successful authentication and consent, the confirmation prompt will be shown:
At this point, the user has authenticated and the device has been authorized.
+ +## Receive tokens + + +After the user authorizes the device application, it receives an HTTP 200 response and the following payload:
{
+
+ "access_token": "eyJz93a...k4laUWw",
+
+ "refresh_token": "GEbRxBN...edjnXbL",
+
+ "id_token": "eyJ0XAi...4faeEoQ",
+
+ "token_type": "Bearer",
+
+ "expires_in": 86400
+
+}
+
+
+
+You should validate your tokens before saving them. To learn how, read Validate Access Tokens and Validate ID Tokens.
Access tokens are used to call the Authentication API Get User Info endpoint (if your device application requested the openid
scope) or the API that was specified by the audience
parameter. If you are calling your own API, your device application must verify the access token before using it.
ID tokens contain user information that must be decoded and extracted. The Authentication API only returns an id_token
if your device application requested the openid
scope.
Refresh tokens are used to obtain a new access token or ID token after the previous one has expired. The Authentication API only returns a refresh_token
if the Allow Offline Access setting is enabled for the API specified by the audience
parameter, and your device application requested the offline_access
scope.
To call your API, your device application must pass the access token as a Bearer token in the Authorization
header of your HTTP request.
curl --request GET \
+
+ --url https://myapi.com/api \
+
+ --header 'authorization: Bearer __AUTH0_API_ACCESS_TOKEN__' \
+
+ --header 'content-type: application/json'
+
+
+
+
+
+## Refresh tokens
+
+
+To get a new access token for a user, your device application can call the Authentication API POST /oauth/token endpoint with the refresh_token
parameter.
curl --request POST \
+
+ --url 'https://${account.namespace}/oauth/token' \
+
+ --header 'content-type: application/x-www-form-urlencoded' \
+
+ --data grant_type=refresh_token \
+
+ --data 'client_id=${account.clientId}' \
+
+ --data 'client_secret=${account.clientSecret}' \
+
+ --data refresh_token=__AUTH0_REFRESH_TOKEN__
+
+
+
+If the request was successful, your device application receives an HTTP 200 response with the following payload:
{
+
+ "access_token": "eyJ...MoQ",
+
+ "expires_in": 86400,
+
+ "scope": "openid offline_access",
+
+ "id_token": "eyJ...0NE",
+
+ "token_type": "Bearer"
+
+}
+
+
+
+To learn more about refresh tokens, read Refresh Tokens.
+ +## Troubleshooting + + +Tenant logs are created for any interaction that takes place and can be used to troubleshoot issues.
**Code** | + +**Name** | + +**Description** | + +
---|---|---|
fdeaz |
+
+Failed device authorization request | + ++ + |
fdeac |
+
+Failed device activation | + ++ + |
fdecc |
+
+User canceled the device confirmation | + ++ + |
fede |
+
+Failed Exchange | + +Device Code for Access Token | + +
sede |
+
+Success Exchange | + +Device Code for Access Token | + +
While you wait for the user to authorize the device, you may receive a few different HTTP 4xx responses.
You will see this error while waiting for the user to take action. Continue polling using the suggested interval
retrieved in the previous step of this tutorial.
`HTTP 403`
+
+
+
+{
+
+ "error": "authorization_pending",
+
+ "error_description": "..."
+
+}
+
+
+
+You are polling too fast. Slow down and use the suggested interval retrieved in the previous step of this tutorial. To avoid receiving this error due to network latency, you should start counting each interval after receipt of the last polling request's response.
`HTTP 429`
+
+
+
+{
+
+ "error": "slow_down",
+
+ "error_description": "..."
+
+}
+
+
+
+The user has not authorized the device quickly enough, so the device_code
has expired. Your application should notify the user that the flow has expired and prompt them to reinitiate the flow.
The expired_token
error is returned exactly once. After that, the endpoint returns the invalid_grant
error.
`HTTP 403`
+
+
+
+{
+
+ "error": "expired_token",
+
+ "error_description": "..."
+
+}
+
+
+
+If access is denied, you receive:
`HTTP 403`
+
+
+
+{
+
+ "error": "access_denied",
+
+ "error_description": "..."
+
+}
+
+
+
+This can occur for a variety of reasons, including:
The user refused to authorize the device.
The authorization server denied the transaction.
A configured Action denied access.
Refer to the samples below to learn how to implement this flow in real-world applications.
AppleTV (Swift): Simple application that shows how Auth0 can be used with the Device Authorization Flow from an AppleTV.
CLI (Node.js): Sample implementation of a CLI that uses the Device Authorization Flow instead of the Authorization Code Flow. The major difference is that your CLI does not need to host a webserver and listen on a port.
To use the Device Authorization Flow, a device application must:
Support Server Name Indication (SNI)
Be a Native Application
Have the Authentication Method set to None
Not be created through Dynamic Client Registration
In addition, the Device Authorization Flow does not allow:
Social Connections using Auth0 developer keys unless you are using New Universal Login Experience
Query string parameters to be accessed from a hosted login page or Actions.
Auth0 allows you to quickly add authentication and access user profile information in your app. This guide demonstrates how to integrate Auth0 with a Flutter app using the Auth0 Flutter SDK.
The Flutter SDK currently only supports Flutter apps for Android, iOS, and macOS.
This quickstart assumes you already have a Flutter app up and running. If not, check out the Flutter "getting started" guides to get started with a simple app.
You should also be familiar with the Flutter command line tool.
New to Auth? Learn How Auth0 works, how it integrates with Single-Page Applications and which protocol it uses.
To use Auth0 services, you need to have an application set up in the Auth0 Dashboard. The Auth0 application is where you will configure how you want authentication to work for your project.
Use the interactive selector to create a new Auth0 application or select an existing Native Auth0 application. Every application in Auth0 is assigned an alphanumeric, unique client ID that your application code will use to call Auth0 APIs through the SDK.
Any settings you configure using this quickstart will automatically update for your application in the Dashboard, which is where you can manage your applications in the future.
If you would rather explore a complete configuration, you can view a sample app instead.
The callback and logout URLs are the URLs that Auth0 invokes to redirect back to your app. Auth0 invokes the callback URL after authenticating the user, and the logout URL after removing the session cookie. If the callback and logout URLs are not set, users will be unable to log in and out of the app and will get an error.
Set the callback and logout URLs to the following values, depending on your platform.
On Android, the value of the SCHEME
placeholder can be https
or some other custom scheme. https
schemes require enabling Android App Links.
On iOS 17.4+ and macOS 14.4+ it is possible to use Universal Links (https
scheme) as callback and logout URLs. When enabled, the SDK will fall back to using a custom URL scheme on older iOS / macOS versions –your app's bundle identifier. This feature requires Xcode 15.3+ and a paid Apple Developer account.
SCHEME://${account.namespace}/android/YOUR_PACKAGE_NAME/callback
https://${account.namespace}/ios/YOUR_BUNDLE_IDENTIFIER/callback,
-Add the Auth0 Flutter SDK into the project:
+YOUR_BUNDLE_IDENTIFIER://${account.namespace}/ios/YOUR_BUNDLE_IDENTIFIER/callback
https://${account.namespace}/macos/YOUR_BUNDLE_IDENTIFIER/callback,
-```shell
-flutter pub add auth0_flutter
-```
+YOUR_BUNDLE_IDENTIFIER://${account.namespace}/macos/YOUR_BUNDLE_IDENTIFIER/callback
For example, if your iOS bundle identifier were com.example.MyApp
and your Auth0 domain were example.us.auth0.com
, then this value would be:
https://example.us.auth0.com/ios/com.example.MyApp/callback,
-## Configure Android {{{ data-action=code data-code="app/build.gradle#11" }}}
+com.example.MyApp://example.us.auth0.com/ios/com.example.MyApp/callback
Add the Auth0 Flutter SDK into the project:
flutter pub add auth0_flutter
If you are not developing for the Android platform, skip this step.
The SDK requires manifest placeholders. Auth0 uses placeholders internally to define an intent-filter
, which captures the authentication callback URL. You must set the Auth0 tenant domain and the callback URL scheme.
The sample uses the following placeholders:
auth0Domain
: The domain of your Auth0 tenant. Generally, you find this in the Auth0 Dashboard under your Application Settings in the Domain field. If you are using a custom domain, you should set this to the value of your custom domain instead.
auth0Scheme
: The scheme to use. Can be a custom scheme, or https if you want to use Android App Links. You can read more about setting this value in the Auth0.Android SDK README.
You do not need to declare a specific intent-filter
for your activity because you defined the manifest placeholders with your Auth0 Domain and Scheme values. The library handles the redirection for you.
Run Sync Project with Gradle Files inside Android Studio to apply your changes.
## Configure iOS/macOS @@ -97,75 +73,33 @@ For the associated domain to work, your app must be signed with your team certif ## Add login to your application {{{ data-action="code" data-code="main_view.dart#29:40" }}} -Universal Login is the easiest way to set up authentication in your app. We recommend using it for the best experience, best security, and the fullest array of features. -Integrate Auth0 Universal Login in your Flutter app by using the `Auth0` class. Redirect your users to the Auth0 Universal Login page using `webAuthentication().login()`. This is a `Future` and must be awaited for you to retrieve the user's tokens. +Universal Login is the easiest way to set up authentication in your app. We recommend using it for the best experience, best security, and the fullest array of features.
Integrate Auth0 Universal Login in your Flutter app by using the Auth0
class. Redirect your users to the Auth0 Universal Login page using webAuthentication().login()
. This is a Future
and must be awaited for you to retrieve the user's tokens.
Android: if you are using a custom scheme, pass this scheme to the login method so that the SDK can route to the login page and back again correctly:
await auth0.webAuthentication(scheme: 'YOUR CUSTOM SCHEME').login();
When a user logs in, they are redirected back to your app. Then, you are able to access the ID and access tokens for this user.
Add a button to your app that calls webAuthentication().login()
and logs the user into your app. Verify that you are redirected to Auth0 for authentication and then back to your app.
Verify that you can get access to the tokens on the result of calling login
.
If your app did not launch successfully:
Ensure you set the Allowed Callback URLs are correct
Verify you saved your changes after entering your URLs
Make sure the domain and client ID values are imported correctly
If using Android, ensure that the manifest placeholders have been set up correctly, otherwise the redirect back to your app may not work
Still having issues? Check out our documentation or visit our community page to get more help.
To log users out, redirect them to the Auth0 logout endpoint to clear their login session by calling the Auth0 Flutter SDK webAuthentication().logout()
. Read more about logging out of Auth0.
Android: if you are using a custom scheme, pass this scheme to the logout method so that the SDK can route back to your app correctly:
await auth0.webAuthentication(scheme: 'YOUR CUSTOM SCHEME').logout();
Add a button to your app that calls webAuthentication().logout()
and logs the user out of your app. When you select it, verify that your Flutter app redirects you to the logout endpoint and back again. You should not be logged in to your app.
If your app did not log out successfully:
Ensure the Allowed Logout URLs are set properly
Verify you saved your changes after entering your URLs
Still having issues? Check out our documentation or visit our community page to get more help.
The user profile automatically retrieves user profile properties for you when you call webAuthentication().login()
. The returned object from the login step contains a user
property with all the user profile properties, which populates by decoding the ID token.
Log in and inspect the user
property on the result. Verify the current user's profile information, such as email
or name
.
If your app did not return user profile information:
Verify the access token is valid
Still having issues? Check out our documentation or visit our community page to get more help.
Auth0 allows you to quickly add authentication and access user profile information in your application. This guide demonstrates how to integrate Auth0 with an Ionic (Angular) & Capacitor application using the Auth0 Angular SDK.
+ +## Getting started + + +This quickstart assumes you already have an Ionic application up and running with Capacitor. If not, check out the Using Capacitor with Ionic Framework guide to get started with a simple app, or clone our sample apps.
You should also be familiar with the Capacitor development workflow.
-<%= include('../_includes/ionic/_configure_urls_interactive') %> +## Configure Auth0 -<%= include('../../_includes/_auth0-angular-install.md') %> -<%= include('../_includes/ionic/_install_plugins') %> +To use Auth0 services, you need to have an application set up in the Auth0 Dashboard. The Auth0 application is where you will configure how you want authentication to work for your project.
Throughout this article, YOUR_PACKAGE_ID
is your application's package ID. This can be found and configured in the appId
field in your capacitor.config.ts
file. See Capacitor's Config schema for more info.
Use the interactive selector to create a new Auth0 application or select an existing application that represents the project you want to integrate with. Every application in Auth0 is assigned an alphanumeric, unique client ID that your application code will use to call Auth0 APIs through the SDK.
Any settings you configure using this quickstart will automatically update for your application in the Dashboard, which is where you can manage your applications in the future.
If you would rather explore a complete configuration, you can view a sample application instead.
A callback URL is a URL in your application that you would like Auth0 to redirect users to after they have authenticated. If not set, users will not be returned to your application after they log in.
If you are following along with our sample project, set this to:
YOUR_PACKAGE_ID://{yourDomain}/capacitor/YOUR_PACKAGE_ID/callback
A logout URL is a URL in your application that you would like Auth0 to redirect users to after they have logged out. If not set, users will not be able to log out from your application and will receive an error.
If you are following along with our sample project, set this to:
YOUR_PACKAGE_ID://{yourDomain}/capacitor/YOUR_PACKAGE_ID/callback
To be able to make requests from your native application to Auth0, set the following Allowed Origins in your Application Settings.
If you are following along with our sample project, set this to capacitor://localhost, http://localhost
for iOS and Android respectively.
Lastly, be sure that the Application Type for your application is set to Native in the Application Settings.
-## Register and configure the authentication module {{{ data-action=code data-code="app.module.ts" }}} +## Install the Auth0 Angular SDK + + +Run the following command within your project directory to install the Auth0 Angular SDK:
npm install @auth0/auth0-angular
The SDK exposes several types that help you integrate Auth0 with your Angular application idiomatically, including a module and an authentication service.
This quickstart and sample make use of some of Capacitor's official plugins. Install these into your app using the following command:
npm install @capacitor/browser @capacitor/app
@capacitor/browser
: Allows you to interact with the device's system browser and is used to open the URL to Auth0's authorization endpoint.
@capacitor/app
: Allows you to subscribe to high-level app events, useful for handling callbacks from Auth0.
Capacitor's Browser plugin on iOS uses SFSafariViewController
, which on iOS 11+ does not share cookies with Safari on the device. This means that SSO will not work on those devices. If you need SSO, please instead use a compatible plugin that uses ASWebAuthenticationSession.
In a Capacitor application, the Capacitor's Browser plugin performs a redirect to the Auth0 Universal Login Page. Set the openUrl
parameter on the loginWithRedirect
function to use Browser.open
so that the URL is opened using the device's system browser component (SFSafariViewController on iOS, and Chrome Custom Tabs on Android).
By default, the SDK's loginWithRedirect
method uses window.location.href
to navigate to the login page in the default browser application on the user's device rather than the system browser component appropriate for the platform. The user would leave your application to authenticate and could make for a suboptimal user experience.
The loginWithRedirect
function tells the SDK to initiate the login flow, using the Browser.open
function to open the login URL with the platform's system browser component by setting the openUrl
parameter. This provides a way for your user to log in to your application. Users redirect to the login page at Auth0 and do not receive any errors.
Sorry about that. Here's a couple things to double check:
ensure that there are no errors in the browser's console window at the point of login
ensure the domain and Client ID are correct according to your Auth0 application in the Dashboard
if you are redirected to Auth0 and receive an error page, check the "technical details" section at the bottom for the reason for the failure
Once users logs in with the Universal Login Page, they redirect back to your app via a URL with a custom URL scheme. The appUrlOpen
event must be handled within your app. You can call the handleRedirectCallback
method from the Auth0 SDK to initialize the authentication state.
You can only use this method on a redirect from Auth0. To verify success, check for the presence of the code
and state
parameters in the URL.
The Browser.close()
method should close the browser when this event is raised.
Note that the appUrlOpen
event callback is wrapped in ngZone.run
. Changes to observables that occur when handleRedirectCallback
runs are picked up by the Angular app. To learn more, read Using Angular with Capacitor. Otherwise, the screen doesn't update to show the authenticated state after log in.
This article assumes you will be using Custom URL Schemes to handle the callback within your application. To do this, register your YOUR_PACKAGE_ID
as a URL scheme for your chosen platform. To learn more, read Defining a Custom URL Scheme for iOS, or Create Deep Links to App Content for Android.
Add the appUrlOpen
to your application's App
component and log in. The browser window should close once the user authenticates and logs in to your app.
Sorry about that. Here's a couple things to double check:
check that the custom URL scheme is registered for your chosen platform. On iOS, define a custom URL scheme, or add an intent filter with your custom scheme for Android
if the event fires but you receive an error, check the logs in your Auth0 Dashboard for the error code
Now that users can log in, you need to configure a way to log out. Users must redirect to the Auth0 logout endpoint in the browser to clear their browser session. Again, Capacitor's Browser plugin should perform this redirect so that the user does not leave your app and receive a suboptimal experience.
To achieve this with Ionic and Capacitor in conjunction with the Auth0 SDK:
Construct the URL for your app Auth0 should use to redirect to after logout. This is a URL that uses your registered custom scheme and Auth0 domain. Add it to your Allowed Logout URLs configuration in the Auth0 Dashboard
Logout from the SDK by calling logout
, and pass your redirect URL back as the logoutParams.returnTo
parameter.
Set the openUrl
parameter to a callback that uses the Capacitor browser plugin to open the URL using Browser.open
.
Similar to the login step, if you do not set openUrl
when calling logout
, the SDK redirects the user to the logout URL using the default browser application on the device, which provides a suboptimal user experience.
Provide a way for your users to log out of your application. Verify the redirect to Auth0 and then to the address you specified in the returnTo
parameter. Make sure users are no longer logged in to your application.
Sorry about that. Here's a couple things to double check:
check that the URL you provided to in the returnTo
parameter is registered as an allowed callback URL in your Auth0 Dashboard
The Auth0 SDK retrieves the profile information associated with logged-in users in whatever component you need, such as their name or profile picture, to personalize the user interface. The profile information is available through the user$
property exposed by AuthService
.
Provide a way for your users to see their user profile details within the app and verify you are able to retrieve and see your profile information on screen once you have logged in.
Sorry about that. Here's a couple things to double check:
check that you are only reading the user's profile when isLoading
is false
check that user
resolves to an object and is not undefined
Auth0 allows you to quickly add authentication and gain access to user profile information in your application. This guide demonstrates how to integrate Auth0 with an Ionic (React) & Capacitor application using the Auth0 React SDK.
+ +## Getting started + + +This quickstart assumes you already have an Ionic application up and running with Capacitor. If not, check out the Using Capacitor with Ionic Framework guide to get started with a simple app, or clone our sample apps.
You should also be familiar with the Capacitor development workflow.
+ +## Configure Auth0 -<%= include('../_includes/ionic/_configure_urls_interactive') %> -<%= include('../../_includes/_auth0-react-install.md') %> +To use Auth0 services, you need to have an application set up in the Auth0 Dashboard. The Auth0 application is where you will configure how you want authentication to work for your project.
Throughout this article, YOUR_PACKAGE_ID
is your application's package ID. This can be found and configured in the appId
field in your capacitor.config.ts
file. See Capacitor's Config schema for more info.
Use the interactive selector to create a new Auth0 application or select an existing application that represents the project you want to integrate with. Every application in Auth0 is assigned an alphanumeric, unique client ID that your application code will use to call Auth0 APIs through the SDK.
Any settings you configure using this quickstart will automatically update for your application in the Dashboard, which is where you can manage your applications in the future.
If you would rather explore a complete configuration, you can view a sample application instead.
A callback URL is a URL in your application that you would like Auth0 to redirect users to after they have authenticated. If not set, users will not be returned to your application after they log in.
If you are following along with our sample project, set this to:
YOUR_PACKAGE_ID://{yourTenant}.auth0.com/capacitor/YOUR_PACKAGE_ID/callback
A logout URL is a URL in your application that you would like Auth0 to redirect users to after they have logged out. If not set, users will not be able to log out from your application and will receive an error.
If you are following along with our sample project, set this to:
YOUR_PACKAGE_ID://{yourTenant}.auth0.com/capacitor/YOUR_PACKAGE_ID/callback
.
To be able to make requests from your native application to Auth0, set the following Allowed Origins in your Application Settings.
If you are following along with our sample project, set this to capacitor://localhost, http://localhost
for iOS and Android respectively.
Lastly, be sure that the Application Type for your application is set to Native in the Application Settings.
-<%= include('../_includes/ionic/_install_plugins') %> +## Install the Auth0 React SDK -## Configure the `Auth0Provider` component {{{ data-action=code data-code="index.tsx" }}} + +Run the following command within your project directory to install the Auth0 React SDK:
npm install @auth0/auth0-react
The SDK exposes methods and variables that help you integrate Auth0 with your React application idiomatically using React Hooks or Higher-Order Components.
This quickstart and sample make use of some of Capacitor's official plugins. Install these into your app using the following command:
npm install @capacitor/browser @capacitor/app
@capacitor/browser
: Allows you to interact with the device's system browser and is used to open the URL to Auth0's authorization endpoint.
@capacitor/app
: Allows you to subscribe to high-level app events, useful for handling callbacks from Auth0.
Capacitor's Browser plugin on iOS uses SFSafariViewController
, which on iOS 11+ does not share cookies with Safari on the device. This means that SSO will not work on those devices. If you need SSO, please instead use a compatible plugin that uses ASWebAuthenticationSession.
In a Capacitor application, the Capacitor's Browser plugin performs a redirect to the Auth0 Universal Login Page. Set the openUrl
parameter on the loginWithRedirect
function to use Browser.open
so that the URL is opened using the device's system browser component (SFSafariViewController on iOS, and Chrome Custom Tabs on Android).
By default, the SDK's loginWithRedirect
method uses window.location.href
to navigate to the login page in the default browser application on the user's device rather than the system browser component appropriate for the platform. The user would leave your application to authenticate and could make for a suboptimal user experience.
The loginWithRedirect
function tells the SDK to initiate the login flow, using the Browser.open
function to open the login URL with the platform's system browser component by setting the openUrl
parameter. This provides a way for your user to log in to your application. Users redirect to the login page at Auth0 and do not receive any errors.
Sorry about that. Here's a couple things to double check:
ensure that there are no errors in the browser's console window at the point of login
ensure the domain and Client ID are correct according to your Auth0 application in the dashboard
if you are redirected to Auth0 and receive an error page, check the "technical details" section at the bottom for the reason for the failure
Once users logs in with the Universal Login Page, they redirect back to your app via a URL with a custom URL scheme. The appUrlOpen
event must be handled within your app. You can call the handleRedirectCallback
method from the Auth0 SDK to initialize the authentication state.
You can only use this method on a redirect from Auth0. To verify success, check for the presence of the code
and state
parameters in the URL.
The Browser.close()
method should close the browser when this event is raised.
This article assumes you will be using Custom URL Schemes to handle the callback within your application. To do this, register your YOUR_PACKAGE_ID
as a URL scheme for your chosen platform. To learn more, read Defining a Custom URL Scheme for iOS, or Create Deep Links to App Content for Android.
Add the appUrlOpen
to your application's App
component and log in. The browser window should close once the user authenticates and logs in to your app.
Sorry about that. Here's a couple things to double check:
check that the custom URL scheme is registered for your chosen platform. On iOS, define a custom URL scheme, or add an intent filter with your custom scheme on Android
if the event fires but you receive an error, check the logs in your Auth0 Dashboard for the reason for the error
Now that users can log in, you need to configure a way to log out. Users must redirect to the Auth0 logout endpoint in the browser to clear their browser session. Again, Capacitor's Browser plugin should perform this redirect so that the user does not leave your app and receive a suboptimal experience.
To achieve this with Ionic and Capacitor in conjunction with the Auth0 SDK:
Construct the URL for your app Auth0 should use to redirect to after logout. This is a URL that uses your registered custom scheme and Auth0 domain. Add it to your Allowed Logout URLs configuration in the Auth0 Dashboard
Logout from the SDK by calling logout
, and pass your redirect URL back as the logoutParams.returnTo
parameter.
Set the openUrl
parameter to a callback that uses the Capacitor browser plugin to open the URL using Browser.open
.
Similar to the login step, if you do not set openUrl
when calling logout
, the SDK redirects the user to the logout URL using the default browser application on the device, which provides a suboptimal user experience.
Provide a way for your users to log out of your application. Verify that you redirect to Auth0 and then to the address you specified in the returnTo
parameter. Check that you are no longer logged in to your application.
The Auth0 React SDK retrieves the user's profile associated with logged-in users in whatever component you need, such as their name or profile picture, to personalize the user interface. The profile information is available through the user
property exposed by the useAuth0()
hook.
Initializing the SDK is asynchronous, and you should guard the user profile by checking the isLoading
and user
properties. Once isLoading
is false
and user
has a value, the user profile can be used.
Provide a way for your users to see their user profile details within the app and verify you are able to retrieve and see your profile information on screen once you have logged in.
Sorry about that. Here's a couple things to double check:
check that you are only reading the user's profile when isLoading
is false
check that user
resolves to an object and is not undefined
{{ user.email }}
+Auth0 allows you to quickly add authentication and gain access to user profile information in your application. This guide demonstrates how to integrate Auth0 with an Ionic (Vue) & Capacitor application using the Auth0 Vue SDK.
+ +## Getting started + + +This quickstart assumes you already have an Ionic application up and running with Capacitor. If not, check out the Using Capacitor with Ionic Framework guide to get started with a simple app, or clone our sample apps.
You should also be familiar with the Capacitor development workflow.
+ +## Configure Auth0 -<%= include('../_includes/ionic/_configure_urls_interactive') %> -<%= include('../../_includes/_auth0-vue-install.md') %> +To use Auth0 services, you need to have an application set up in the Auth0 Dashboard. The Auth0 application is where you will configure how you want authentication to work for your project.
Throughout this article, YOUR_PACKAGE_ID
is your application's package ID. This can be found and configured in the appId
field in your capacitor.config.ts
file. See Capacitor's Config schema for more info.
Use the interactive selector to create a new Auth0 application or select an existing application that represents the project you want to integrate with. Every application in Auth0 is assigned an alphanumeric, unique client ID that your application code will use to call Auth0 APIs through the SDK.
Any settings you configure using this quickstart will automatically update for your application in the Dashboard, which is where you can manage your applications in the future.
If you would rather explore a complete configuration, you can view a sample application instead.
A callback URL is a URL in your application that you would like Auth0 to redirect users to after they have authenticated. If not set, users will not be returned to your application after they log in
If you are following along with our sample project, set this to YOUR_PACKAGE_ID://{yourDomain}/capacitor/YOUR_PACKAGE_ID/callback
A logout URL is a URL in your application that you would like Auth0 to redirect users to after they have logged out. If not set, users will not be able to log out from your application and will receive an error.
If you are following along with our sample project, set this to YOUR_PACKAGE_ID://{yourDomain}/capacitor/YOUR_PACKAGE_ID/callback
.
To be able to make requests from your native application to Auth0, set the following Allowed Origins in your Application Settings.
If you are following along with our sample project, set this to capacitor://localhost, http://localhost
for iOS and Android respectively.
Lastly, be sure that the Application Type for your application is set to Native in the Application Settings.
-<%= include('../_includes/ionic/_install_plugins') %> +## Install the Auth0 Vue SDK -## Configure the `createAuth0` plugin {{{ data-action=code data-code="main.ts" }}} + +Run the following command within your project directory to install the Auth0 Vue SDK:
npm install @auth0/auth0-vue
The SDK exposes several types that help you integrate Auth0 with your Vue application idiomatically, including a module and an authentication service.
This quickstart and sample make use of some of Capacitor's official plugins. Install these into your app using the following command:
npm install @capacitor/browser @capacitor/app
@capacitor/browser
- allows you to interact with the device's system browser and is used to open the URL to Auth0's authorizaction endpoint
@capacitor/app
- allows you to subscribe to high-level app events, useful for handling callbacks from Auth0
Capacitor's Browser plugin on iOS uses SFSafariViewController
, which on iOS 11+ does not share cookies with Safari on the device. This means that SSO will not work on those devices. If you need SSO, please instead use a compatible plugin that uses ASWebAuthenticationSession.
In a Capacitor application, the Capacitor's Browser plugin performs a redirect to the Auth0 Universal Login Page. Set the openUrl
parameter on the loginWithRedirect
function to use Browser.open
so that the URL is opened using the device's system browser component (SFSafariViewController on iOS, and Chrome Custom Tabs on Android).
By default, the SDK's loginWithRedirect
method uses window.location.href
to navigate to the login page in the default browser application on the user's device rather than the system browser component appropriate for the platform. The user would leave your application to authenticate and could make for a suboptimal user experience.
The loginWithRedirect
function tells the SDK to initiate the login flow, using the Browser.open
function to open the login URL with the platform's system browser component by setting the openUrl
parameter. This provides a way for your user to log in to your application. Users redirect to the login page at Auth0 and do not receive any errors.
Sorry about that. Here's a couple things to double check:
ensure that there are no errors in the browser's console window at the point of login
ensure the domain and Client ID are correct according to your Auth0 application in the dashboard
if you are redirected to Auth0 and receive an error page, check the "technical details" section at the bottom for the reason for the failure
Once users logs in with the Universal Login Page, they redirect back to your app via a URL with a custom URL scheme. The appUrlOpen
event must be handled within your app. You can call the handleRedirectCallback
method from the Auth0 SDK to initialize the authentication state.
You can only use this method on a redirect from Auth0. To verify success, check for the presence of the code
and state
parameters in the URL.
The Browser.close()
method should close the browser when this event is raised.
This article assumes you will be using Custom URL Schemes to handle the callback within your application. To do this, register your YOUR_PACKAGE_ID
as a URL scheme for your chosen platform. To learn more, read Defining a Custom URL Scheme for iOS, or Create Deep Links to App Content for Android.
Add the appUrlOpen
to your application's App
component setup and log in. The browser window should close once the user authenticates and logs in to your app.
Sorry about that. Here's a couple things to double check:
check that the custom URL scheme is registered for your chosen platform. On iOS, define a custom URL scheme, or add an intent filter with your custom scheme on Android
if the event fires but you receive an error, check the logs in your Auth0 Dashboard for the reason for the error
Now that users can log in, you need to configure a way to log out. Users must redirect to the Auth0 logout endpoint in the browser to clear their browser session. Again, Capacitor's Browser plugin should perform this redirect so that the user does not leave your app and receive a suboptimal experience.
To achieve this with Ionic and Capacitor in conjunction with the Auth0 SDK:
Construct the URL for your app Auth0 should use to redirect to after logout. This is a URL that uses your registered custom scheme and Auth0 domain. Add it to your Allowed Logout URLs configuration in the Auth0 Dashboard
Logout from the SDK by calling logout
, and pass your redirect URL back as the logoutParams.returnTo
parameter.
Set the openUrl
parameter to a callback that uses the Capacitor browser plugin to open the URL using Browser.open
.
Similar to the login step, if you do not set openUrl
when calling logout
, the SDK redirects the user to the logout URL using the default browser application on the device, which provides a suboptimal user experience.
Provide a way for your users to log out of your application. Verify that you redirect to Auth0 and then to the address you specified in the returnTo
parameter. Check that you are no longer logged in to your application.
Sorry about that. Here's a couple things to double check:
check that the URL you provided to in the returnTo
parameter is registered as an allowed callback URL in your Auth0 Dashboard
The Auth0 Vue SDK retrieves the user's profile associated with logged-in users in whatever component you need, such as their name or profile picture, to personalize the user interface. The profile information is available through the user
property exposed by the useAuth0()
composable.
Initializing the SDK is asynchronous, and you should guard the user profile by checking the isLoading
and user
properties. Once isLoading
is false
and user
has a value, the user profile can be used.
Provide a way for your users to see their user profile details within the app and verify you are able to retrieve and see your profile information on screen once you have logged in.
This guide demonstrates how to add authentication and access user profile information in any iOS / macOS app using the Auth0.swift SDK.
To use this quickstart, you need to:
Sign up for a free Auth0 account or log in to Auth0.
Have an existing iOS / macOS app that you want to integrate. Alternatively, you can view or download a sample app after logging in.
To use Auth0 services, you need an application set up in the Auth0 Dashboard. The Auth0 application is where you will configure how you want authentication to work for the app you are developing.
Use the interactive selector to create a new Auth0 application or select an existing Native Auth0 application. Auth0 assigns every application an alphanumeric, unique Client ID that your app uses to call Auth0 APIs through the SDK.
Any settings you configure using this quickstart automatically update your Auth0 application in the Dashboard, which is where you can manage your applications in the future.
If you would rather explore a complete configuration, you can view a sample app instead.
Auth0 invokes the callback and logout URLs to redirect users back to your app. Auth0 invokes the callback URL after authenticating the user and the logout URL after removing the session cookie. If you do not set the callback and login URLs, users will not be able to log in and out of the app, and your app will produce an error.
On iOS 17.4+ and macOS 14.4+ it is possible to use Universal Links as callback and logout URLs. When enabled, Auth0.swift will fall back to using a custom URL scheme on older iOS / macOS versions.
This feature requires Xcode 15.3+ and a paid Apple Developer account.
Add the following URLs to Callback URLs and Logout URLs, depending on the platform of your app. If you have a custom domain, use this instead of your Auth0 tenant’s domain.
https://${account.namespace}/ios/YOUR_BUNDLE_IDENTIFIER/callback,
-Use the interactive selector to create a new Auth0 application or select an existing **Native** Auth0 application. Auth0 assigns every application an alphanumeric, unique Client ID that your app uses to call Auth0 APIs through the SDK.
-
-Any settings you configure using this quickstart automatically update your Auth0 application in the Dashboard, which is where you can manage your applications in the future.
-
-If you would rather explore a complete configuration, you can view a sample app instead.
-
-### Configure callback and logout URLs
-
-Auth0 invokes the callback and logout URLs to redirect users back to your app. Auth0 invokes the callback URL after authenticating the user and the logout URL after removing the session cookie. If you do not set the callback and login URLs, users will not be able to log in and out of the app, and your app will produce an error.
-
-::: note
-On iOS 17.4+ and macOS 14.4+ it is possible to use Universal Links as callback and logout URLs. When enabled, Auth0.swift will fall back to using a custom URL scheme on older iOS / macOS versions.
-
-**This feature requires Xcode 15.3+ and a paid Apple Developer account**.
-:::
-
-Add the following URLs to **Callback URLs** and **Logout URLs**, depending on the platform of your app. If you have a custom domain, use this instead of your Auth0 tenant’s domain.
-
-#### iOS
-
-```text
-https://${account.namespace}/ios/YOUR_BUNDLE_IDENTIFIER/callback,
YOUR_BUNDLE_IDENTIFIER://${account.namespace}/ios/YOUR_BUNDLE_IDENTIFIER/callback
-```
-#### macOS
+
+
+https://${account.namespace}/macos/YOUR_BUNDLE_IDENTIFIER/callback,
-```text
-https://${account.namespace}/macos/YOUR_BUNDLE_IDENTIFIER/callback,
YOUR_BUNDLE_IDENTIFIER://${account.namespace}/macos/YOUR_BUNDLE_IDENTIFIER/callback
-```
-For example, if your iOS bundle identifier was `com.example.MyApp` and your Auth0 domain was `example.us.auth0.com`, then this value would be:
+
+
+For example, if your iOS bundle identifier was com.example.MyApp
and your Auth0 domain was example.us.auth0.com
, then this value would be:
https://example.us.auth0.com/ios/com.example.MyApp/callback,
-```text
-https://example.us.auth0.com/ios/com.example.MyApp/callback,
com.example.MyApp://example.us.auth0.com/ios/com.example.MyApp/callback
```
@@ -108,37 +71,27 @@ For the associated domain to work, your app must be signed with your team certif
## Install the SDK
-### Using the Swift Package Manager
-Open the following menu item in Xcode:
+Using the Swift Package Manager
Open the following menu item in Xcode:
File > Add Package Dependencies...
In the Search or Enter Package URL search box enter this URL:
https://github.com/auth0/Auth0.swift
-**File > Add Package Dependencies...**
+
-In the **Search or Enter Package URL** search box enter this URL:
+Then, select the dependency rule and press Add Package.
For further reference on SPM, check its official documentation.
Using Cocoapods
Add the following line to your Podfile
:
pod 'Auth0', '~> 2.0'
-```text
-https://github.com/auth0/Auth0.swift
-```
+
-Then, select the dependency rule and press **Add Package**.
+Then, run pod install
.
For further reference on Cocoapods, check their official documentation.
Using Carthage
Add the following line to your Cartfile
:
github "auth0/Auth0.swift" ~> 2.0
-::: note
-For further reference on SPM, check its official documentation.
-:::
+
-### Using Cocoapods
+Then, run carthage bootstrap --use-xcframeworks
.
For further reference on Carthage, check their official documentation.
-Add the following line to your `Podfile`:
+## Configure the SDK {{{ data-action="code" data-code="Auth0.plist" }}}
-```ruby
-pod 'Auth0', '~> 2.0'
-```
-Then, run `pod install`.
+The Auth0.swift SDK needs your Auth0 domain and Client ID. You can find these values in the settings page of your Auth0 application.
domain: The domain of your Auth0 tenant. If you have a custom domain, use this instead of your Auth0 tenant’s domain.
Client ID: The alphanumeric, unique ID of the Auth0 application you set up earlier in this quickstart.
Create a plist
file named Auth0.plist
in your app bundle containing the Auth0 domain and Client ID values.
You can also configure the SDK programmatically. Check the README to learn more.
iOS Swift Quickstart - Step 3 Checkpoint You configured the Auth0.swift SDK. Run your app to verify that it is not producing any errors related to the SDK.
-::: note
-For further reference on Cocoapods, check their official documentation.
-:::
+
### Using Carthage
@@ -182,75 +135,35 @@ Still having issues? Check out our Universal Login page in the action of your **Login** button.
+## Add login to your application {{{ data-action="code" data-code="MainView.swift#20:31" }}}
-::: note
-You can use async/await or Combine instead of the callback-based API. Check the README to learn more.
-:::
-
+Import the Auth0
module in the file where you want to present the login page. Then, present the Universal Login page in the action of your Login button.
You can use async/await or Combine instead of the callback-based API. Check the README to learn more.
iOS Swift Quickstart - Step 4 Checkpoint Press the Login button and verify that:
An alert box shows up asking for consent.
Choosing Continue opens the Universal Login page in a Safari modal.
You can log in or sign up using a username and password or a social provider.
The Safari modal closes automatically afterward.
-::::checkpoint
-:::checkpoint-default
-Press the **Login** button and verify that:
-- An alert box shows up asking for consent.
-- Choosing **Continue** opens the Universal Login page in a Safari modal.
-- You can log in or sign up using a username and password or a social provider.
-- The Safari modal closes automatically afterward.
-:::
+
-:::checkpoint-failure
-If login fails or produces errors:
-- Verify you entered the correct callback URL
-- Ensure you set the Auth0 domain and Client ID correctly
+ If login fails or produces errors:
Verify you entered the correct callback URL
Ensure you set the Auth0 domain and Client ID correctly
Still having issues? Check out our documentation or visit our community page to get more help.
-Still having issues? Check out our documentation or visit our community page to get more help.
-:::
-::::
+
-## Add logout to your application {{{ data-action=code data-code="MainView.swift#33:44" }}}
+## Add logout to your application {{{ data-action="code" data-code="MainView.swift#34:45" }}}
-Now that you can log in to your app, you need a way to log out. In the action of your **Logout** button, call the `clearSession()` method to clear the Universal Login session cookie.
-::::checkpoint
-:::checkpoint-default
-Press the **Logout** button and verify that:
-- An alert box shows up asking for consent.
-- Choosing **Continue** opens a page in a Safari modal.
-- The Safari modal closes automatically soon after.
-:::
+Now that you can log in to your app, you need a way to log out. In the action of your Logout button, call the clearSession()
method to clear the Universal Login session cookie.
iOS Swift Quickstart - Step 5 Checkpoint Press the Logout button and verify that:
An alert box shows up asking for consent.
Choosing Continue opens a page in a Safari modal.
The Safari modal closes automatically soon after.
-:::checkpoint-failure
-If logout fails or produces errors:
-- Verify you entered the correct callback URL
-- Ensure you set the Auth0 domain and Client ID correctly
+
-Still having issues? Check out our documentation or visit our community page to get more help.
-:::
-::::
+ If logout fails or produces errors:
Verify you entered the correct callback URL
Ensure you set the Auth0 domain and Client ID correctly
Still having issues? Check out our documentation or visit our community page to get more help.
-## Access user profile information {{{ data-action=code data-code="User.swift#11:14" }}}
+
-The `Credentials` instance you obtained after logging in includes an ID token. The ID token contains the profile information associated with the logged-in user, such as their email and profile picture. You can use these details to personalize the user interface of your app.
+## Access user profile information {{{ data-action="code" data-code="User.swift#11:14" }}}
-The Auth0.swift SDK includes a utility for decoding JWTs like the ID token. Start by importing the `JWTDecode` module in the file where you want to access the user profile information. Then, use the `decode(jwt:)` method to decode the ID token and access the claims it contains.
-::: note
-You can retrieve the latest user information with the `userInfo(withAccessToken:)` method. Check the EXAMPLES to learn more.
-:::
+The Credentials
instance you obtained after logging in includes an ID token. The ID token contains the profile information associated with the logged-in user, such as their email and profile picture. You can use these details to personalize the user interface of your app.
The Auth0.swift SDK includes a utility for decoding JWTs like the ID token. Start by importing the JWTDecode
module in the file where you want to access the user profile information. Then, use the decode(jwt:)
method to decode the ID token and access the claims it contains.
You can retrieve the latest user information with the userInfo(withAccessToken:)
method. Check the EXAMPLES to learn more.
iOS Swift Quickstart - Step 6 Checkpoint Verify that you can access the email
, picture
, or any other claim after you have logged in.
-::::checkpoint
-:::checkpoint-default
-Verify that you can access the `email`, `picture`, or any other claim after you have logged in.
-:::
+
-:::checkpoint-failure
-If you cannot access the user information:
-- Verify you imported the `JWTDecode` module where you invoke the `decode(jwt:)` method
-- Make sure you spelled your claims correctly
+ If you cannot access the user information:
Verify you imported the JWTDecode
module where you invoke the decode(jwt:)
method
Make sure you spelled your claims correctly
Still having issues? Check out our documentation or visit our community forums to get more help.
-Still having issues? Check out our documentation or visit our community forums to get more help.
-:::
-::::
+
diff --git a/articles/quickstart/native/maui/files/MainPage.xaml.md b/articles/quickstart/native/maui/files/MainPage.xaml.md
new file mode 100644
index 0000000000..010c5970f8
--- /dev/null
+++ b/articles/quickstart/native/maui/files/MainPage.xaml.md
@@ -0,0 +1,73 @@
+---
+name: MainPage.xaml.cs
+language: csharp
+---
+
+```csharp
+public partial class MainPage : ContentPage
+{
+ Auth0Client client = new Auth0Client(new Auth0ClientOptions
+ {
+ Domain = "${account.namespace}"
+ ClientId = "${account.clientId}",
+ RedirectUri = "myapp://callback",
+ PostLogoutRedirectUri = "myapp://callback",
+ Scope = "openid profile email"
+ });
+
+ public MainPage()
+ {
+ InitializeComponent();
+ }
+
+ private async void OnLoginClicked(object sender, EventArgs e)
+ {
+ var extraParameters = new Dictionary();
+ var audience = ""; // FILL WITH AUDIENCE AS NEEDED
+
+ if (!string.IsNullOrEmpty(audience))
+ extraParameters.Add("audience", audience);
+
+ var result = await client.LoginAsync(extraParameters);
+
+ DisplayResult(result);
+ }
+
+ private async void OnLogoutClicked(object sender, EventArgs e)
+ {
+ BrowserResultType browserResult = await client.LogoutAsync();
+
+ if (browserResult != BrowserResultType.Success)
+ {
+ ErrorLabel.Text = browserResult.ToString();
+ return;
+ }
+
+ LogoutBtn.IsVisible = false;
+ LoginBtn.IsVisible = true;
+
+ HelloLabel.Text = $"Hello, World!";
+ ErrorLabel.Text = "";
+ }
+
+ private void DisplayResult(LoginResult loginResult)
+ {
+ if (loginResult.IsError)
+ {
+ ErrorLabel.Text = loginResult.Error;
+ return;
+ }
+
+ var user = loginResult.User;
+ var name = user.FindFirst(c => c.Type == "name")?.Value;
+ var email = user.FindFirst(c => c.Type == "email")?.Value;
+ var picture = user.FindFirst(c => c.Type == "picture")?.Value;
+
+ LogoutBtn.IsVisible = true;
+ LoginBtn.IsVisible = false;
+
+ HelloLabel.Text = $"Hello, {loginResult.User.Identity.Name}";
+ ErrorLabel.Text = "";
+ }
+}
+```
diff --git a/articles/quickstart/native/maui/interactive.md b/articles/quickstart/native/maui/interactive.md
index cbe1ca5db4..7e7e0aa404 100644
--- a/articles/quickstart/native/maui/interactive.md
+++ b/articles/quickstart/native/maui/interactive.md
@@ -1,203 +1,160 @@
---
-title: Add login to your .NET MAUI application
-default: true
+title: Add Login to Your MAUI Application
description: This tutorial demonstrates how to add user login with Auth0 to a .NET MAUI application.
-budicon: 448
-topics:
- - quickstarts
- - native
- - maui
- - dotnet
- - android
- - ios
- - windows
-github:
- path: Sample
-contentType: tutorial
-useCase: quickstart
-interactive: true
+interactive: true
files:
- - files/main-page
+ - files/MainPage.xaml
+github:
+ path: https://github.com/auth0-samples/auth0-maui-samples/tree/master/Sample
+locale: en-US
---
# Add Login to Your MAUI Application
-Auth0 allows you to add authentication to almost any application type quickly. This guide demonstrates how to integrate Auth0, add authentication, and display user profile information in any .NET MAUI application using the Auth0 SDKs for MAUI.
-::: note
-The MAUI SDK supports Android, iOS, macOS, and Windows. Continue reading for platform-specific configuration.
-:::
+Auth0 allows you to add authentication to almost any application type quickly. This guide demonstrates how to integrate Auth0, add authentication, and display user profile information in any .NET MAUI application using the Auth0 SDKs for MAUI.
The MAUI SDK supports Android, iOS, macOS, and Windows. Continue reading for platform-specific configuration.
+
+## Configure Auth0
-<%= include('../../_includes/_configure_auth0_interactive', {
- callback: 'myapp://callback',
- returnTo: 'myapp://callback'
-}) %>
+
+To use Auth0 services, you’ll need to have an application set up in the Auth0 Dashboard. The Auth0 application is where you will configure how you want authentication to work for the project you are developing.
Configure an application
Use the interactive selector to create a new Auth0 application or select an existing application that represents the project you want to integrate with. Every application in Auth0 is assigned an alphanumeric, unique client ID that your application code will use to call Auth0 APIs through the SDK.
Any settings you configure using this quickstart will automatically update for your Application in the Dashboard, which is where you can manage your Applications in the future.
If you would rather explore a complete configuration, you can view a sample application instead.
Configure Callback URLs
A callback URL is a URL in your application that you would like Auth0 to redirect users to after they have authenticated. If not set, users will not be returned to your application after they log in.
If you are following along with our sample project, set this to myapp://callback
.
Configure Logout URLs
A logout URL is a URL in your application that you would like Auth0 to redirect users to after they have logged out. If not set, users will not be able to log out from your application and will receive an error.
If you are following along with our sample project, set this to myapp://callback
.
## Install the Auth0 SDK
-Auth0 provides a MAUI SDK to simplify the process of implementing Auth0 authentication in MAUI applications.
-Use the NuGet Package Manager (Tools -> Library Package Manager -> Package Manager Console) to install the `Auth0.OidcClient.MAUI` package.
+Auth0 provides a MAUI SDK to simplify the process of implementing Auth0 authentication in MAUI applications.
Use the NuGet Package Manager (Tools -> Library Package Manager -> Package Manager Console) to install the Auth0.OidcClient.MAUI
package.
Alternatively, you can use the NuGet Package Manager Console (Install-Package
) or the dotnet
CLI (dotnet add
).
Install-Package Auth0.OidcClient.MAUI
+
+
+
+dotnet add package Auth0.OidcClient.MAUI
-Alternatively, you can use the Nuget Package Manager Console (`Install-Package`) or the `dotnet` CLI (`dotnet add`).
+
-```ps
-Install-Package Auth0.OidcClient.MAUI
-```
-```
-dotnet add package Auth0.OidcClient.MAUI
-```
+
## Platform specific configuration
-You need some platform-specific configuration to use the SDK with Android and Windows.
-### Android
-Create a new Activity that extends `WebAuthenticatorCallbackActivity`:
+You need some platform-specific configuration to use the SDK with Android and Windows.
Android
Create a new Activity that extends WebAuthenticatorCallbackActivity
:
[Activity(NoHistory = true, LaunchMode = LaunchMode.SingleTop, Exported = true)]
-```csharp
-[Activity(NoHistory = true, LaunchMode = LaunchMode.SingleTop, Exported = true)]
[IntentFilter(new[] { Intent.ActionView },
+
Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
+
DataScheme = CALLBACK_SCHEME)]
+
public class WebAuthenticatorActivity : Microsoft.Maui.Authentication.WebAuthenticatorCallbackActivity
+
{
- const string CALLBACK_SCHEME = "myapp";
+
+ const string CALLBACK_SCHEME = "myapp";
+
}
-```
-
-The above activity will ensure the application can handle the `myapp://callback` URL when Auth0 redirects back to the Android application after logging in.
-
-### Windows
-To make sure it can properly reactivate your application after being redirected back to Auth0, you need to do two things:
-
-- Add the corresponding protocol to the `Package.appxmanifest`. In this case, this is set to `myapp`, but you can change this to whatever you like (ensure to update all relevant Auth0 URLs as well).
- ```xml
-
-
-
-
-
-
-
-
-
- ```
-- Call `Activator.Default.CheckRedirectionActivation()` in the Windows-specific `App.xaml.cs` file.
- ```csharp
- public App()
- {
- if (Auth0.OidcClient.Platforms.Windows.Activator.Default.CheckRedirectionActivation())
- return;
-
- this.InitializeComponent();
- }
- ```
-
-## Instantiate the Auth0Client {{{ data-action="code" data-code="MainPage.xaml.cs#3-10" }}}
-
-To integrate Auth0 into your application, instantiate an instance of the `Auth0Client` class, passing an instance of `Auth0ClientOptions` that contains your Auth0 Domain, Client ID and the required Scopes.
-Additionally, you also need to configure the `RedirectUri` and `PostLogoutRedirectUri` to ensure Auth0 can redirect back to the application using the URL(s) configured.
-
-```csharp
-using Auth0.OidcClient;
-var client = new Auth0Client(new Auth0ClientOptions
+
+
+The above activity will ensure the application can handle the myapp://callback
URL when Auth0 redirects back to the Android application after logging in.
Windows
To make sure it can properly reactivate your application after being redirected back to Auth0, you need to do two things:
Add the corresponding protocol to the Package.appxmanifest
. In this case, this is set to myapp
, but you can change this to whatever you like (ensure to update all relevant Auth0 URLs as well).
<Applications>
+
+ <Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="$targetentrypoint$">
+
+ <Extensions>
+
+ <uap:Extension Category="windows.protocol">
+
+ <uap:Protocol Name="myapp"/>
+
+ </uap:Extension>
+
+ </Extensions>
+
+ </Application>
+
+</Applications>
+
+
+
+Call Activator.Default.CheckRedirectionActivation()
in the Windows-specific App.xaml.cs
file.
public App()
+
{
- Domain = "${account.namespace}",
- ClientId = "${account.clientId}",
- RedirectUri = "myapp://callback",
- PostLogoutRedirectUri = "myapp://callback",
- Scope = "openid profile email"
-});
-```
-By default, the SDK will leverage Chrome Custom Tabs for Android, ASWebAuthenticationSession for iOS and macOS and use your system's default browser on Windows.
+ if (Auth0.OidcClient.Platforms.Windows.Activator.Default.CheckRedirectionActivation())
+
+ return;
+
+
+
+ this.InitializeComponent();
+
+}
+
+
+
+
+
+## Instantiate the Auth0Client {{{ data-action="code" data-code="MainPage.xaml.cs#3:10" }}}
+
-::::checkpoint
+To integrate Auth0 into your application, instantiate an instance of the Auth0Client
class, passing an instance of Auth0ClientOptions
that contains your Auth0 Domain, Client ID and the required Scopes. Additionally, you also need to configure the RedirectUri
and PostLogoutRedirectUri
to ensure Auth0 can redirect back to the application using the URL(s) configured.
using Auth0.OidcClient;
-:::checkpoint-default
-Your `Auth0Client` should now be properly instantiated. Run your application to verify that:
-- the `Auth0Client` is instantiated correctly in the `MainPage`.
-- your application is not throwing any errors related to Auth0
-:::
+var client = new Auth0Client(new Auth0ClientOptions
+
+{
-:::checkpoint-failure
-Sorry about that. Here are a couple things to double-check:
-* make sure the correct application is selected
-* did you save after entering your URLs?
-* make sure the domain and client ID are imported correctly
+ Domain = "${account.namespace}",
-Still having issues? Check out our documentation or visit our community page to get more help.
+ ClientId = "${account.clientId}",
-:::
-::::
+ RedirectUri = "myapp://callback",
-## Add login to your application {{{ data-action="code" data-code="MainPage.xaml.cs#25" }}}
+ PostLogoutRedirectUri = "myapp://callback",
-Now that you have configured your Auth0 Application and the Auth0 SDK, you need to set up login for your project. To do this, you will use the SDK’s `LoginAsync()` method to create a login button that redirects users to the Auth0 Universal Login page.
+ Scope = "openid profile email"
+
+});
-```csharp
-var loginResult = await client.LoginAsync();
-```
+
-If there isn't any error, you can access the `User`, `IdentityToken`, `AccessToken` and `RefreshToken` on the `LoginResult` returned from `LoginAsync()`.
+By default, the SDK will leverage Chrome Custom Tabs for Android, ASWebAuthenticationSession for iOS and macOS and use your system's default browser on Windows.
MAUI Quickstart - Step 4 Checkpoint Your Auth0Client
should now be properly instantiated. Run your application to verify that:
The Auth0Client
is instantiated correctly in the MainPage
.
Your application is not throwing any errors related to Auth0.
-::::checkpoint
+
-:::checkpoint-default
+ Sorry about that. Here are a couple things to double-check:
make sure the correct application is selected
did you save after entering your URLs?
make sure the domain and client ID are imported correctly
Still having issues? Check out our documentation or visit our community page to get more help.
-You should now be able to log in or sign up using a username and password.
+
-Click the login button and verify that:
-* your application redirects you to the Auth0 Universal Login page
-* you can log in or sign up
-* Auth0 redirects you to your application.
+## Add login to your application {{{ data-action="code" data-code="MainPage.xaml.cs#25:25" }}}
-:::
-:::checkpoint-failure
-Sorry about that. Here's something to double-check:
-* you called `LoginAsync` as expected
+Now that you have configured your Auth0 Application and the Auth0 SDK, you need to set up login for your project. To do this, you will use the SDK’s LoginAsync()
method to create a login button that redirects users to the Auth0 Universal Login page.
var loginResult = await client.LoginAsync();
-Still having issues? Check out our documentation or visit our community page to get more help.
+
-:::
-::::
+If there isn't any error, you can access the User
, IdentityToken
, AccessToken
and RefreshToken
on the LoginResult
returned from LoginAsync()
.
MAUI Quickstart - Step 5 Checkpoint You should now be able to log in or sign up using a username and password.
Click the login button and verify that:
Your application redirects you to the Auth0 Universal Login page.
You can log in or sign up.
Auth0 redirects you to your application.
-## Add logout to your application {{{ data-action="code" data-code="MainPage.xaml.cs#32" }}}
+
-Users who log in to your project will also need a way to log out. Create a logout button using the SDK’s `LogoutAsync()` method. When users log out, they will be redirected to your Auth0 logout endpoint, which will then immediately redirect them back to the logout URL you set up earlier in this quickstart.
+ Sorry about that. Here's something to double-check:
you called LoginAsync
as expected
Still having issues? Check out our documentation or visit our community page to get more help.
-```csharp
-await client.LogoutAsync();
-```
+
-::::checkpoint
+## Add logout to your application {{{ data-action="code" data-code="MainPage.xaml.cs#32:32" }}}
-:::checkpoint-default
-Run your application and click the logout button, verify that:
-* your application redirects you to the address you specified as one of the Allowed Logout URLs in your Application Settings
-* you are no longer logged in to your application
+Users who log in to your project will also need a way to log out. Create a logout button using the SDK’s LogoutAsync()
method. When users log out, they will be redirected to your Auth0 logout endpoint, which will then immediately redirect them back to the logout URL you set up earlier in this quickstart.
await client.LogoutAsync();
-:::
+
-:::checkpoint-failure
-Sorry about that. Here are a couple things to double-check:
-* you configured the correct Logout URL
-* you called `LogoutAsync` as expected.
+MAUI Quickstart - Step 6 Checkpoint Run your application and click the logout button, verify that:
Your application redirects you to the address you specified as one of the Allowed Logout URLs in your Application Settings.
You are no longer logged in to your application.
-Still having issues? Check out our documentation or visit our community page to get more help.
+
-:::
+ Sorry about that. Here are a couple things to double-check:
you configured the correct Logout URL
you called LogoutAsync
as expected.
Still having issues? Check out our documentation or visit our community page to get more help.
-::::
+
-## Show User Profile Information {{{ data-action="code" data-code="MainPage.xaml.cs#55-58" }}}
+## Show user profile information {{{ data-action="code" data-code="MainPage.xaml.cs#55:58" }}}
-Now that your users can log in and log out, you will likely want to be able to retrieve the profile information associated with authenticated users. For example, you may want to be able to display a logged-in user’s name or profile picture in your project.
-The Auth0 SDK for MAUI provides user information through the `LoginResult.User` property.
+Now that your users can log in and log out, you will likely want to be able to retrieve the profile information associated with authenticated users. For example, you may want to be able to display a logged-in user’s name or profile picture in your project.
The Auth0 SDK for MAUI provides user information through the LoginResult.User
property.
diff --git a/articles/quickstart/native/net-android-ios/files/AppDelegate.md b/articles/quickstart/native/net-android-ios/files/AppDelegate.md
new file mode 100644
index 0000000000..0efcf0d8ce
--- /dev/null
+++ b/articles/quickstart/native/net-android-ios/files/AppDelegate.md
@@ -0,0 +1,19 @@
+---
+name: AppDelegate.cs
+language: csharp
+---
+
+```csharp
+using Auth0.OidcClient;
+
+[Register("AppDelegate")]
+public class AppDelegate : UIApplicationDelegate
+{
+ public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
+ {
+ ActivityMediator.Instance.Send(url.AbsoluteString);
+
+ return true;
+ }
+}
+```
diff --git a/articles/quickstart/native/net-android-ios/files/MainActivity.md b/articles/quickstart/native/net-android-ios/files/MainActivity.md
new file mode 100644
index 0000000000..dcf30e59af
--- /dev/null
+++ b/articles/quickstart/native/net-android-ios/files/MainActivity.md
@@ -0,0 +1,57 @@
+---
+name: MainActivity.cs
+language: csharp
+---
+
+```csharp
+// Example of a full Android Activity
+[Activity(Label = "AndroidSample", MainLauncher = true, Icon = "@drawable/icon",
+ LaunchMode = LaunchMode.SingleTask)]
+[IntentFilter(
+ new[] { Intent.ActionView },
+ Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
+ DataScheme = "YOUR_ANDROID_PACKAGE_NAME",
+ DataHost = "${account.namespace}",
+ DataPathPrefix = "/android/YOUR_ANDROID_PACKAGE_NAME/callback")]
+public class MainActivity : Activity
+{
+ private Auth0Client _auth0Client;
+
+ protected override void OnNewIntent(Intent intent)
+ {
+ base.OnNewIntent(intent);
+ ActivityMediator.Instance.Send(intent.DataString);
+ }
+
+ protected override void OnCreate(Bundle bundle)
+ {
+ base.OnCreate(bundle);
+
+ Auth0ClientOptions clientOptions = new Auth0ClientOptions
+ {
+ Domain = "${account.namespace}"
+ ClientId = "${account.clientId}"
+ };
+
+ _auth0Client = new Auth0Client(clientOptions, this);
+ }
+
+ private async void LoginButtonOnClick(object sender, EventArgs eventArgs)
+ {
+ var loginResult = await _auth0Client.LoginAsync();
+
+ if (loginResult.IsError == false)
+ {
+ var user = loginResult.User;
+ var name = user.FindFirst(c => c.Type == "name")?.Value;
+ var email = user.FindFirst(c => c.Type == "email")?.Value;
+ var picture = user.FindFirst(c => c.Type == "picture")?.Value;
+ }
+ }
+
+ private async void LogoutButtonOnClick(object sender, EventArgs e)
+ {
+ await _auth0Client.LogoutAsync();
+ }
+}
+```
diff --git a/articles/quickstart/native/net-android-ios/files/MyViewController.md b/articles/quickstart/native/net-android-ios/files/MyViewController.md
new file mode 100644
index 0000000000..99821cc2bd
--- /dev/null
+++ b/articles/quickstart/native/net-android-ios/files/MyViewController.md
@@ -0,0 +1,47 @@
+---
+name: MyViewController.cs
+language: csharp
+---
+
+```csharp
+// Example of a full iOS UIViewController
+public partial class MyViewController : UIViewController
+{
+ private Auth0Client _auth0Client;
+
+ public MyViewController() : base("MyViewController", null)
+ {
+ }
+
+ public override void ViewDidLoad()
+ {
+ base.ViewDidLoad();
+
+ Auth0ClientOptions clientOptions = new Auth0ClientOptions
+ {
+ Domain = "${account.namespace}"
+ ClientId = "${account.clientId}"
+ };
+
+ _auth0Client = new Auth0Client(clientOptions, this);
+ }
+
+ private async void LoginButton_TouchUpInside(object sender, EventArgs e)
+ {
+ var loginResult = await _auth0Client.LoginAsync();
+
+ if (loginResult.IsError == false)
+ {
+ var user = loginResult.User;
+ var name = user.FindFirst(c => c.Type == "name")?.Value;
+ var email = user.FindFirst(c => c.Type == "email")?.Value;
+ var picture = user.FindFirst(c => c.Type == "picture")?.Value;
+ }
+ }
+
+ private async void LogoutButton_TouchUpInside(object sender, EventArgs e)
+ {
+ await _auth0Client.LogoutAsync();
+ }
+}
+```
diff --git a/articles/quickstart/native/net-android-ios/interactive.md b/articles/quickstart/native/net-android-ios/interactive.md
index 1255214a65..7bd2c84c09 100644
--- a/articles/quickstart/native/net-android-ios/interactive.md
+++ b/articles/quickstart/native/net-android-ios/interactive.md
@@ -1,208 +1,165 @@
---
-title: Add login to your .NET Android or iOS application
-default: true
+title: Add Login to Your .NET Android and iOS Application
description: This tutorial demonstrates how to add user login with Auth0 to a .NET Android or iOS application.
-budicon: 448
-topics:
- - quickstarts
- - native
- - xamarin
- - dotnet
- - android
- - ios
-github:
- path: Quickstart/01-Login
-contentType: tutorial
-useCase: quickstart
-interactive: true
+interactive: true
files:
- - files/main-activity
- - files/app-delegate
- - files/my-view-controller
+ - files/MainActivity
+ - files/AppDelegate
+ - files/MyViewController
+github:
+ path: https://github.com/auth0-samples/auth0-xamarin-oidc-samples/tree/master/Quickstart/01-Login
+locale: en-US
---
# Add Login to Your .NET Android and iOS Application
-Auth0 allows you to add authentication to almost any application type quickly. This guide demonstrates how to integrate Auth0, add authentication, and display user profile information in any .NET Android and iOS application using the Auth0 SDKs for Android and iOS.
-::: note
-This quickstart focusses on .NET Android and iOS, as they are the next generation of `Xamarin.Android` and `Xamarin.iOS`. If you are still using `Xamarin.Android` and `Xamarin.iOS`, you can follow this guide as well as integration is identical and the SDKs are compatible.
-:::
+Auth0 allows you to add authentication to almost any application type quickly. This guide demonstrates how to integrate Auth0, add authentication, and display user profile information in any .NET Android and iOS application using the Auth0 SDKs for Android and iOS.
This quickstart focuses on .NET Android and iOS, as they are the next generation of Xamarin.Android
and Xamarin.iOS
. If you are still using Xamarin.Android
and Xamarin.iOS
, you can follow this guide as the integration is identical, and the SDKs are compatible.
-To use this quickstart, you’ll need to:
+
To use this quickstart, you’ll need to:
Sign up for a free Auth0 account or log in to Auth0.
Have a working Android or iOS project using .NET 6 (or above) that you want to integrate with. Alternatively, you can view or download a sample application after logging in.
-- Sign up for a free Auth0 account or log in to Auth0.
-- Have a working Android or iOS project using .NET 6 (or above) that you want to integrate with. Alternatively, you can view or download a sample application after logging in.
+## Configure Auth0
-<%= include('_configure_urls_interactive') %>
-## Install the Auth0 SDK
+To use Auth0 services, you need to have an application set up in the Auth0 Dashboard. The Auth0 application is where you will configure how you want authentication to work for your project.
Configure an application
Use the interactive selector to create a new "Native Application", or select an existing application that represents the project you want to integrate with. Every application in Auth0 is assigned an alphanumeric, unique client ID that your application code will use to call Auth0 APIs through the SDK.
Any settings you configure using this quickstart will automatically update for your application in the Dashboard, which is where you can manage your applications in the future.
If you would rather explore a complete configuration, you can view a sample application instead.
Configure Callback URLs
A callback URL is a URL in your application that you would like Auth0 to redirect users to after they have authenticated. If not set, users will not be returned to your application after they log in.
If you are following along with our sample project, set this to one of the following URLs depending on your platform:
Android: YOUR_PACKAGE_NAME://{yourDomain}/android/YOUR_PACKAGE_NAME/callback
iOS: YOUR_BUNDLE_ID://{yourDomain}/ios/YOUR_BUNDLE_ID/callback
Configure Logout URLs
A logout URL is a URL in your application that you would like Auth0 to redirect users to after they have logged out. If not set, users will not be able to log out from your application and will receive an error.
If you are following along with our sample project, set this to one of the following URLs depending on your platform:
Android: YOUR_PACKAGE_NAME://{yourDomain}/android/YOUR_PACKAGE_NAME/callback
iOS: YOUR_BUNDLE_ID://{yourDomain}/ios/YOUR_BUNDLE_ID/callback
Lastly, be sure that the Application Type for your application is set to Native in the Application Settings.
-Auth0 provides an Android and iOS SDK to simplify the process of implementing Auth0 authentication in .NET Android and iOS applications.
+## Install the Auth0 SDK
-Use the NuGet Package Manager (Tools -> Library Package Manager -> Package Manager Console) to install the `Auth0.OidcClient.AndroidX` or `Auth0.OidcClient.iOS` package, depending on whether you are building an Android or iOS application.
-Alternatively, you can use the Nuget Package Manager Console (`Install-Package`) or the `dotnet` CLI (`dotnet add`).
+Auth0 provides an Android and iOS SDK to simplify the process of implementing Auth0 authentication in .NET Android and iOS applications.
Use the NuGet Package Manager (Tools -> Library Package Manager -> Package Manager Console) to install the Auth0.OidcClient.AndroidX
or Auth0.OidcClient.iOS
package, depending on whether you are building an Android or iOS application.
Alternatively, you can use the NuGet Package Manager Console (Install-Package
) or the dotnet
CLI (dotnet add
).
Install-Package Auth0.OidcClient.AndroidX
-```ps
-Install-Package Auth0.OidcClient.AndroidX
Install-Package Auth0.OidcClient.iOS
-```
-```
-dotnet add Auth0.OidcClient.AndroidX
+
+
+
+dotnet add Auth0.OidcClient.AndroidX
+
dotnet add Auth0.OidcClient.iOS
-```
+
+
+
+
## Instantiate the Auth0Client
-To integrate Auth0 into your application, instantiate an instance of the `Auth0Client` class, passing an instance of `Auth0ClientOptions` that contains your Auth0 Domain and Client ID.
-```csharp
-using Auth0.OidcClient;
+To integrate Auth0 into your application, instantiate an instance of the Auth0Client
class, passing an instance of Auth0ClientOptions
that contains your Auth0 Domain and Client ID.
using Auth0.OidcClient;
+
+
+
+var client = new Auth0Client(new Auth0ClientOptions {
+
+ Domain = "${account.namespace}",
+
+ ClientId = "${account.clientId}"
-var client = new Auth0Client(new Auth0ClientOptions
-{
- Domain = "${account.namespace}",
- ClientId = "${account.namespace}"
}, this);
-```
-By default, the SDK will leverage Chrome Custom Tabs for Android and ASWebAuthenticationSession for iOS.
+
+
+By default, the SDK will leverage Chrome Custom Tabs for Android and ASWebAuthenticationSession for iOS.
.NET Android/iOS Quickstart - Step 3 Checkpoint Your Auth0Client
should now be properly instantiated. Run your application to verify that:
The Auth0Client
is instantiated correctly in the Activity
(Android) or UIViewController
(iOS).
Your application is not throwing any errors related to Auth0.
+
+
+
+ Sorry about that. Here are a couple things to double-check:
make sure the correct application is selected
did you save after entering your URLs?
make sure the domain and client ID are imported correctly
Still having issues? Check out our documentation or visit our community page to get more help.
+
+
-::::checkpoint
+## Configure Android {{{ data-action="code" data-code="MainActivity.cs#2:9" }}}
-:::checkpoint-default
-Your `Auth0Client` should now be properly instantiated. Run your application to verify that:
-- the `Auth0Client` is instantiated correctly in the `Activity` (Android) or `UIViewController` (iOS)
-- your application is not throwing any errors related to Auth0
+After a user successfully authenticates, they will be redirected to the callback URL you set up earlier in this quickstart.
To handle the callback on Android devices, you need to register an intent that handles this callback URL. An easy way to do this is to register the intent on the same activity from which you called the LoginAsync method to instantiate the authentication flow.
Ensure to replace YOUR_ANDROID_PACKAGE_NAME
in the code sample with the actual Package Name for your application, such as com.mycompany.myapplication
, and ensure that all the text for the DataScheme
, DataHost
, and DataPathPrefix
is in lowercase. Also, set LaunchMode = LaunchMode.SingleTask
for the Activity; otherwise, the system will create a new instance of the activity every time the Callback URL gets called.
Additionally, you need to handle the intent in the OnNewIntent
event in your Activity
class. You need to notify the Auth0 OIDC Client to finish the authentication flow by calling the Send
method of the ActivityMediator
singleton, passing along the URL that was sent in.
protected override void OnNewIntent(Intent intent)
-:::
+ {
-:::checkpoint-failure
-Sorry about that. Here are a couple things to double-check:
-* make sure the correct application is selected
-* did you save after entering your URLs?
-* make sure the domain and client ID are imported correctly
+ base.OnNewIntent(intent);
-Still having issues? Check out our documentation or visit our community page to get more help.
+ ActivityMediator.Instance.Send(intent.DataString);
-:::
-::::
+ }
-## Configure Android {{{ data-action="code" data-code="MainActivity.cs#2-9,14-18" }}}
+
-After a user successfully authenticates, they will be redirected to the callback URL you set up earlier in this quickstart.
+
-To handle the callback on Android devices, you need to register an intent that handles this callback URL. An easy way to do this is to register the intent on the same activity from which you called the LoginAsync method to instantiate the authentication flow.
+## Configure iOS {{{ data-action="code" data-code="AppDelegate.cs#6:11" }}}
-Ensure to replace `YOUR_ANDROID_PACKAGE_NAME` in the code sample with the actual Package Name for your application, such as com.mycompany.myapplication, and ensure that all the text for the `DataScheme`, `DataHost`, and `DataPathPrefix` is in lower case. Also, set `LaunchMode = LaunchMode.SingleTask` for the Activity, otherwise the system will create a new instance of the activity every time the Callback URL gets called.
-Additionally, you need to handle the intent in the `OnNewIntent` event in your `Activity` class. You need to notify the Auth0 OIDC Client to finish the authentication flow by calling the `Send` method of the `ActivityMediator` singleton, passing along the URL that was sent in.
+After a user successfully authenticates, they will be redirected to the callback URL you set up earlier in this quickstart.
To handle the callback on iOS devices:
Open your application's Info.plist
file in Visual Studio, and go to the Advanced tab.
Under URL Types, click the Add URL Type button.
Set the Identifier as Auth0, the URL Schemes the same as your application's Bundle Identifier
, and the Role as None
.
This is an example of the XML representation of your info.plist
file after you have added the URL Type:
<key>CFBundleURLTypes</key>
-## Configure iOS {{{ data-action="code" data-code="AppDelegate.cs#6-11" }}}
+<array>
-After a user successfully authenticates, they will be redirected to the callback URL you set up earlier in this quickstart.
+ <dict>
-To handle the callback on iOS devices:
+ <key>CFBundleTypeRole</key>
-- Open your application's `Info.plist` file in Visual Studio, and go to the **Advanced** tab.
-- Under **URL Types**, click the **Add URL Type** button
-- Set the **Identifier** as Auth0, the **URL Schemes** the same as your application's Bundle Identifier, and the **Role** as None
+ <string>None</string>
-This is an example of the XML representation of your `info.plist` file after you have added the URL Type:
+ <key>CFBundleURLName</key>
-```xml
-CFBundleURLTypes
-
-
- CFBundleTypeRole
- None
- CFBundleURLName
- Auth0
- CFBundleURLSchemes
-
- YOUR_BUNDLE_IDENTIFIER
-
-
-
-```
+ <string>Auth0</string>
-Additionally, you need to handle the Callback URL in the `OpenUrl` event in your `AppDelegate` class. You need to notify the Auth0 OIDC Client to finish the authentication flow by calling the `Send` method of the `ActivityMediator` singleton, passing along the URL that was sent in.
+ <key>CFBundleURLSchemes</key>
-## Add login to your application
+ <array>
-Now that you have configured your Auth0 Application and the Auth0 SDK, you need to set up login for your project. To do this, you will use the SDK’s `LoginAsync()` method to create a login button that redirects users to the Auth0 Universal Login page.
+ <string>YOUR_BUNDLE_IDENTIFIER</string>
-```csharp
-var loginResult = await client.LoginAsync();
-```
+ </array>
-If there isn't any error, you can access the `User`, `IdentityToken`, `AccessToken` and `RefreshToken` on the `LoginResult` returned from `LoginAsync()`.
+ </dict>
-::::checkpoint
+</array>
-:::checkpoint-default
+
-You should now be able to log in or sign up using a username and password.
+Additionally, you need to handle the Callback URL in the OpenUrl
event in your AppDelegate
class. You need to notify the Auth0 OIDC Client to finish the authentication flow by calling the Send
method of the ActivityMediator
singleton, passing along the URL that was sent in.
-Click the login button and verify that:
-* your Android or iOS application redirects you to the Auth0 Universal Login page
-* you can log in or sign up
-* Auth0 redirects you to your application.
+## Add login to your application
-:::
-:::checkpoint-failure
-Sorry about that. Here's something to double-check:
-* you called `LoginAsync` as expected
+Now that you have configured your Auth0 Application and the Auth0 SDK, you need to set up login for your project. To do this, you will use the SDK’s LoginAsync()
method to create a login button that redirects users to the Auth0 Universal Login page.
var loginResult = await client.LoginAsync();
-Still having issues? Check out our documentation or visit our community page to get more help.
+
-:::
-::::
+If there isn't any error, you can access the User
, IdentityToken
, AccessToken
and RefreshToken
on the LoginResult
returned from LoginAsync()
.
.NET Android/iOS Quickstart - Step 6 Checkpoint You should now be able to log in or sign up using a username and password.
Click the login button and verify that:
Your Android or iOS application redirects you to the Auth0 Universal Login page.
You can log in or sign up.
Auth0 redirects you to your application.
+
+
+
+ Sorry about that. Here's something to double-check:
you called LoginAsync
as expected
Still having issues? Check out our documentation or visit our community page to get more help.
+
+
## Add logout to your application
-Users who log in to your project will also need a way to log out. Create a logout button using the SDK’s `LogoutAsync()` method. When users log out, they will be redirected to your Auth0 logout endpoint, which will then immediately redirect them back to the logout URL you set up earlier in this quickstart.
-```csharp
-await client.LogoutAsync();
-```
+Users who log in to your project will also need a way to log out. Create a logout button using the SDK’s LogoutAsync()
method. When users log out, they will be redirected to your Auth0 logout endpoint, which will then immediately redirect them back to the logout URL you set up earlier in this quickstart.
await client.LogoutAsync();
-::::checkpoint
+
-:::checkpoint-default
+.NET Android/iOS Quickstart - Step 7 Checkpoint Run your application and click the logout button. Verify that:
Your Android or iOS application redirects you to the address you specified as one of the Allowed Logout URLs in your Application Settings.
You are no longer logged in to your application.
-Run your application and click the logout button, verify that:
-* your Android or iOS application redirects you to the address you specified as one of the Allowed Logout URLs in your Application Settings
-* you are no longer logged in to your application
+
-:::
+ Sorry about that. Here are a couple things to double-check:
you configured the correct Logout URL
you called LogoutAsync
as expected.
Still having issues? Check out our documentation or visit our community page to get more help.
-:::checkpoint-failure
-Sorry about that. Here are a couple things to double-check:
-* you configured the correct Logout URL
-* you called `LogoutAsync` as expected.
+
-Still having issues? Check out our documentation or visit our community page to get more help.
+## Show user profile information
-:::
-::::
+Now that your users can log in and log out, you will likely want to be able to retrieve the profile information associated with authenticated users. For example, you may want to display a logged-in user’s name or profile picture in your project.
The Auth0 SDK for Android and iOS provides user information through the LoginResult.User
property.
if loginResult.IsError == false {
-## Show User Profile Information
+ var user = loginResult.User
-Now that your users can log in and log out, you will likely want to be able to retrieve the profile information associated with authenticated users. For example, you may want to be able to display a logged-in user’s name or profile picture in your project.
+ var name = user.FindFirst(c => c.Type == "name")?.Value
-The Auth0 SDK for Android and iOS provides user information through the `LoginResult.User` property.
+ var email = user.FindFirst(c => c.Type == "email")?.Value
+
+ var picture = user.FindFirst(c => c.Type == "picture")?.Value
-```csharp
-if (loginResult.IsError == false)
-{
- var user = loginResult.User;
- var name = user.FindFirst(c => c.Type == "name")?.Value;
- var email = user.FindFirst(c => c.Type == "email")?.Value;
- var picture = user.FindFirst(c => c.Type == "picture")?.Value;
}
-```
+
+
+
+
diff --git a/articles/quickstart/native/react-native-expo/files/app.md b/articles/quickstart/native/react-native-expo/files/app.md
index 76f15e528c..2812a72d51 100644
--- a/articles/quickstart/native/react-native-expo/files/app.md
+++ b/articles/quickstart/native/react-native-expo/files/app.md
@@ -1,43 +1,49 @@
---
-name: App.js
-language: javascript
+name: app.json
+language: json
---
-
-```javascript
-import React from 'react';
-import {Button, Text, View, StyleSheet} from 'react-native';
-import {useAuth0, Auth0Provider} from 'react-native-auth0';
-
-const Home = () => {
- const {authorize, clearSession, user, error, isLoading} = useAuth0();
-
- const onLogin = async () => {
- try {
- await authorize();
- } catch (e) {
- console.log(e);
- }
- };
-
- const onLogout = async () => {
- try {
- await clearSession();
- } catch (e) {
- console.log('Log out cancelled');
+
+```json
+{
+ "expo": {
+ "name": "00-Login-Expo",
+ "slug": "00-Login-Expo",
+ "version": "1.0.0",
+ "orientation": "portrait",
+ "icon": "./assets/icon.png",
+ "userInterfaceStyle": "light",
+ "plugins": [
+ [
+ "react-native-auth0",
+ {
+ "domain": "${account.namespace}",
+ }
+ ]
+ ],
+ "splash": {
+ "image": "./assets/splash.png",
+ "resizeMode": "contain",
+ "backgroundColor": "#ffffff"
+ },
+ "updates": {
+ "fallbackToCacheTimeout": 0
+ },
+ "assetBundlePatterns": [
+ "**/*"
+ ],
+ "web": {
+ "favicon": "./assets/favicon.png"
+ },
+ "android": {
+ "package": "com.auth0samples"
+ },
+ "ios": {
+ "bundleIdentifier": "com.auth0samples"
}
- };
-
- if (isLoading) {
- return Loading ;
}
-
- const loggedIn = user !== undefined && user !== null;
-
- return (
-
- {loggedIn && You are logged in as {user.name} }
- {!loggedIn && You are not logged in }
- {error && {error.message} }
+}
+```
+r && {error.message} }