Auth0 with React-Native results in JWT with no data - reactjs

I have a React-Native application that I am trying to add Auth0 login. So far I have it so it will log in to the app but it is providing a JWT that when I check the jwt.io debugger I get an error message about missing data and the data section is empty. My JWT looks like <string>..<string> when IIRC it should be <string>.<string>.<string> where the middle string that is missing is the data value.
My question is what am I missing that is causing the no data to be in my JWT?
Below is my code with the credentials removed.
// Setup
import Auth0 from 'react-native-auth0'
const auth0 = new Auth0({ domain: '<>', clientId: '<>' })
// Code inside login function
auth0.webAuth
.authorize({
scope: 'openid profile email'
})
.then(credentials => {
// Using this to check the token for the correct format
Alert.alert(credentials.accessToken)
// This is setting it to a global state store where I can access it from elsewhere
globalStorage.set('accessToken', credentials.accessToken)
})
navigation.navigate('list')
Edit**
Here is an example payload/data from a working token I am getting from my Vue.js app
{
"iss": "https://<my domain>.us.auth0.com/",
"sub": "auth0|<user ID>",
"aud": [
"<my audience>",
"https://<my domain>.us.auth0.com/userinfo"
],
"iat": 1661293312,
"exp": 1661379712,
"azp": "<>",
"scope": "openid profile email",
"permissions": [<bunch in here removed for clarity>]
}

Finally figured it out, I needed an audience but it doesn't get added like the package I used with Vue.js but instead gets added to the authorize function. Example code here:
.authorize({
scope: 'openid profile email',
audience: '<>'
})

Related

"Authority mismatch on settings vs. signin state" with OIDC Client when trying to grant access between 2 client Applications

We have two .net core with angular applications where we have used Openid server and client
https://localhost:80 : Parent Application
https://localhost:85 : Child Application
We want to authenticate the child application within the parent application.
In the angular end, we used oidc-client and updated the UserManager dynamically inside the child application.
The flow we are trying to achieve is
Login Page child application (https://localhost:85) -> Click Login -> it redirects to parent app Login Page (https://localhost) -> entering credentials and After successful signing in the redirection URL will be (https://localhost:85) and it will grant access to that child application.
While redirecting to the child application by redirect URL after login it throws the below error "Authority mismatch on settings vs. signin state"
[![enter image description here][1]][1]
Can someone help me with the flow of authentication of multiple client applications via openid client ?
Error: authority mismatch on settings vs. signin state
at t [as _processSigninParams] (oidc-client.min.js:1:57198)
at t [as validateSigninResponse] oidc-client.min.js:1:55646)
at oidc-client.min. js:1:27449 at
ZoneDelegate. invoke (zone, js:372รท26) at Object.onInvoke (core.mjs:26356:33) at
ZoneDelegate. invoke (zone. js:371:52)
at Zone.run (zone. js:134:43)
at zone. js:1275:36 at
ZoneDelegate. invokeTask (zone. js:496:31)
at Object.onInvokeTask (core.mijs:26343:33)
Initially, the child application will have the below config
this.ChildAppConfig = {
authority: 'https://localhost',
client_id: 'child-spa',
redirect_uri: `https://localhost/signin-callback`,
scope: 'profile openid offline_access',
response_type: 'code',
post_logout_redirect_uri: `https://localhost/signout-callback`,
silent_redirect_uri: `https://localhost/silent-renew`,
automaticSilentRenew: false,
revokeAccessTokenOnSignout: true,
accessTokenExpiringNotificationTime: 60,
};
When I want to grant access to a child application via a parent application I will redirect it to the parent application, where the parent application will have the below config, and once authenticated it should redirect back to the child application
grantAccessConfig = {
authority: 'https://localhost:85',
client_id: 'spa',
redirect_uri: `https://localhost/signin-callback`,
scope: 'profile openid offline_access',
response_type: 'code',
post_logout_redirect_uri: `https://localhost/signout-callback`,
silent_redirect_uri: `https://localhost/silent-renew`,
automaticSilentRenew: false,
revokeAccessTokenOnSignout: true,
accessTokenExpiringNotificationTime: 60,
};
Ok i had this error before with Reactjs oidc-react and .net backend. the problem was that the configuration defined in SigninCallBack.js(here i init the storage and redirect) was not same as the configuration defined in identity server. this config was from the test app that throws that error
import React from 'react'
import { WebStorageStateStore } from 'oidc-client-ts';
import { UserManager } from 'oidc-react';
const SigninCallBack = () => {
var config = {
userStore: new WebStorageStateStore({store: window.localStorage}),
authority: "https://localhost:9001/",
client_id: "myappid",
redirect_uri: "https://localhost:3000/signincallback",
client_secret: "thesecretkey_but_i_used_PKCE",
response_type: "code",
scope:"openid profile someApi",
post_logout_redirect_uri : "https://localhost:3000/signout-callback-oidc",
loadUserInfo: true
};
var userManager = new UserManager(config);
userManager.signinCallback().then(res => {
window.location.href = '/';
});
}
export default SigninCallBack;
and mine was the client url which here i was defined with http but in the identityserver config i defined it with https. however it could be any of them such as response type ,client Id etc.

MSAL + Capacitor integration React

I'm trying to integrate MSAL authentication in my app but i can't find a solution to solve the redirectUri value.
This is my config file:
export const msalConfig = {
auth: {
clientId: bundle id,
authority: https://login.microsoftonline.com/{your tenant ID})
redirectUri: ???,
},
cache: {
cacheLocation: 'sessionStorage', // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
};
The app, being a web app, when used on iOS has capacitor://localhost as link so I don't know how to configure it on Azure AD portal.Tried to put capacitor://localhostas redirectUri and different approaches that i found on internet but none of them work.
Redirect URL should follow the format msauth.[Your_Bundle_Id]://auth. For more information take a look to MSAL redirect URI format requirements.

Calling an Azure AD secured Azure Function from React SPA/Azure Static Web App

I'm developing an SPA with React that is hosted as an Azure Static Web App. The App is secured with Azure AD Authentication which works great, I already built a Login that works fine and I can call Azure (Graph) APIs with the token I got and retrieve information for the granted scopes (e.g. user profile picture). To achieve this, I'm using a wrapper called React AAD MSAL which neatly wraps the Microsoft Authentication Library (msal#1.4.0).
So far so good, no problems here. But I'm in need of a backend, of course. I decided to this with Azure Functions, since serverless is the best way for me here. So I made a quick HTTP trigger protoype that runs in Azure as Azure Function und works when I call the URL with the correct paramters.
But of course the Azure Function needs to be secured, so only my React App can call this function. So I thought there should be way to do this through Azure AD, since my user is already logged in as such.
I tried and tried and tried different ways I found online but none of them seem to work or I am doing something wrong.
The general tutorial I tried to follow is this one from MS itself. I tried using the "Express" setting which of course didn't work. I tried the advanced configuration, which also didn't work. The advanced tutorial says you need to have an App registration for the service, I'm not even sure if this is can be my Static Web App or a new on (I tried both with no success). Isn't it enough to tell the Azure Function that it is now AAD secured and may only accept calls from a source secured by an access token that contains the App ID of my app, which is provided in the settings? You can easily provide all these settings, it just doesn't seem to work.
So I'm stalling very early on here. To call the function itself, I first need to get a Authorization Token. According to this tutorial from MS (see "Validate tokens from providers"), I need to send an access token which I got when logging in to my SPA Web App to the Azure Function endpoint ending in .auth/login/aad. Getting this token is easy, since React AAD MSAL provides a method authProvider.getAccessToken() which I can use to extract it. I'm then making a POST request to https://<My Azure Function URI>/.auth/login/aad with the access token in the body as JSON { 'access_token': authToken.accessToken }. I should be getting an Authentication Token which I can then use to call the actual function, but I always get the same response, no matter what I try: You do not have permission to view this directory or page.
So this is where I am. I tried different methods and solutions I found to no avail. Maybe I did something wrong from the ground up, maybe I'm using the wrong methods, I really don't know at this point. Does anyone have experience with this? Is there something wrong in my general approach, do I need to do something else? Or is it just something in the configuration I need to change?
Edit
Since it was asked, here's how I retrieve the token. The concept behind this is using a redux-thunk to dispatch an asynchronous action to the react-redux store. I simplified it not only for this question here but for my testing as well. Right now I'm only trying to get the authentication token and log the answer the POST request is giving me:
import { authProvider } from '../../Authentication/AuthProvider';
//Fetch
async function getAccessToken(authToken) {
const body = { 'access_token': authToken.accessToken };
fetch('https://<My Azure function URL>/.auth/login/aad', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body)
},
).then(response => {
console.log(response);
});
}
export const fetchAddressData = () => async dispatch => {
const token = await authProvider.getAccessToken();
await getAccessToken(token);
// The actual call to the Azure function will go here once we have an Authentication Token
}
The authProvider is a component from react-aad msal and the configuration looks like this:
import { MsalAuthProvider, LoginType } from 'react-aad-msal';
//MSAL Config
const config = {
auth: {
authority: '<Tenant ID>',
clientId: '<Client ID from App registration (Azure Static Web App)>',
redirectUri: window.location.origin
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
// Authentication Parameters
const authenticationParameters = {
scopes: [
'openid',
'user.read',
'https://<Azure Function URI>/user_impersonation'
],
forceRefresh: true
}
// Options
const options = {
loginType: LoginType.Redirect,
tokenRefreshUri: window.location.origin
}
export const authProvider = new MsalAuthProvider(config, authenticationParameters, options)
Edit 2
I tweaked some additional settings trying to work with the user impersonation, still no success. Here's an overview over my current Azure settings that are important for this (did I forget any?).
Azure Function:
Authentication is activated, AAD auth only, advanced settings:
Azure Function - App Registration:
Authentication settings:
Client secret:
Expose an API - Exposing user_impersonation API so the Web App can consume it:
Azure Static Web App (React SPA) - App Registration:
Application URI ID which is used as Token Audience in the Azure Function (advanced authentication setting):
API permissions - using the user_impersonation API which is exposed by the Azure Function App Registration:
Is there anything wrong in this configuration? It mostly likely is, but I don't know what since I followed the tutorial on MSDN. I only added the user_impersonation afterwards since it didn't work.
According to the information provided, you do not configure right scope in your authProvider file. You need to add the scope you define when you create AD application to protect function. So please update the scope as scopes: ["openid","<your function app scope>"] in authProvider.
For example
Create Azure AD application to protect function
Register Azure AD application. After doing that, please copy Application (client) ID and the Directory (tenant) ID
Configure Redirect URI. Select Web and type <app-url>/.auth/login/aad/callback.
Enable Implicit grant flow
Define API scope and copy it
Create client secret.
Enable Azure Active Directory in your App Service app
Create Client AD application to access function
Register application
Enable Implicit grant flow
configure API permissions. Let your client application have permissions to access function
Code
authProvider
import { MsalAuthProvider, LoginType } from "react-aad-msal";
import { Logger, LogLevel } from "msal";
export const authProvider = new MsalAuthProvider(
{
auth: {
authority: "https://login.microsoftonline.com/<tenant>",
clientId: "<>",
postLogoutRedirectUri: window.location.origin,
redirectUri: window.location.origin,
validateAuthority: true,
navigateToLoginRequestUrl: false,
},
system: {
logger: new Logger(
(logLevel, message, containsPii) => {
console.log("[MSAL]", message);
},
{
level: LogLevel.Verbose,
piiLoggingEnabled: false,
}
),
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: true,
},
},
{
scopes: [
"openid",
"<the scope you define for your function>",
],
forceRefresh: true,
},
{
loginType: LoginType.Popup,
tokenRefreshUri: window.location.origin + "/auth.html",
}
);
Call API
const CallAPI= async () => {
// You should should use getAccessToken() to fetch a fresh token before making API calls
const authToken = await provider.getAccessToken();
console.log(authToken.accessToken);
let body = { access_token: authToken.accessToken };
let res = await fetch(
"<your function url>/.auth/login/aad",
{
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
}
);
let data = await res.json();
console.log(data);
body = { name: "Azure" };
res = await fetch("<>", {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
"X-ZUMO-AUTH": data["authenticationToken"],
},
body: JSON.stringify(body),
});
data = await res.text();
console.log(data);
};
I was dealing with the same issue for a while. If your sure you are getting the right access token and and passing it correctly, then look into the configuration in the portal. If you automatically created the app registration for the function app, Check how the ISSUER URL is set up. You can find this in the function app>authentication>edit. make sure that the url does not have /v2.0 at the end. Azure function only work with the default(/v1.0) route.

How to retrieve user info with Azure AD scopes and oidc-client.js?

I'm confused how I can get access tokens and user info details when using azure ad scopes with oidc-client.js.
I have the following scope against my app in the portal...
I then have my user manager settings set up as follows....
var settings: UserManagerSettings = {
authority: `https://login.microsoftonline.com/${tenantId}`,
client_id: clientId,
redirect_uri: "http://localhost:3000/authcallback",
post_logout_redirect_uri: "http://localhost:3000/authcallback",
response_type: "token id_token",
scope: `api://${clientId}/access_user_data openid`,
popup_redirect_uri: "http://localhost:3000/authcallback",
silent_redirect_uri: "http://localhost:3000/authcallback",
automaticSilentRenew: true,
loadUserInfo: true,
metadata: {
userinfo_endpoint: "https://graph.microsoft.com/oidc/userinfo",
authorization_endpoint: `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize`,
issuer: `https://login.microsoftonline.com/${tenantId}/v2.0`,
jwks_uri: `https://login.microsoftonline.com/${tenantId}/discovery/v2.0/keys`
}
};
When I login with signinRedirect I get an access_token returned to my callback, however the call to https://graph.microsoft.com/oidc/userinfo fails with unauthorized when doing getUser().
oidc-client.min.js:1 GET https://graph.microsoft.com/oidc/userinfo 401 (Unauthorized)
The access token does appear to work with my api that requires the api://${clientId}/access_user_data scope.
The discovery document here lists the following available scopes
"scopes_supported": [
"openid",
"profile",
"email",
"offline_access"
]
Which I thought would have worked as I am also including the openid scope. Note that if I only have the openid scope like so scope: "openid", getUser() works, however it doesn't have the scope I need for calling my api.
What am I doing wrong here?
Thanks,
Had the Same issue after some research tried setting loadUserInfo to false that resolved my problem can please try the same

Google redirect_uri with a path not working

I'm using a redirect_uri to choose the page that's opened after Google Authentication. It works fine in dev, but not in production (both are using the same OAuth Client ID). I've added both the localhost and the production links in the Authorized redirect URIs section of the Client ID.
The production error looks like this (I'm replacing my actual domain with test.com). I'm confused because the link in the error matches the link I've added to the Authorized redirect URIs:
Error: redirect_uri_mismatch. The redirect URI in the request,
https://www.test.com/target does not match the ones authorized for the OAuth client.
So this works:
const gapiClientConfig: GapiClientConfig = {
client_id: CLIENT_ID,
discoveryDocs: [ DISCOVERYDOCS ],
scope: [ SCOPES ].join(' '),
ux_mode: 'redirect',
redirect_uri: 'http://localhost:8888/targetPage
};
But this does not:
const gapiClientConfig: GapiClientConfig = {
client_id: CLIENT_ID,
discoveryDocs: [ DISCOVERYDOCS ],
scope: [ SCOPES ].join(' '),
ux_mode: 'redirect',
redirect_uri: 'https://www.test.com/targetPage
};
If I remove the path from the link, it works.
redirect_uri: 'https://www.test.com'
It seems as though the changes to the OAuth client settings in the Google Cloud Console may not take effect immediately. Everything is working now.

Resources