<@U04UQ68083H> Please explain to me the flow of Or...
# ory-copilot
q
@chilly-king-10285 Please explain to me the flow of Ory Kratos for Native Apps
c
A message from kapa.ai
The flow of Ory Kratos for native apps involves several steps: 1. Initialization: The native app initializes a login or registration flow through the Ory Network APIs. The flow is of type
api
. The
return_to
parameter is set to the URL of the native application, which is used to redirect the user back to the app after the social sign-in. The
return_session_token_exchange_code
parameter is set to
true
to receive the session token exchange code in the response. 2. Social Sign-in: Upon rendering the form, the user selects the specific social sign-in provider. The native application submits the form to the Ory Network. If the user needs to perform a social sign-in from a flow of type
api
, Ory Network returns a
422
status code. The response contains the URL of the identity provider in the
redirect_browser_to
field. The user authenticates with the identity provider and grants the application access to profile information. The identity provider then issues a redirect to the Ory Network callback URL, which the browser follows. 3. Session Token Exchange: Ory Network issues a session for the user and redirects the browser to the application's
return_to
URL. The native application receives the second part of the session token exchange code in the
code
URL query parameter. The native application then exchanges the session token exchange code for a session token using the first part of the code returned from the flow initialization, and the second part of the code returned from the
return_to
query parameter. 4. Session Token Storage: Finally, the native application stores the session token in the secure storage and redirects the user to the home screen. Please note that native applications must use the API flows which don't set any cookies. The response contains all data required to render the UI. On successful login, Ory issues a session token that can be used to authenticate following requests to Ory. Sources: - [Native App Authentication Flow](https://www.ory.sh/docs/kratos/social-signin/native-apps#the-native-app-authentication-flow) - [Implementation of Native App Authentication Flow](https://www.ory.sh/docs/kratos/social-signin/native-apps#implementation) - [API Flows: Native Mobile & Desktop Apps](https://www.ory.sh/docs/kratos/self-service#api-flows-native-mobile--desktop-apps-command-line-interfaces-smart-tvs-and-more) - [Ory Identities API - frontend](https://www.ory.sh/docs/kratos/reference/api) - [Integration Basics](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#flows)
q
@chilly-king-10285 How do I perform SSO with Google for Native Apps using HTTP Requests
c
A message from kapa.ai
To perform Single Sign-On (SSO) with Google for native apps using HTTP requests, you can follow these steps: 1. Configure Google Social Sign-in Provider: Configure a Google social sign-in provider in Ory using the same
client_id
as used in your native app. If your Android app generates different token audiences per distribution (debug, release, etc.), you can add the ID of your current distribution to the
additional_id_token_audiences
field. 2. Obtain an
id_token
from Google
: Obtain an
id_token
from Google using the Google SDK. If your SDK supports nonce validation, make sure to use a generated value and submit that during the next step. 3. Submit the
id_token
and
nonce
to Ory
: Submit the
id_token
and
nonce
(as the
id_token_nonce
) as part of the
updateRegistrationFlow
or
updateLoginFlow
request to Ory. Ory will validate the
id_token
and create an identity and optionally a session (if configured). Here is an example of how you can implement a Sign in with Google button using the Ory SDK and google_sign_in Flutter package:
Copy code
dart
import 'package:flutter/material.dart';  
import 'package:google_sign_in/google_sign_in.dart';  
import 'package:one_of/one_of.dart';  
import 'package:ory_client/ory_client.dart';  
  
class SignInWithGoogleButton extends StatelessWidget {  
  final String flowId;  
  final OryClient ory;  
  
  final GoogleSignIn _googleSignIn = GoogleSignIn(  
    scopes: [  
      'email',  
      // Add additional scopes, if you require that data in your Jsonnet mapping  
    ],  
  );  
  
  SignInWithGoogleButton({super.key, required this.flowId, required this.ory});  
  
  void handleGoogleSignIn(GoogleSignInAccount? value) {  
    value?.authentication.then((value) {  
      var idToken = value.idToken;  
      if (idToken == null) {  
        // If we end up here, but there is no ID token, something went wrong  
        print("No idToken found");  
        return;  
      }  
  
      // Create the payload for the updateRegistrationFlow endpoint with the idToken from Google  
      var body = UpdateRegistrationFlowWithOidcMethod(  
        (b) => b  
          ..idToken = idToken  
          ..method = 'oidc'  
          ..provider = 'google',  
      );  
  
      // Submit the updateRegistrationFlow endpoint with the payload  
      ory.getFrontendApi().updateRegistrationFlow(  
            flow: flowId,  
            updateRegistrationFlowBody: UpdateRegistrationFlowBody(  
                (b) => b..oneOf = OneOf.fromValue1(value: body)),  
          );  
    });  
  }  
  
  @override  
  Widget build(BuildContext context) {  
    return TextButton(  
      child: const Text("Sign in with Google"),  
      onPressed: () => {_googleSignIn.signIn().then(handleGoogleSignIn)},  
    );  
  }  
}
To perform Single Sign-On (SSO) with Google for native apps using HTTP requests, you can follow these steps: 1. Configure Google Social Sign-in Provider: Configure a Google social sign-in provider in Ory using the same
client_id
as used in your native app. If your Android app generates different token audiences per distribution (debug, release, etc.), you can add the ID of your current distribution to the
additional_id_token_audiences
field. 2. Obtain an
id_token
from Google
: Obtain an
id_token
from Google using the Google SDK. If your SDK supports nonce validation, make sure to use a generated value and submit that during the next step. 3. Submit the
id_token
and
nonce
to Ory
: Submit the
id_token
and
nonce
(as the
id_token_nonce
) as part of the
updateRegistrationFlow
or
updateLoginFlow
request to Ory. Ory will validate the
id_token
and create an identity and optionally a session (if configured). Here is an example of how you can implement a Sign in with Google button using the Ory SDK and google_sign_in Flutter package:
Copy code
dart import 'package:flutter/material.dart';   import 'package:google_sign_in/google_sign_in.dart';   import 'package:one_of/one_of.dart';   import 'package:ory_client/ory_client.dart';      class SignInWithGoogleButton extends StatelessWidget {     final String flowId;     final OryClient ory;        final GoogleSignIn _googleSignIn = GoogleSignIn(       scopes: [         'email',         // Add additional scopes, if you require that data in your Jsonnet mapping       ],     );        SignInWithGoogleButton({super.key, required this.flowId, required this.ory});        void handleGoogleSignIn(GoogleSignInAccount? value) {       value?.authentication.then((value) {         var idToken = value.idToken;         if (idToken == null) {           // If we end up here, but there is no ID token, something went wrong           print("No idToken found");           return;         }            // Create the payload for the updateRegistrationFlow endpoint with the idToken from Google         var body = UpdateRegistrationFlowWithOidcMethod(           (b) => b             ..idToken = idToken             ..method = 'oidc'             ..provider = 'google',         );            // Submit the updateRegistrationFlow endpoint with the payload         ory.getFrontendApi().updateRegistrationFlow(               flow: flowId,               updateRegistrationFlowBody: UpdateRegistrationFlowBody(                   (b) => b..oneOf = OneOf.fromValue1(value: body)),             );       });     }        @override     Widget build(BuildContext context) {       return TextButton(         child: const Text("Sign in with Google"),         onPressed: () => {_googleSignIn.signIn().then(handleGoogleSignIn)},       );     }   }
Sources: - [Google Social Sign-in](https://www.ory.sh/docs/kratos/social-signin/google#using-the-google-sdk-on-native-apps) - [Flutter Code Example](https://www.ory.sh/docs/kratos/social-signin/google#flutter-code-example)
q
@chilly-king-10285 I don't want to use the SDK Tell me how to work with the response from HTTP request
c
A message from kapa.ai
Sure, you can work with HTTP requests directly without using the SDK. Here's a general guide on how to handle responses from HTTP requests in Ory: 1. Successful Requests: If the request is successful, Ory will return a
200
or
204
HTTP status code. The response body will contain the data you requested. For example, in a successful login, Ory issues a session token that can be used to authenticate following requests to Ory. 2. Error Handling: Ory provides errors at different levels of the flow: request level, method level, and field level. Each level's error message structure is the same. Here's an example of how you can handle errors:
Copy code
javascript
// call the api  
// api...  
.then(({data: flow}) => {  
  // error message can also exist inside the flow data even when the request is successful.  
  // This is the case when retrieving the login flow using the flow ID and the flow was submitted previously  
  // but still contains errors.  

  // method level error  
  // messages is an array of error messages  
  err.response?.data?.ui.messages.forEach((message) => {  
    console.log(message)  
  })  

  // field level error  
  err.response?.data?.ui.nodes.forEach(({ messages }) => {  
    // messages is an array of error messages  
    messages.forEach((message) => {  
      console.log(message)  
    })  
  })  
})  
.catch((err: AxiosError) => {  
  // if the request failed but the response is not just an error  
  // it will contain flow data which can be used to display error messages  
  // this is common when submitting a form (e.g. login or registration)  
  // and getting a response status 400 `Bad Request` back.  

  if (err.response.status === 400) {  
    // method level error  
    // messages is an array of error messages  
    err.response?.data?.ui.messages.forEach((message) => {  
      console.log(message)  
    })  

    // field level error  
    err.response?.data?.ui.nodes.forEach(({ messages }) => {  
      // messages is an array of error messages  
      messages.forEach((message) => {  
        console.log(message)  
      })  
    })  
  } else {  
    // request level error  
    if (err.response?.data?.error) {  
      console.log(err.response.data.error)  
    }  
  }  
})
3. Webhook Response Handling: Webhooks can be configured to ignore the response, or to parse the response and use it to interrupt the flow or to update the identity. If you decide that the system response that indicates if the process was successful is not critical for your setup, make the webhook execution non-blocking to ignore whatever response is returned. To do that, set
response.ignore
to
true
in the webhook config.
Sure, you can work with HTTP requests directly without using the SDK. Here's a general guide on how to handle responses from HTTP requests in Ory: 1. Successful Requests: If the request is successful, Ory will return a
200
or
204
HTTP status code. The response body will contain the data you requested. For example, in a successful login, Ory issues a session token that can be used to authenticate following requests to Ory. 2. Error Handling: Ory provides errors at different levels of the flow: request level, method level, and field level. Each level's error message structure is the same. Here's an example of how you can handle errors:
Copy code
javascript // call the api   // api...   .then(({data: flow}) => {     // error message can also exist inside the flow data even when the request is successful.     // This is the case when retrieving the login flow using the flow ID and the flow was submitted previously     // but still contains errors.      // method level error     // messages is an array of error messages     err.response?.data?.ui.messages.forEach((message) => {       console.log(message)     })      // field level error     err.response?.data?.ui.nodes.forEach(({ messages }) => {       // messages is an array of error messages       messages.forEach((message) => {         console.log(message)       })     })   })   .catch((err: AxiosError) => {     // if the request failed but the response is not just an error     // it will contain flow data which can be used to display error messages     // this is common when submitting a form (e.g. login or registration)     // and getting a response status 400 `Bad Request` back.      if (err.response.status === 400) {       // method level error       // messages is an array of error messages       err.response?.data?.ui.messages.forEach((message) => {         console.log(message)       })        // field level error       err.response?.data?.ui.nodes.forEach(({ messages }) => {         // messages is an array of error messages         messages.forEach((message) => {           console.log(message)         })       })     } else {       // request level error       if (err.response?.data?.error) {         console.log(err.response.data.error)       }     }   })
3. Webhook Response Handling: Webhooks can be configured to ignore the response, or to parse the response and use it to interrupt the flow or to update the identity. If you decide that the system response that indicates if the process was successful is not critical for your setup, make the webhook execution non-blocking to ignore whatever response is returned. To do that, set
response.ignore
to
true
in the webhook config. Sources: - [Webhook Response Handling](https://www.ory.sh/docs/guides/integrate-with-ory-cloud-through-webhooks#webhook-response-handling) - [Error Handling](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#error-handling) - [Native Application](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#native-application)
q
@chilly-king-10285 After making an HTTP Request to http://localhost:4433/self-service/login/api?return_session_token_exchange_code=true I get "state": "choose_method" with "nodes": [ { "type": "input", "group": "oidc", "attributes": { "name": "provider", "type": "submit", "value": "google", "disabled": false, "node_type": "input" }, What do I do now
c
A message from kapa.ai
The response you received indicates that the login flow is in the "choose_method" state. This means you need to choose a method to sign in with. In your case, the method is "oidc" (OpenID Connect), and the provider is "google". To proceed, you need to make a POST request to the "action" URL provided in the "ui" object of the response. The body of the request should contain the "provider" field with the value "google". Here's an example of how you might structure this request in curl:
Copy code
bash curl -X POST -H "Content-Type: application/json" \ -d '{"provider":"google"}' \ <action_url>
Replace
<action_url>
with the actual "action" URL from the response. This will initiate the OpenID Connect flow with Google as the provider. Please note that this is a simplified example and the actual request might need additional parameters depending on your setup. After this, you'll be redirected to Google's sign-in page. Once you've successfully authenticated with Google, you'll be redirected back to your application with a session token. Please note that this is a general guide and the exact steps might vary based on your specific setup and requirements.
q
@chilly-king-10285 On doing this I get { "error": { "id": "browser_location_change_required", "code": 422,
c
A message from kapa.ai
The
422
error code with the
browser_location_change_required
message indicates that the browser needs to be redirected to a new location. This is usually sent when an AJAX request indicates that the browser needs to open a specific URL. This is most likely used in Social Sign In flows. In the error response, there should be a field named
redirect_browser_to
. This field contains the URL to which the browser needs to be redirected. Here's an example of how the error response might look:
Copy code
json {     "error": {       "id": "browser_location_change_required",       "code": 422,       "status": "Unprocessable Entity",       "reason": "In order to complete this flow please redirect the browser to: /ui/login?flow=ad574ad7-1a3c-4b52-9f54-ef9e866f3cec",       "message": "browser location change required",     },     "redirect_browser_to": "/ui/login?flow=ad574ad7-1a3c-4b52-9f54-ef9e866f3cec",   }
In this case, you should redirect the browser to the URL specified in the
redirect_browser_to
field to continue with the flow. Sources: - [SPAs and the '422' error](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-advanced-integration#spas-and-the-422-error) - [Ory Identities API - frontend](https://www.ory.sh/docs/kratos/reference/api)
q
@chilly-king-10285 But I do not have a browser. I am performing Authentication for Native App here
c
A message from kapa.ai
In the context of a native app, the "browser" refers to a web view or similar component within your app that can handle web URLs. When you receive a
422
status code with a
redirect_browser_to
field in the response, it means you need to open the URL specified in
redirect_browser_to
in a web view within your app. Here's how you can handle this: 1. Open a Web View: Use a web view component provided by your app's framework to open the URL. For example, in a React Native app, you might use the [WebBrowser](https://docs.expo.dev/versions/latest/sdk/webbrowser/) module from Expo. 2. Handle the Redirect: After the user completes the sign-in process in the web view, the identity provider (Google, in your case) will redirect the user to a callback URL. You need to handle this redirect in your app and extract the session token or other data from the redirect URL. 3. Close the Web View: Once you've handled the redirect and extracted the necessary data, you can close the web view and continue with your app's flow. Please note that the exact steps and code will depend on the specific framework and libraries you're using in your app. Sources: - [Native App Authentication Flow](https://www.ory.sh/docs/kratos/social-signin/native-apps#the-native-app-authentication-flow) - [Implementation of Native App Authentication Flow](https://www.ory.sh/docs/kratos/social-signin/native-apps#implementation)
q
@chilly-king-10285 Okay so once I get to the choose method am I supposed to make a CURL request or what ?
c
A message from kapa.ai
When you receive the "choose_method" state, it means you need to choose a method to proceed with the flow. In your case, the method is "oidc" (OpenID Connect), and the provider is "google". However, since you're working with a native app, you can't make a cURL request directly. Instead, you need to open a web view within your app and navigate to the URL specified in the
redirect_browser_to
field of the response. Here's a general guide on how to proceed: 1. Open a Web View: Use a web view component provided by your app's framework to open the URL. This will initiate the OpenID Connect flow with Google as the provider. 2. Handle the Redirect: After the user completes the sign-in process in the web view, the identity provider (Google, in your case) will redirect the user to a callback URL. You need to handle this redirect in your app and extract the session token or other data from the redirect URL. 3. Close the Web View: Once you've handled the redirect and extracted the necessary data, you can close the web view and continue with your app's flow. Please note that the exact steps and code will depend on the specific framework and libraries you're using in your app. Sources: - [Native App Authentication Flow](https://www.ory.sh/docs/kratos/social-signin/native-apps#the-native-app-authentication-flow) - [Implementation of Native App Authentication Flow](https://www.ory.sh/docs/kratos/social-signin/native-apps#implementation)
q
@chilly-king-10285 In the web view how do I specify provider: google ?
c
A message from kapa.ai
When you're at the "choose_method" state, the response from Ory Kratos includes a list of nodes. Each node represents a form field or a button. In your case, you have a node with the type "input" and the group "oidc". The "value" of this node is "google", which indicates that this is the button for signing in with Google. In a web view, you don't need to manually specify
provider: google
. Instead, you should render the form fields and buttons based on the nodes in the response. When the user clicks the "Sign in with Google" button, your app should automatically submit the form with
provider: google
. Here's a simplified example of how you might render the form in a web view:
Copy code
html <form action="{action_url}" method="POST">   <!-- Render other form fields... -->   <input type="submit" name="provider" value="google" /> </form>
Replace
{action_url}
with the actual "action" URL from the response. When the user clicks the "Sign in with Google" button, the form will be submitted with
provider: google
. This will initiate the OpenID Connect flow with Google as the provider. Please note that this is a simplified example and the actual code might be more complex depending on your specific setup and requirements. Sources: - [Understanding UI Nodes and Error Messages](https://www.ory.sh/docs/kratos/concepts/ui-user-interface) - [Bring Your Own UI](https://www.ory.sh/docs/kratos/bring-your-own-ui)
s
@chilly-king-10285 After redirect_browser_to url I got code from return url. How can I get x-session-token from this code?
c
A message from kapa.ai
After you receive the code from the return URL, you can exchange this code for a session token. This is done by making a GET request to the
/sessions/token-exchange
endpoint. Here's an example of how you might structure this request in curl:
Copy code
bash curl -X GET "<http://localhost:4433/sessions/token-exchange?init_code=<init_code>&return_to_code=<return_to_code>>"
Replace
<init_code>
and
<return_to_code>
with the actual codes you received. The response from this request will contain the session token. You can then use this session token to authenticate subsequent requests to Ory. Please note that the exact steps and code will depend on the specific setup and requirements of your application. Sources: - [Exchange the session token exchange code for a session token](https://www.ory.sh/docs/kratos/social-signin/native-apps#steps-12-14-exchange-the-session-token-exchange-code-for-a-session-token) - [Ory Identities API - frontend](https://www.ory.sh/docs/kratos/reference/api)
s
@chilly-king-10285 "error": { "code": 404, "status": "Not Found", "request": "9c8d2c4f-2192-9dd5-b0d3-16aa8fe9d086", "reason": "no session yet for this \"code\"", "message": "The requested resource could not be found" } }
c
A message from kapa.ai
The error message "no session yet for this 'code'" indicates that the session token exchange code you provided does not correspond to an active session. This could happen for a few reasons: 1. The code is incorrect: Make sure you're using the correct code that you received from the return URL. 2. The session has expired: Sessions in Ory Kratos have a limited lifetime and will expire after a certain period of inactivity. If the session has expired, you'll need to initiate a new login flow. 3. The session was not created: If the user did not complete the login process successfully, the session might not have been created. Make sure the user has completed the login process before attempting to exchange the code for a session token. To resolve this issue, you might need to initiate a new login flow and ensure that the user completes the login process successfully. Once you have a new code from the return URL, you can attempt to exchange it for a session token again. Sources: - [Exchange the session token exchange code for a session token](https://www.ory.sh/docs/kratos/social-signin/native-apps#steps-12-14-exchange-the-session-token-exchange-code-for-a-session-token) - [Ory Identities API - frontend](https://www.ory.sh/docs/kratos/reference/api)
s
@chilly-king-10285 session life time?
c
A message from kapa.ai
The session lifetime in Ory Kratos is the duration for which a session remains valid. This duration is defined by the
lifespan
configuration value. When the session lifespan expires, the user must re-authenticate. The session lifespan is expressed in hours, minutes, and seconds. You can use a combination of these units to define the desired lifespan. For example:
72h
,
10m
,
12s
,
1h13m3s
. To change the session lifespan, you can go to the Ory Console, navigate to Session Settings, enter the desired lifespan, and click the Save button. For example, to set the session lifespan to 30 days, you would enter
720h
. You can also change the session lifespan using the Ory CLI by updating the
lifespan
property in the Ory Identities configuration file (
identity-config.yaml
). Here's an example of how to do this:
Copy code
bash ## List all available workspaces   ory list workspaces      ## List all available projects   ory list projects --workspace <workspace-id>      ## Get config   ory get identity-config --project <project-id> --workspace <workspace-id> --format yaml > identity-config.yaml    # Update the configuration value for session lifespan property to the desired value: # config.yml session:   cookie:      domain: $<http://PROJECT_SLUG.projects.oryapis.com|PROJECT_SLUG.projects.oryapis.com>      name: ory_session_{name}      path: /      persistent: false      same_site: Lax   lifespan: 720h    # Update the Ory Identities configuration using the file you worked with: ory update identity-config --project <project-id> --workspace <workspace-id> --file identity-config.yaml
Please replace
<workspace-id>
and
<project-id>
with your actual workspace and project IDs. Sources: - [Session Lifespan](https://www.ory.sh/docs/kratos/session-management/session-lifespan) - [Ory Identities API - frontend](https://www.ory.sh/docs/kratos/reference/api)