vmurin / react-native-azure-auth Goto Github PK
View Code? Open in Web Editor NEWReact Native library implementing Azure AD OAuth2 API
License: MIT License
React Native library implementing Azure AD OAuth2 API
License: MIT License
Hi! I'm having the following problem:
The first time I sign in to my App with a MS account (registration) it request me to accept the permissions according to the scope declared in azureAuth.webAuth.authorize ({scope: ......});
and I think that it's OK.
The problem appears when I want to sign in again with my MS account, what happens is that every time I want to do this MS request me again to accept the permissions (MS don't remember that I already accept them in the registration) and i think that it's not okay and it is very annoying.
Is this problem related to this library or is it part of the configuration of the application in MS? Did someone have the same problem or know how to fix it?
Thanks
Hi Vmurin,
I have use this plugin for SSO with Microsoft IdToken.
When I logout using
azureAuth.webAuth.clearSession({})
get the success callback.
When I got to login, then app is auto login with older account, it should be take credentials for other account.
Login Code Sample
util.auth.webAuth.authorize({ scope: 'openid profile User.Read' }).then((resp) => {
storage.token.saveToken(resp.rawIdToken, (saved) => {
if (saved) {
me.props.dispatch(loginAction.request({ HTTP_X_MS_TOKEN_GOOGLE_ID_TOKEN: resp.rawIdToken }));
} else {
util.alert({ title: 'Error', message: 'Token Not saved' });
this.props.dispatch(loading({ isLoad: false }));
}
});
}, (err) => {
this.props.dispatch(loading({ isLoad: false }));
util.alert({ title: 'Error', message: err.error_description });
});
})
Logout Code Sample
util.auth.webAuth.logout({}).then((resp) => {
util.navigation.navigate('Login');
});
Custom Util
import AzureAuth from 'react-native-azure-auth';
import consts from './consts';
let util = {
auth: new AzureAuth({
clientId: consts.AzureConfig.client_id,
persistentCache: false
})
}
export default util;
Thanks,
Devesh
Earlier i have used react native msal plugin there i configured with msal identifier. Here if i give my msal identifier in url schemes it is not working.
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleURLSchemes</key>
<array>
<string>msalXXXXXXXXXXXXXXXXXXXXX</string>
</array>
</dict>
</array>
I am getting this error
Application is not configured as a multi-tenant application.Usage of the /common endpoint is not supported for such applications created after 10/15/2018 use a tenant specific endpoint or configure the application to be multi-tenant
I am using the "react-native-azure-auth" library to implement Azure AD V2 login functionality in my react native app for iOS.
Issue 1:
When I call the "acquireTokenSilent" method after the AccessToken had expired, I am getting an error "Invalid Parameter: scope". I checked the source code and found that the parameters are not passed in the right format to the method "refreshTokens". The "refreshTokens" method expects a single object parameter but the "acquireTokenSilent" method invokes it with 2 separate parameters.
Issue 2:
Also, the refreshToken is a property within the refreshToken object returned by the method - "getRefreshToken".
I fixed both these issues by making the below code change locally in the file "auth/index.js". Kindly update the below line in the github repository for the benefit of all who use this library.
Fix :
File : auth/index.js Line: 192
const tokenResponse = await this.refreshTokens({refreshToken: refreshToken.refreshToken, scope: scope})
The library is working fine. The problem is when I came back after login is successful it does not navigate to Dashboard screen. This is my code:
async azureLogin(){
try {
let tokens = await azureAuth.webAuth.authorize({scope: 'openid profile User.Read Mail.Read' })
this.setState({ accessToken: tokens.accessToken });
let info = await azureAuth.auth.msGraphRequest({token: tokens.accessToken, path: '/me'})
this.setState({ user: info.displayName, userId: tokens.userId },()=>{
this.props.navigation.navigate('Dashboard');
})
} catch (error) {
console.log(error)
}
}
Hi @vmurin
Please see screenshot attached. The
The error is caught here: https://github.com/vmurin/react-native-azure-auth/blob/master/src/auth/index.js#L199
When I create a new AzureAuth object I see the following yellowbox warning, although it doesn't seem to be a problem for now.
Module AzureAuth requires main queue setup since it overrides
constantsToExport
but doesn't implementrequiresMainQueueSetup
. In a future release React Native will default to initializing all native modules on a background thread unless explicitly opted-out of.
Hello
On Android 26 after success authtorization the opened brawser is trying to open the next url with parameters
com.name://com.name/android/callback#params
So it doesn't open my app.
How can I fix it?
I'm trying to complete the callback URL registration and failing miserably. :)
In the Microsoft Application Registration Portal, if I put in an Android callback URL per the instructions, I always get "Your changes could not be saved.
One or more added object references already exist for the following modified properties: 'owners'."
If I try any other test URL, I get simply "Your changes could not be saved." and no error details.
Since the MAR portal has a "no longer supported after May 2019" warning at the top, I'm wondering if it's broken / dead.
If I try the new Azure portal and try to enter an Android callback under "Redirect URIs" and then "Public client (mobile & desktop)", the field turns red and it won't allow it to save.
I could be doing something wrong, but I'm wondering if there may be updated instructions.
Thanks!
Is this have to do to with the manifest here:
<data
android:pathPrefix="/android/${applicationId}/callback"
android:scheme="${applicationId}"
/>
I get an error on the manifest which says that one host
must be defined. Which host does it refer to?
Not sure...
Hello,
I've registered on Azure 2 Apps called for example SSO and Web:
Scope for the APP SSO was updated with api://18bXXXX..../user_impersonation (of the Web app)
I try to connect to the API of the App Service using the Client ID of the App SSO and I get: HTTP Error 401.83 - Unauthorized
I use the following method:
let tokens = await azureAuth.webAuth.authorize({scope: 'openid profile User.Read **api://18bXXXX..../user_impersonation** ' })
I successfully got the access token, the rawIdToken, the userId, but, when I try to call my APIs (using Bearer in Authentication header) I receive the above mentioned error.
My function (I removed some lines to keep it simple):
async getActiveProjects(url) { try { let response = await fetch(url, { method: 'GET', headers: { mode: 'no-cors', Accept: 'application/json, image/*;q=0.1', 'Content-Type': 'application/x-www-form-urlencoded', Authorization : 'Bearer ' + this.state.id_token }}); let responseJson = await response.json(); } catch (error) { console.error(error); } }
Thank you
Hi, i'm working on building react-native app with your great library.
There is a warning about async storage that will be remove.
react-native version : 0.59.5
Warning: Async Storage has been extracted from react-native core and will be removed in a future release. It can now be installed and imported from '@react-native-community/async-storage' instead of 'react-native'. See https://github.com/react-native-community/react-native-async-storage
thanks.
Hey there!
I'm having an issue with signing in. I've got the package installed and configured – everything seems good to go with no errors or obvious issues. When I sign in with my Microsoft account and reach this screen, it loads endlessly and doesn't present any errors:
Those blue loading dots at the top scroll across forever. This is after clicking "Personal account" – there is no work/school account, so that flow does not work. I've tried another person's Microsoft account and I get the same result here also. I can also log into my Microsoft account via Safari directly on iOS, and on my computer, without trouble – so I don't think it's something on Microsoft's end.
Any assistance that you can provide would be great! =)
I followed the setup instructions and I'm getting this error
[invalid_grant: AADSTS70000: The provided 'code_verifier' input value does not match the original 'code_challenge.'
Trace ID: 6188a23a-6f74-4b98-a788-7f1928469100
Correlation ID: cd809842-ffbb-4d42-a358-d8c20923b8c8
Timestamp: 2019-10-15 20:21:16Z]
ReactNative: 0.61.2
react-native-azure-auth: 1.2.0
I've noticed on iOS, if you use a 2FA (Microsoft Authenticator) application, when you jump to the 2FA app the browser window that hosted the auth is dead when you return and you get a "Can't end BackgroundTask: no background task exists with identifier 1 (0x1), or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug." error and auth ultimately fails because the page is no longer waiting for the signal to continue.
iOS Callback on Logout in sample app works. But the browser tab on Android does not close on its own and does not invoke the logout callback. Any idea what I am doing wrong?
_onLogout = () => {
azureAuth.webAuth
.clearSession({})
.then(success => {
//This does not get called on Android.
this.setState({ accessToken: null, user: null });
})
.catch(error => console.log(error));
};
После прохождения аутентификации webView переходит по redirectUri и не возвращает в приложение, что может быть не так?
I have checked closed issues related to this question. But I am looking same behaviour that if i do clear session and if i try to do userinteraction login it is not even showing login screen.
On logout i have written this method afterthat i am calling login api
_onLogout = () => {
azureAuth.webAuth
.clearSession({options})
.then(success => {
this.setState({ accessToken: null, user: null });
})
.catch(error => console.log(error));
};
_onLogin = async () => {
try {
let tokens = await azureAuth.webAuth.authorize({scope: 'openid profile User.Read' })
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', error)
}
};
I use launchMode="singleTop" for "react-native-google-signin" and "react-native-firebase".
If I use launchMode="singleTask", those functions can't work.
How can I use this with singleTop launchMode?
Hi!
There is an issue where if the user has successfully signed in on micorsoft – it then not possible to switch to another user - see here the screen on Microsoft page: there is no option here to select a different user
Is there any way to clear the cache so each time the user will be taken to manage users screen? I have tried the azureAuth.webAuth.clearSession()
, but this only seems to clear the token
oferRounds wrote:
I still have a problem @vmurin – at least on my Pixel emulator, on the "showUrl" method, it chooses the CustomTabsIntent path, and after the user insert their credentials, the broswer just remain hanging on the Microsoft page forever... If I remove it – having it choose the "startNewBrowserActivity" path - it works perfect
Tell me please revisions of the following components you are using:
And post if possible the screenshot of "hanging MS page"
Hi,
I'm trying to use the package in iOS, but when I try to build it always crashes with this error 'React/RCTDefines.h'.
I have tried in Android and works fine. However, in iOS I have done the links, and followed the config steps, but It doesn't works.
The error is in the AzureAuth.h file:
/react-native/React/Base/RCTBridgeModule.h:10:9: 'React/RCTDefines.h' file not found
where it tries the import #import "RCTBridgeModule.h"
react: 16.8.3
react-native: 0.59.10
react-native-azure-auth: 1.3.10
Hello,
This is a bug?
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:pathPrefix="/android/${applicationId}/callback"
android:scheme="${applicationId}" />
</intent-filter>
inside of android:pathPrefix="/android/${applicationId}/callback"
should be android:pathPrefix="/${applicationId}/android/callback"
or not and in the documentation is {YOUR_APP_PACKAGE_NAME}://{YOUR_APP_PACKAGE_NAME}/android/callback
?
What is correct?
Hi @vmurin
I see that the library is using AsyncStorage to store to the token, and was wondering, as AsyncStorage does not store data in a secure way, is this a problem?
Was reading this lately: richardkotze.com/coding/send-jwt-client-apollo-graphql#securely-storing-jwt-tokens
Hello, im having a issue with the account type that should be supported by the app.
If I choose for accounts only in this directory, I receive a error when opening the web auth with the unauthorized_client.
Is there a solution/configuration that I should be using that limits the access to only the aplication im registering and not opening to all azure ad?
I am using this plugin for login, i am calling silent login with valid parameters still i am getting this issue
try {
// Try to get cached token or refresh an expired ones
let token = await azureAuth.auth.acquireTokenSilent({userId: tokenUserId,scope: customscope})
if (!token) {
// No cached tokens or the requested scope defines new not yet consented permissions
// Open a window for user interaction
token = await azureAuth.webAuth.authorize({scope: customscope})
return token
}
return token
} catch (error) {
console.log(error)
return error
}
console.error: "Error in silent request: ", Missing required parameters: Missing required parameters: [
"refresh_token"
]
Auth#acquireTokenSilent
index.js:199:20
tryCatch
runtime.js:45:39
invoke
runtime.js:271:21
prototype.method
runtime.js:97:20
tryCatch
runtime.js:45:39
invoke
runtime.js:135:19
Promise.resolve.then$argument_0
runtime.js:145:12
tryCallOne
core.js:37:11
Getting the error: Cannot read property 'bundleIdentifier' of undefined
.
I see that in fact, it does not find the module. I did run the linking.
Do I need to do some package import on the MainApplication
file?
I get stuck on the final part of the login process (see attached image). I've gotten an email from microsoft that tells me that the app is connected to my microsoft account, so it has to be working, right?
The login view doesn't seem to return control back to my app.
I am trying do multiple users login. So first i logged in with some userid after that i logged out. Now i am logged with different userid. After some time if i do logout trying to login again the web url showing two users login ids. If i click on previous user login it is doing successful login. That means previous user login session is not clearing.
I just implemented react-native-azure-auth in my react native project referring react-native-azure-auth-sample and when I tap on the Login button, it says
AADSTS90102: 'redirect_uri' value must be a valid absolute Uri
on login.microsoftonline.com
I searched for a redirect_uri on the example implementation found in react-native-azure-auth-sample. But I did not get anything. Help me, please.
Hi,
My existing backend server does not support jwt token which comes with a 'nonce' header. how can i generate a jwt token without nonce, as the nonce aspect is hard coded into the library, and i can't seem to be able to override them
I integrated this plugin it is working fine in ios and android.In android I am able to run and done successful login. After that i uninstalled the app from emulator and try to run again and clicking on login it is going to silent login.i kept backup= false in android manifest still it is storing token in async storage.
I am trying to make a POST request to add events to outlook calendar.
But msGraphRequest
in azureAuth.auth
can only make get calls.
Is there any other way to do this?
Hi,
I've developed an app (the code is here) but the refresh_token is never returned.
The returned object is here
Using another library (react-native-app-auth) it's returned properly.
What am I doing wrong?
How to login as another user on android?
Azure save account and always login automatically
Hi, I'am trying to login with AD, so I created my app on azure ad portal, configured all steps following the readme.
My application is calling back from auth page when I clicked on Accept button or Sign In button but my react native app receives an error like below image.
Could you help me?
My intent filter is just like this:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:pathPrefix="/android/${applicationId}/callback" android:scheme="${applicationId}" />
</intent-filter>
My applicationId on gradle file is like this:
com.adtest
On Azure Portal my callback url is like this:
com.adtest://com.adtest/android/callback
Best Regards,
Facing a strange issue: on Android, when I tested on Beta (sent via Crashlytics) the SSO worked perfect.
But after submitting it to Google Play, when I download the version, it seems that the callback does not trigger the app launch. The user get stuck after completing the login on the Microsoft page.
Any idea why that might happen?
Any idea what might cause it?
Is there a way to request a specific resource (ie graph.windows.net) so the audience is set on the return token? I noticed the aud in the token is set to a random (???) guid and I cannot validate against that in my services.
I am getting response after successful login after that i am killing my app and try to do silent login it is navigating to user interaction login. Am i doing anything wrong
code:
import AzureAuth from 'react-native-azure-auth';
const options = {
clientId: ‘XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX’,
tenant: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
redirectUri: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX’://auth',
persistentCache:true,
authorityUrl:'https://login.microsoftonline.com/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX’/oauth2/v2.0/'
}
const azureAuth = new AzureAuth(options);
const custom_scope =["XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX’"];
class AzureAuthLogin {
static getToken = async() => {
try {
let token = await azureAuth.webAuth.authorize({scope: custom_scope[0]})
return token
} catch (error) {
console.log(error)
return error
}
}
static getSilentToken = async (tokenUserId) => {
try {
// Try to get cached token or refresh an expired ones
let token = await azureAuth.auth.acquireTokenSilent({ userId: tokenUserId,scope: custom_scope[0]})
if (!token) {
// No cached tokens or the requested scope defines new not yet consented permissions
// Open a window for user interaction
token = await azureAuth.webAuth.authorize({scope: custom_scope[0]})
return token
}
return token
} catch (error) {
console.log(error)
return error
}
}
}
export default AzureAuthLogin;
On ios emulator xcode cant reconnect to application.
After logging in Azure safari throw error:
"Safari cannot open the page because the address is invalid".
And everytime on next boot application throw this error.
InfoPlist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>STENN</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>org.reactjs.native.STENN.$(PRODUCT_NAME:rfc1034identifier)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSLocationWhenInUseUsageDescription</key>
<string/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>None</string>
<key>CFBundleURLName</key>
<string>auth0</string>
<key>CFBundleURLSchemes</key>
<array>
<string>org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)</string>
</array>
</dict>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
<key>UIAppFonts</key>
<array>
<string>Geometria-Bold.ttf</string>
<string>Geometria-BoldItalic.ttf</string>
<string>Geometria-ExtraBold.ttf</string>
<string>Geometria-ExtraBoldItalic.ttf</string>
<string>Geometria-ExtraLight.ttf</string>
<string>Geometria-ExtraLightItalic.ttf</string>
<string>Geometria-Heavy.ttf</string>
<string>Geometria-HeavyItalic.ttf</string>
<string>Geometria-Italic.ttf</string>
<string>Geometria-Light.ttf</string>
<string>Geometria-LightItalic.ttf</string>
<string>Geometria-Medium.ttf</string>
<string>Geometria-MediumItalic.ttf</string>
<string>Geometria-Thin.ttf</string>
<string>Geometria-ThinItalic.ttf</string>
<string>Geometria.ttf</string>
<string>icomoon.ttf</string>
<string>AntDesign.ttf</string>
<string>Entypo.ttf</string>
<string>EvilIcons.ttf</string>
<string>Feather.ttf</string>
<string>FontAwesome.ttf</string>
<string>FontAwesome5_Brands.ttf</string>
<string>FontAwesome5_Regular.ttf</string>
<string>FontAwesome5_Solid.ttf</string>
<string>Foundation.ttf</string>
<string>Ionicons.ttf</string>
<string>MaterialCommunityIcons.ttf</string>
<string>MaterialIcons.ttf</string>
<string>Octicons.ttf</string>
<string>SimpleLineIcons.ttf</string>
<string>Zocial.ttf</string>
</array>
</dict>
</plist>
AppDelegate.m
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "AppDelegate.h"
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import <React/RCTLinkingManager.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
moduleName:@"STENN"
initialProperties:nil];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [UIViewController new];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
return YES;
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
return [RCTLinkingManager application:application openURL:url options:options];
}
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}
@end
There is a way to add params to autorizeUrl like "p=B2C_1_SIGN" to support B2C AD auth?
I'm following along with your tutorial. I am curious if something has changed to the uri callback formation ({YOUR_BUNDLE_IDENTIFIER}://${YOUR_BUNDLE_IDENTIFIER}/ios/callback)? I'm trying to save a new custom uri after adding Platforms/Native Device and it won't let me save. I remove it and I can save - with no real warning as to why. New to react-native. Thanks for helping. -Tori
This package when used with application from personal account works well but when used with owned application gives an error of Unauthorized_Client. How can it be solved please.
Can you show example code how to logout from Azure, not only removing token from AsyncStorage?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.