Issue with state mismatch on registration using react native app auth - react-native

Im wondering if anyone has some experience in this issue.
I am getting a state mismatch error when trying to register using react native app auth.
React native version: "0.67.3",
React native app auth version: "^6.4.3",
[Error: State mismatch, expecting Z2-6m8_T7FcIlbG9wep3Xb2wvgsylbd9M54iiX97rXs but got Z2-6m8_T7FcIlbG9wep3Xb2wvgsylbd9M54iiX97rXsregistration in authorization response <OIDAuthorizationResponse: 0x6000017b29e0, authorizationCode: 4d890080dde715cedddf076e5ffb4fc8aaeeb22d4ebca281d4c7d74df377607c, state: "Z2-6m8_T7FcIlbG9wep3Xb2wvgsylbd9M54iiX97rXsregistration", accessToken: "(null)", accessTokenExpirationDate: (null), tokenType: (null), idToken: "(null)", scope: "(null)", additionalParameters: {
}, request: <OIDAuthorizationRequest: 0x600001f7c000, request: https://api.staging.com/oauth/authorize?nonce=iJxSOkt6tGToBUndfg3n0V4B_ZZNBIm8TwbTg18EGOo&response_type=code&scope=trusted%20public%20refresh_token&code_challenge=iNlpVkj7UDpXyu5wBlMuln41huSZcGsdWEQ9fYLtcuU&code_challenge_method=S256&redirect_uri=someredirectt&client_id=9dc36c26d21198f5c97f12b34be3cce7a37e5abdc323fcc0b205a898d22994f7&state=Z2-6m8_T7FcIlbG9wep3Xb2wvgsylbd9M54iiX97rXs>>]
the code that generates the request is so:
import { authorize } from 'react-native-app-auth';
const config = {
issuer: TEMP_API,
clientId: OAUTH_PUBLIC_CLIENT_ID,
redirectUrl: OAUTH_CALLBACK_URL,
clientSecret: OAUTH_CLIENT_SECRET,
scopes: ['trusted', 'public', 'refresh_token'],
};
const configForSignup = {
...config,
additionalParameters: {
response_mode: 'query'
},
};
export const authorizeOauthUser = (
{
isSignup,
},
) => async () => {
try {
const oAuthConfig = isSignup ? configForSignup : config;
const result = await authorize(oAuthConfig);
console.log({result});
} catch (error) {
console.log({error})
}
};
I have looked at the following ticket and implemented the suggested response_mode: "query" but to no avail.
Im not quite sure of the 'registration' at the end of the expected token [Z2-6m8_T7FcIlbG9wep3Xb2wvgsylbd9M54iiX97rXsregistration] is appended to the token itself and thats why its mismatching or if its just spaced strangely.

A little bit old but the response mentions explicitly state: "Z2-6m8_T7FcIlbG9wep3Xb2wvgsylbd9M54iiX97rXsregistration"
I guess you are trying to connect to a custom authentication system, you should log that as a bug. The state parameter in the response should exactly match the one from the request.
The state is not the token, it is just a random ID to make sure that the response is received for the right request.

Related

How to login using microsoft account in react-native

I want to log in to my app using a Microsoft account in react native when a "Login with Microsoft" button is clicked.
I had used a component called react-native-msal but I am getting errors (as shown in the below image). Can anyone help me on this code or any other component where I can log in using Microsoft account using react native
My code:
const config: MSALConfiguration = {
auth: {
clientId: (i have written my client id here in my code),
authority: 'https://login.microsoftonline.com/common'
},
};
const scopes = ['openid', 'profile','user.Read'];
const pca = new PublicClientApplication(config);
console.log(pca);
try {
await pca.init();
} catch (error) {
console.error('Error initializing the pca, check your config.', error);
}
const params: MSALInteractiveParams = { scopes };
const result: MSALResult = await pca.acquireToken(params);
Error:
use AzureInstance, AzureLoginView
What the other answer mean with
use AzureInstance, AzureLoginView
is probably the views exported by this package:
https://github.com/shedaltd/react-native-azure-ad-2

cypress-keycloak-commands using on keycloak login

I try to use cypress-keycloak-commands in my tests but always get this error:
I did everything accorig to this docu: https://www.npmjs.com/package/cypress-keycloak-commands
I don't understand how the code should know where to fill in the username an password. This is my code for the login:
it('Login', () => {
cy.visit(Cypress.env('GBS_URL'))
cy.kcLogout();
cy.kcLogin("user");
cy.visit("/"); })
What is the probleme here? I changed the user.json to my setings, added the env: { ... } to the json abd installed the package. Also added:import "cypress-keycloak-commands"; in the commands.js file.
The error comes from the keycloak library, and it's expecting to find a <form> element, but not finding it.
This is the piece of code where the error occurs.
const authBaseUrl = Cypress.env("auth_base_url");
const realm = Cypress.env("auth_realm");
const client_id = Cypress.env("auth_client_id");
cy.request({
url: `${authBaseUrl}/realms/${realm}/protocol/openid-connect/auth`,
followRedirect: false,
qs: {
scope: "openid",
response_type: "code",
approval_prompt: "auto",
redirect_uri: Cypress.config("baseUrl"),
client_id
}
})
.then(response => {
const html = document.createElement("html");
html.innerHTML = response.body;
const form = html.getElementsByTagName("form")[0];
const url = form.action;
The form should be part of the response.body, but since it's not there the request must be failing.
Check what you have in Cypress.env("auth_base_url"), Cypress.env("auth_realm") and Cypress.env("auth_client_id")
If you added them to cypress.json they would be similar to this
Ref Setup Keycloak configuration
Setup the Keycloak configuration in cypress.json configuration file:
{
"env": {
"auth_base_url": "https://auth.server/auth",
"auth_realm": "my_realm",
"auth_client_id": "my_client_id"
}
}

React Native: Google OAuth Invalid parameter value for redirect_uri: Invalid scheme

I have some problems with authentication with Google OAuth2 in my react-native app. I'm using 'expo-auth-session' library for my authentification. I need get access token and then get Youtube profile. But i'm stuck with error "Invalid parameter value for redirect_uri: Invalid scheme"
My scheme in app.json:
"scheme": "com.liga.online"
My code is below:
import {
makeRedirectUri,
useAuthRequest,
ResponseType,
} from "expo-auth-session";
const discoveryYoutube = {
authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth',
tokenEndpoint: 'https://oauth2.googleapis.com/token',
revocationEndpoint: 'https://oauth2.googleapis.com/revoke'
};
/// Inside my React component
const [requestYoutube, responseYoutube, promptAsyncYoutube] = useAuthRequest(
{
responseType: ResponseType.Code,
clientId: YOUTUBE_CLIENT_ID,
scopes: ["https://www.googleapis.com/auth/youtube.readonly"],
redirectUri: makeRedirectUri({
native: "com.liga.online/callback",
}),
},
discoveryYoutube
);
When I press the button, callback is starting
const signInYoutube = async () => {
const response = await promptAsyncYoutube();
console.log(response.data);
}
But I get error
Any idea how I can fix it?
P.S. I tried fix it with library "expo-google-app-auth". I get access token, but when I try to get Youtube profile and get "Request failed with status code 403".
UPDATE 1
By the way about my connection to Youtube Profile.
I change something to get access token.
For example:
import * as Google from 'expo-google-app-auth';
import { startAsync } from 'expo-auth-session';
// Inside my React component
// When I press the button, callback is starting
const signInYoutube = async () => {
const config = {
androidClientId: YOUTUBE_CLIENT_ID
};
const { type, accessToken, user } = await Google.logInAsync(config);
// I need again open my Browser for get Youtube data
const response = await startAsync({
authUrl: `https://www.googleapis.com/youtube/v3/channels?access_token=${accessToken}&part=snippet&mine=true&scope=https://www.googleapis.com/auth/youtube.readonly`,
showInRecents: true
});
console.log(response.data);
}
But I get error
UPDATE 2
I wanted to see which data is loaded from AuthRequest. And I see pretty weird log. Redirect_uri is different from the set.
RESOLUTION
When I add "https://www.googleapis.com/auth/youtube.readonly" in my scopes - i can get profile data. Another words below is my code.
import axios from 'axios';
import * as Google from 'expo-google-app-auth';
// Inside my React component
// Callback function
const signInYoutube = async () => {
const config = {
androidClientId: YOUTUBE_CLIENT_ID,
scopes: ['https://www.googleapis.com/auth/youtube.readonly']
};
const { type, accessToken, user } = await Google.logInAsync(config);
if (type === 'success') {
const response = await axios.get(
`https://www.googleapis.com/youtube/v3/channels?part=id&mine=true&key=${encodeURI(YOUTUBE_API_KEY)}`,
{
headers: {
Authorization: `Bearer ${accessToken}`
}
}
);
setYoutubeData({ accessToken, user, youtubeId: response.data.items[0].id });
}
};
IMPORTANT
Don't remember add in your project Youtube API v3
It looks like your expo environment is using the development redirect URI instead of the native one. Check out these docs for setting up the environment that will give you the native scheme you're looking for: https://docs.expo.io/guides/authentication/#standalone-bare-or-custom
Also make sure that you register your custom scheme with Google: https://developers.google.com/identity/protocols/oauth2/native-app#redirect-uri_custom-scheme
As for your Youtube example, you should be specifying the scopes in the call to Google.loginAsync, not the call to the Youtube API. scopes are requested during the authorization step, and your current authorization request doesn't include any. The relevant docs are here: https://docs.expo.io/versions/latest/sdk/google/#loginasync
REDIRECT URI
Your code looks roughly right though your redirect URI is a private URI scheme and should include a colon character:
com.liga.online:/callback
TRACING MESSAGES
For people to help you with your YouTube profile request you'll need to be able to tell us what is being sent over HTTP/S. Could you try to trace messages as in this write up of mine, then paste the request and response details into your question above

Scopes being ignored by Azure AD with React Native integration

I'm creating an app that login with Azure AD and the same token returned by Azure AD should be used to consume API's.
I've followed all the steps describe at this article with success and it's working.
My problem is about generate the access-token and refresh-token with a custom scope that allows the app to call the api.
I've tried to react-native libraries and each one has a different problem (probably my code has a problem, not the libraries).
First I've tried react-native-azure-auth and when I've defined the following scope:
scope: ['openid', 'profile', 'User.Read', 'offline_access', 'api://multiplan_broker_dev/read']
When defining this scope, it returns a token only valid for the scope api://multiplan_broker_dev/read and doesn't return a refresh_token (seems it's ignoring the offline_access scope)
You can see the whole returned object here and the main code for this implementation here
The main piece of code is below:
const CLIENT_ID = '75a43463-c3b4-4e31-b740-3a5a1858XXXX';
const TENANT_ID = '862085e1-045e-4d8c-832f-96837b0XXXXX';
const azureAuth = new AzureAuth({
clientId: CLIENT_ID,
tenant: TENANT_ID,
});
export default class Auth0Sample extends Component {
constructor(props) {
super(props);
this.state = { accessToken: null, user: '' , mails: [], userId: ''};
}
_onLogin = async () => {
try {
let tokens = await azureAuth.webAuth.authorize({
scope: ['openid', 'profile', 'User.Read', 'offline_access', 'api://multiplan_broker_dev/read'],
login_hint: 'rioa#XXX.com'
})
console.log('CRED>>>', tokens)
this.setState({ accessToken: tokens.accessToken });
let info = await azureAuth.auth.msGraphRequest({token: tokens.accessToken, path: 'me'})
console.log('info', info)
this.setState({ user: info.displayName, userId: tokens.userId })
} catch (error) {
console.log('Error during Azure operation', JSON.stringify(error))
}
};
So I've tried to another library (react-native-app-auth) and it returns the refresh_token, but ignores completely the scopes I'm asking for.
You can see the returned object here and main code here
What I'm doing wrong?
P.S: The solution can be for any library, I don't have preference.
Thanks
The scope is not correct. Your scope contains both Microsoft Graph API endpint and your own api endpoint. As far as I know we can only ask for the token for one resource at one time.
You can change the scope as below:
scope: ['openid', 'offline_access', 'api://multiplan_broker_dev/read']

React-Native Expo app Auth0 login, AuthSession - authURL fails

I'm trying to setup my login to my react native Expo app using AuthSession.
I keep getting this error: ValidationError: child "authUrl" fails because ["authUrl" must be a valid uri]".
The weird thing is, if I console log the URI that is getting passed, copy it, and paste it into a browser, it works! (pulls up the Auth0 login screen as expected).
Why am I getting this error when trying to call it from my Expo client app?
Here's my code:
function toQueryString(params) {
return '?' + Object.entries(params)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
}
class SignInScreen extends React.Component {
logIn = async () => {
const redirectUrl = AuthSession.getRedirectUrl();
console.log(`Redirect URL: ${redirectUrl}`);
// Structure the auth parameters and URL
const queryParams = toQueryString({
client_id: auth0ClientId,
redirect_uri: redirectUrl,
response_type: 'id_token', // id_token will return a JWT token
scope: 'openid profile', // retrieve the user's profile
nonce: 'nonce', // ideally, this will be a random value
});
const authUrl = `${auth0Domain}/authorize` + queryParams;
// Perform the authentication
const response = await AuthSession.startAsync({ authUrl });
console.log('Authentication response', response);
if (response.type === 'success') {
this.handleResponse(response.params);
}
};
handleResponse = (response) => {
if (response.error) {
Alert('Authentication error', response.error_description || 'something went wrong');
return;
}
console.log(response.id_token)
};
I figured this out soon after posting it. Here's what I did to get it to work.
I was using :
const auth0Domain = 'myapp.auth0.com'
I should have been using:
const auth0Domain = 'https://myapp.auth0.com'
UPDATE in addition, be sure to add a scheme to your app.json directly under 'expo', the scheme should be your slug name all lower case, don't forget it has to be all lower case. Also, don't forget that this new app.json cannot be updated OTA and must be submitted to the app store. If you try to use this Auth0 without the updated app.json that includes the scheme, then you will get a safari error saying something like 'safari can't open this page because it's an invalid url' or something like that. When you see this remember this is not a problem with your redirect URL (assuming you're using the boilerplate AuthSession.getRedirectURL() method, and you put that same redirect url into your callback in Auth0 settings). If you did those two things then you are seeing this error because you have not updated your scheme on the app store or test flight build.