Code Monkey home page Code Monkey logo

active-directory-b2c-ios-swift-native-msal's Introduction

languages page_type description products urlFragment
swift
sample
The MSAL preview library for iOS and macOS gives your app the ability to begin using the Microsoft Cloud by supporting Azure B2C.
azure
azure-active-directory
microsoft-authentication-library-b2c-ios

Microsoft Authentication Library B2C Sample for Apple iOS in Swift

Getting Started Library Docs Support

The MSAL library for iOS and macOS gives your app the ability to begin using the Microsoft identity platform by supporting Azure B2C using industry standard OAuth2 and OpenID Connect. This sample demonstrates all the normal lifecycles your application should experience, including:

  • How to get a token
  • How to refresh a token
  • How to call your backend REST API service
  • How to clear your user from your application

Example

do {
	// Create an instance of MSALPublicClientApplication with proper config
	let authority = try MSALB2CAuthority(url: URL(string: "<your-authority-here>")!)
	let pcaConfig = MSALPublicClientApplicationConfig(clientId: "<your-client-id-here>", redirectUri: nil, authority: authority)
	let application = try MSALPublicClientApplication(configuration: pcaConfig)
            
	let viewController = self /*replace with your main presentation controller here */
	let webViewParameters = MSALWebviewParameters(authPresentationViewController: viewController)
	let interactiveParameters = MSALInteractiveTokenParameters(scopes: ["<enter-your-scope-here>"], webviewParameters: webViewParameters)
            
	application.acquireToken(with: interactiveParameters) { (result, error) in
                
		guard let result = result else {
			print(error!) /* MSAL token acquisition failed, check error information */
			return
                }
                
                let accessToken = result.accessToken
                let account = result.account
                /* MSAL token acquisition succeeded, use access token or check account */
                
	}
}
catch {
	print(error) /* MSALPublicClientApplication creation failed, check error information */
}

App Registration

You will need to have a B2C client application registered with Microsoft. Follow the instructions here. Make sure you make note of your client ID, and the name of the policies you create. Once done, you will need add the redirect URI of msal<your-client-id-here>://auth.

Installation

Load the podfile using cocoapods. This will create a new XCode Workspace you will load.

From terminal navigate to the directory where the podfile is located

$ pod install
...
$ open MSALiOSB2C.xcworkspace

⚠️ Note: If using an ARM-based Mac (M1/M2) then pod install needs to be run in a Rosetta terminal window. For more information follow the instructions here.

Configure your application

  1. Add your application's redirect URI scheme to added in the portal to your info.plist file. It will be in the format of msal<client-id>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>msalyour-client-id-here</string>
            </array>
        </dict>
    </array>
  1. Configure your application defaults

In the ViewControler.swift file, update the variables at the top of this file with the information for your tenant.

    let kTenantName = "fabrikamb2c.onmicrosoft.com" // Your tenant name
    let kAuthorityHostName = "fabrikamb2c.b2clogin.com" // Your authority host name
    let kClientID = "Enter_the_Application_Id_Here" // Your client ID from the portal when you created your application
    let kSignupOrSigninPolicy = "b2c_1_susi" // Your signup and sign-in policy you created in the portal
    let kEditProfilePolicy = "b2c_1_edit_profile" // Your edit policy you created in the portal
    let kResetPasswordPolicy = "b2c_1_reset" // Your reset password policy you created in the portal
    let kGraphURI = "https://fabrikamb2chello.azurewebsites.net/hello" // This is your backend API that you've configured to accept your app's tokens
    let kScopes: [String] = ["https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read"] // This is a scope that you've configured your backend API to look for.

Community Help and Support

We use Stack Overflow to provide support using tag MSAL and tag azure-ad-b2c. We highly recommend you ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.

If you find and bug or have a feature request, please raise the issue on GitHub Issues.

To provide a recommendation, visit our User Voice page.

Contribute

We enthusiastically welcome contributions and feedback. You can clone the repo and start contributing now.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Security Library

This library controls how users sign-in and access services. We recommend you always take the latest version of our library in your app when possible. We use semantic versioning so you can control the risk associated with updating your app. As an example, always downloading the latest minor version number (e.g. x.y.x) ensures you get the latest security and feature enhanements but our API surface remains the same. You can always see the latest version and release notes under the Releases tab of GitHub.

Security Reporting

If you find a security issue with our libraries or services please report it to [email protected] with as much detail as possible. Your submission may be eligible for a bounty through the Microsoft Bounty program. Please do not post security issues to GitHub Issues or any other public site. We will contact you shortly upon receiving the information. We encourage you to get notifications of when security incidents occur by visiting this page and subscribing to Security Advisory Alerts.

Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License (the "License");

active-directory-b2c-ios-swift-native-msal's People

Contributors

antrix1989 avatar brandwe avatar chadhasbrook avatar jasoncoolmax avatar jennyf19 avatar jmprieur avatar johnpiscia avatar juan-arias avatar kengaderdus avatar microsoftopensource avatar mipetriu avatar msftgits avatar oldalton avatar parakhj avatar saeedakhter-msft avatar supernova-eng avatar wham avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

active-directory-b2c-ios-swift-native-msal's Issues

Command PhaseScriptExecution failed with a nonzero exit code

Hi, when trying to archive the app, I am getting this error:

A shell task (/usr/bin/xcrun lipo -remove x86_64 -output /var/folders/gk/yy0jdqss6q9g2cbg50vr77w00000gn/T/TemporaryItems/(A\ Document\ Being\ Saved\ By\ carthage\ 108)/carthage-lipo-zffIFN/MSAL.framework.dSYM/Contents/Resources/DWARF/MSAL /var/folders/gk/yy0jdqss6q9g2cbg50vr77w00000gn/T/TemporaryItems/(A\ Document\ Being\ Saved\ By\ carthage\ 108)/carthage-lipo-zffIFN/MSAL.framework.dSYM/Contents/Resources/DWARF/MSAL) failed with exit code 1:

Showing Recent Messages
fatal error: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/lipo: input file (/var/folders/gk/yy0jdqss6q9g2cbg50vr77w00000gn/T/TemporaryItems/(A Document Being Saved By carthage 108)/carthage-lipo-zffIFN/MSAL.framework.dSYM/Contents/Resources/DWARF/MSAL) must be a fat file when the -remove option is specified

Command PhaseScriptExecution failed with a nonzero exit code

Has anyone been able to surpass this?

Show how you can prepopulate the login screen with username and password

For our UI tests, we are used to entering the username and password for a local test user through code. When your samples use the SFSafariViewController, we are prevented from accessing the contents of these screens.

Until we can find out how to do this, we've got 300 broken UI tests.

Xcode 11.3, iOS.

New user login

  • Not working: Login successfully with one user and then without killing the application and again try to login "Use another account". It will ask for the new email to enter. After entering a new email and click on next. it's automatically getting old signed in account and login with that old account successfully.

  • Working: if I login successfully with one account and kill application then again open the application and go to the option "Use another account". Enter a new email address now it's asking for the password and login with new enter email.

In short why I need to kill application to log in with Use another account.
How can I login with another account without kill the application?
Waiting for the response. Thank you.

Getting Error after hitting Authorize "Could not acquire token

Hi,

Xcode:- 11.3
iOS 13.2.3

I am getting error when I am hitting authorise button with my own created azure tenant id and application on the Azure portal.
Here is the error:-
https://ibotcontrols.b2clogin.com/ibotcontrols.onmicrosoft.com/oauth2/v2.0/authorize?p=B2C_1_0701&client_id=46555959-acc8-4e32-bc82-39645e482495
<MSALB2CAuthority: 0x281066a00>
%@ TID=276726 MSAL 1.0.0 iOS 13.2.3 [2020-01-17 12:49:06] Requiring default broker type due to app being built with iOS 13 SDK
%@ TID=276726 MSAL 1.0.0 iOS 13.2.3 [2020-01-17 12:49:06 - 1C17DF4D-844E-45DB-A867-74AC24D40570] [MSAL] -[MSALPublicClientApplication acquireTokenWithParameters:(
"https://ibotcontrols.onmicrosoft.com/46555959-acc8-4e32-bc82-39645e482495/demo.read"
)
extraScopesToConsent:(null)
account:Masked(null)
loginHint:Masked(null)
promptType:MSALPromptTypeSelectAccount
extraQueryParameters:(null)
authority:<MSALB2CAuthority: 0x281066a00>
webviewType:MSALWebviewTypeDefault
customWebview:No
correlationId:(null)
capabilities:(null)
claimsRequest:(null)]

Could not acquire token: Error Domain=MSALErrorDomain Code=-50000 "(null)" UserInfo={MSALErrorDescriptionKey=Authority validation is not supported for this type of authority, MSALInternalErrorCodeKey=-42008, MSALCorrelationIDKey=1C17DF4D-844E-45DB-A867-74AC24D40570}

@oldalton
@jennyf19

Please help.

Thanks,
Jitender

WKWebView open inside app. asking for re-authentication.

After authenticated with any method, and opening WKWebView (new instance or shared singleton) webview is asking for sign-in.

Is there any way to sign in with the access token without showing sign-in page?

Even with SFSafariViewController and login page set to .default, still is showing sign-in page in SFSafariViewController

Fails to parse userIdentities collection in native client iOS for Azure AD B2C and instead sends empty arrays

When using this sample, the token is not being properly parsed correctly with for the userIdentities collection returned from Azure AD B2C. We confirmed the same policy works OK with a web application as well as a test JWT app (the userIdentities field is populated - confirmed via MS Graph and with a test web app).

The token viewed inline appears to look like:

image

We are seeing this also on the MSAL Android as well - but we are able to repro it on with this sample.

Safari cannot open the page because the address is invalid

Hello, Thank you for the sample.
I'm encountering an issue and was wondering if someone can point me in the right direction.

20201214_132248463_iOS

I've set things up referencing the read me and this post. (#28)
Where would I be able to find out the invalid address?
Would love to dig in a bit more myself to find out what the invalid address is, but not sure where to go aside from debugging the MSAL library itself.

This is the log that shows in the debug console.
%@ TID=282805 MSAL 1.0.0 iOS 14.3 [2020-12-14 13:22:19 - 73701494-1B4E-469D-AD0E-F68CAD810634] [MSAL] Beginning interactive flow. %@ TID=282805 MSAL 1.0.0 iOS 14.3 [2020-12-14 13:22:19 - 73701494-1B4E-469D-AD0E-F68CAD810634] [MSAL] Resolving authority: Masked(not-null), upn: Masked(null) %@ TID=282805 MSAL 1.0.0 iOS 14.3 [2020-12-14 13:22:19 - 73701494-1B4E-469D-AD0E-F68CAD810634] [MSAL] Resolved authority, validated: NO, error: 0 %@ TID=282805 MSAL 1.0.0 iOS 14.3 [2020-12-14 13:22:19] Start background app task with type 0 2020-12-14 08:22:54.738659-0500 MSALiOSB2C[617:282805] [BackgroundTask] Background Task 5 ("Interactive login"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.

acquireTokenSilent method returns every time different token, even before session expire

I'm trying to integrating MSAL into iOS Application using swift code, Followed below steps link:
https://docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-ios#register-your-application
acquireTokenSilent method returns every time different token, even before session expire, as per my understand silent token should new token returns only when session got expired.

Below my code snip:
===============On First time loading =====================================
func initB2CClientApplication(vc:UIViewController) {

    self.viewController = vc
    guard let authorityURL = URL(string:ADB2CStringConstants.kAuthorityURL) else {
        print("Unable to create authority URL")
        return
    }
    do {
        self.mSALB2CAuthority = try MSALB2CAuthority(url: authorityURL)
        let msalConfiguration = MSALPublicClientApplicationConfig(clientId: ADB2CStringConstants.kClientID, redirectUri: ADB2CStringConstants.kRedirectUri, authority: self.mSALB2CAuthority)
        msalConfiguration.knownAuthorities = [self.mSALB2CAuthority]
        
        self.applicationContext = try MSALPublicClientApplication(configuration: msalConfiguration)
        self.initWebViewParams()
        
    } catch  {
        print("Error:\(error)")
    }
}
func initWebViewParams() {
    self.webViewParamaters = MSALWebviewParameters(authPresentationViewController:  self.viewController)
}

### After Login into ADB2C get the account details (verified account details its correct only) and passing to the below method.

func acquireTokenSilently(_ account : MSALAccount!, completionHandler:@escaping MSALAccountResult) {

    **let parameters = MSALSilentTokenParameters(scopes: ADB2CStringConstants.kScopesRead, account: account)**
    **parameters.authority = self.mSALB2CAuthority**
    **self.applicationContext.acquireTokenSilent(with: parameters) { (result, error) in**
        if let error = error {
           // print("Could not acquire token silently: \(error)")
            completionHandler(nil, error)
            return
        }
        guard let result = result else {
           // print("Could not acquire token: No result returned")
            completionHandler(nil, error)
            return
        }
        completionHandler(result, nil)
        **print("SILENT TOKEN:\(result.accessToken)")**
    }
}

====================================================

Xcode 9.3 issue after tapping Login button.

Hi Author,

I downloaded the active-directory-b2c-ios-swift-native-msal as zip.
Once its done, I executed the code with the default configuration values(I did not integrate my configuration values) and I was launched in the Sign-In page.
Since I do not have any account to Sign-In, I went for Sign-Up.
Once I tapped the Create Button/Sign-In button, the application crashed.

Help me in addressing this issue. Thanks

access token issue

"Error Domain=MSALErrorDomain Code=-42105 "(null)" UserInfo={MSALErrorDescriptionKey=Token response is missing the access token"This is the error when i run the code with my credentials .Could you please tell me where is the actual problem.in configuration of AAD b2c or in code side .
Regards,
Subhan Fazal
@brandwe

How to limit scopes for idToken?

I need guidance on how to set the scope for idToken because I do not need access_token.

Currently, the sample requires scope to be set even for an id_token. The empty scope or the scope of openid is not supported either.

let kScopes: [String] = ["https://ultimatetest1.onmicrosoft.com/Read"] // This is a scope that you've configured your backend API to look for.

It would be helpful to get some guidance.

Edit profile Policy ask for login

Hi,
i've successfully login and getting accesstoken but when i tap on edit profile it first ask for login and after login it goes to edit profile
Login -> Get Access Token - > Edit Profile -> Again ask for Login (which is not supposed to , i can login from another user and edit the profile of that user)
i debugged the the code , for edit profile it gets user by policy and i'm getting 2 user sometimes 1
with u_id = b2c_signin & b2c_edit
Any help please ?

Getting Error "Could not acquire token: Error Domain=MSALErrorDomain Code=-50000 "(null)"

Hi Team,

Using Xcode 11.2
macOS Mojave 10.14.5

I clone this "active-directory-b2c-ios-swift-native-msal" and try to run with the same tenant information provided in that its working fine for me.

I create my own azure tenant id and application on the Azure portal and replace the required information(B2C details) as per the mentioned steps for the ios code base.

when i try to run application with new tenant its getting Error "Could not acquire token: Error Domain=MSALErrorDomain Code=-50000 "(null)" UserInfo={MSALErrorDescriptionKey=Failed to start an interactive session, MSALInternalErrorCodeKey=-42008, MSALCorrelationIDKey=C9207A45-6A7D-416B-90E4-93E08F28A637}"

Note: the b2c credentials are working fine for the Xamarin Android app.

So, can you please let me know that is that any platform-specific issue?

Deep Linking on Policy Page removed

Our Azure B2C SignupOrSignin policy pages rendered with MSAL currently removes the href's of mobile deep links, redirect uri's in the form of appName://path, that redirect back to our mobile application. We need this functionality for our mobile application.

We contacted Microsoft about this issue and the response was that we needed a custom domain in order to point to non absolute urls on our policy page. Our team has registered a custom domain for our tenant and are able to see mobile deep links when we view the policy in a web browser.

However, we have not figured out the correct way to instantiate MSAL with our custom domain. You can pass in the custom domain URL as the tenant name and still obtain the token but it appears that the mobile deep links have been removed. Clicking on the links does nothing. I believe that the issue is that the url constructed in the web view starts with the domain of login.microsoft.com instead of our custom domain. How can we correctly obtain tokens and point to this domain?

Sample does not return from acquireToken: Big Sur macOS 11.2.3 (20D91) with XCode12 Version 12.5 (12E262)

Hello,
Having successfully configured this project via the Carthage docs for XCode 12, I have brought up this sample and the initial view displays without issue. When I click Authorize, I see "fabrikamb2c.b2clogin.com" in the webview header and then the webview starts cycling. There is no other logging activity until the termination risk log entry is added. After that entry, I cancel the webview. At this point, logging shows the "User cancelled" error.

  1. msal90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6
    I get this log entry when I use the msal scheme%@ TID=3212045 MSAL 1.1.18 iOS Sim 14.5 [2021-05-04 11:44:36] Encountered error with code -51118, description Masked(not-null)
  2. msauth.com.microsoft.identity.client.sample.MSALiOSB2C
    I do not get any log error when I use this scheme.
  • I have added LSApplicationQueriesSchemes.
  • I have experimented with minimum build versions
  • I have recently upgraded to MSAL 1.1.18 per the swift package option.

My MSAL logs follow.

What are your recommendations on fixing this issue?
Thanks so much!


MSAL logs, as is, no PII filter

%@ TID=3226128 MSAL 1.1.18 iOS Sim 14.5 [2021-05-04 12:07:12] Default app's access group: "Masked(not-null)".
%@ TID=3226128 MSAL 1.1.18 iOS Sim 14.5 [2021-05-04 12:07:12] Using "Masked(not-null)" Team ID.
%@ TID=3226128 MSAL 1.1.18 iOS Sim 14.5 [2021-05-04 12:07:12] Init MSIDKeychainTokenCache with keychainGroup: Masked(not-null)
%@ TID=3226128 MSAL 1.1.18 iOS Sim 14.5 [2021-05-04 12:07:21] Requiring default broker type due to app being built with iOS 13 SDK
%@ TID=3226128 MSAL 1.1.18 iOS Sim 14.5 [2021-05-04 12:07:21 - A321E1FA-C248-4E06-AFB0-57615607ACD0] [MSAL] -[MSALPublicClientApplication acquireTokenWithParameters:(
"https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read"
)
extraScopesToConsent:(null)
account:Masked(null)
loginHint:Masked(null)
promptType:MSALPromptTypeSelectAccount
extraQueryParameters:(null)
authority:<MSALB2CAuthority: 0x600000a85fc0>
webviewType:MSALWebviewTypeDefault
customWebview:No
correlationId:(null)
capabilities:(null)
claimsRequest:(null)]
%@ TID=3226128 MSAL 1.1.18 iOS Sim 14.5 [2021-05-04 12:07:21 - A321E1FA-C248-4E06-AFB0-57615607ACD0] [MSAL] Beginning interactive flow.
%@ TID=3226128 MSAL 1.1.18 iOS Sim 14.5 [2021-05-04 12:07:21] Start background app task with type 0
%@ TID=3226128 MSAL 1.1.18 iOS Sim 14.5 [2021-05-04 12:07:21 - A321E1FA-C248-4E06-AFB0-57615607ACD0] [MSAL] Resolving authority: Masked(not-null), upn: Masked(null)
%@ TID=3226128 MSAL 1.1.18 iOS Sim 14.5 [2021-05-04 12:07:21 - A321E1FA-C248-4E06-AFB0-57615607ACD0] [MSAL] Resolved authority, validated: NO, error: 0
2021-05-04 08:07:56.191044-0400 MSALiOSB2C[35446:3226128] [BackgroundTask] Background Task 1 ("Interactive login"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.
%@ TID=3226128 MSAL 1.1.18 iOS Sim 14.5 [2021-05-04 12:08:02] Creating Error with description: User cancelled the authorization session.
%@ TID=3226128 MSAL 1.1.18 iOS Sim 14.5 [2021-05-04 12:08:02 - A321E1FA-C248-4E06-AFB0-57615607ACD0] [MSAL] Interactive flow finished. Result (null), error: -51700 error domain: MSIDErrorDomain
%@ TID=3226128 MSAL 1.1.18 iOS Sim 14.5 [2021-05-04 12:08:02 - A321E1FA-C248-4E06-AFB0-57615607ACD0] [MSAL] acquireToken returning with error: (MSALErrorDomain, -50005) Masked(not-null)

Getting error while work with xcode 9.3

HI ,

We are trying to integrate the MSAL library with our project but in Xcode 9.3 we are getting lots of error due to syntax changes. Please update the existing repository so anyone can use it with latest. i will try to figure out from my side.

Thanks ,

Question: Intercept Custom WebView Events

Hi!

I am trying to intercept a few WebView events and delegates but none of them seems to be called. Is this by security or there are a few more setups to do? Just to understand if it's a limitation and we cannot do it or if we can keep studying in order to put it to work.

Using a normal WebView opening a website all works, but passing it as a parameter as a custom WebView to MSAL they are not being called.

I need to get some information to natively log into our analytics tool like intercept a few button click methods for instance. I've already done all the setup =/

Tried first with the simple ones which are the WKNavigationDelegate to check if I can intercept the URL's being called, so later I could work with the userContentController and WKScriptMessageHandler to intercept button clicks and events with custom WKUserScript and a jsbridge in the WebView, or if at least we could make the jsbridge to work:

webView?.navigationDelegate = self

....

extension BaseOAuthWebViewController: WKNavigationDelegate {

    webview func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        // code here
    }
}

Thanks in advance!

How to completely logout

Hi Team,

Using Xcode 11.0
MacOS Cataline 10.15

I would like to design a login page with below mentioned criteria.
1- Authorization button.
1.1- On clicking this button, it shall redirect to ask username(email) and password page.
1.2- On providing valid user name and password and clicking generate button, it shall return me with token.
2- Next step, when I press on logout button, it supposed to be redirect it into login page, but it is auto login and displaying my first page.
How sahll I make it to redirect to login page instead of logged in page.

Does the sample follows RFC 8252 OAuth 2.0 for Native Apps

Could you please add to Readme, does the sample follows RFC 8252
OAuth 2.0 for Native Apps
?
“ For authorizing users in native apps, the best current practice is to perform the OAuth authorization request in an external user agent (typically the browser) rather than an embedded user agent (such as one implemented with web-views).”

The same suggestion is for similar sample for android https://github.com/Azure-Samples/ms-identity-android-java#b2cmodefragment-class

The other 2 examples are based on AppAuth library, that explicitly state that It follows the best practices set out in RFC 8252 - OAuth 2.0 for Native Apps

iOS autofill sms code from the keyboard does not work

hi,

with sms input field, if we enter code manually , it works,

But if we tap the code in the top of keyboard (iOS), our form never can be completed.

WhatsApp Image 2020-11-23 at 8 52 14 PM

We cannot modify this field. Can we add button there for complete the sms flow?

Not a B2C Authority. Trying to initialize access token when missing access token field.

I'm trying to setup Google as an identity procider in my Azure B2C AD and pass an access token into my iOS app.

I've mirrored the sample app you've provided, and I've configured my B2C AD according to these tutorials:

https://docs.microsoft.com/en-us/azure/active-directory-b2c/add-native-application?tabs=app-reg-ga
https://docs.microsoft.com/en-us/azure/active-directory-b2c/add-sign-in-policy?pivots=b2c-user-flow
https://docs.microsoft.com/en-us/azure/active-directory-b2c/idp-pass-through-user-flow?pivots=b2c-user-flow

My issue is that the MSAL library fails to initialize the access token in the result of acquireToken(). There is an internal error that isn't handled by the library, the library just logs an error to stdout.

Here is the error log:

TID=2581843 MSAL 1.1.17 iOS Sim 14.4 [2021-05-07 02:09:15] Creating Error with description: It is not B2C authority.
TID=2581843 MSAL 1.1.17 iOS Sim 14.4 [2021-05-07 02:09:15] Trying to initialize access token when missing access token field

Also worth noting. When running the user flow from the Azure portal with the reply URL set to https://jwt.ms, the token is returned successfully from Google Cloud to this page.

I'm not sure why the library is having issues retrieving the access token from the webview into the app.

Thank you for your time. If needed, I can provide code snippets.

Problem with Authentication

Hi :)
I'm new with Azure B2C. I followed the indication on web site (https://docs.microsoft.com/en-us/azure/active-directory-b2c/tutorial-create-tenant) on how to create a azure b2c. Now I wanna implement it in my iOS and Android applications. I started with iOS and with this MSAL library. I followed the readme and I put my tenant fields in example variables.

I have some doubts:

  • What do I have to insert in kGraphURI & kScopes if I haven't any backend REST API?
  • When I run the code the first log is:

Unable to create application Error Domain=MSALErrorDomain Code=-50000 "(null)" UserInfo={MSALErrorDescriptionKey=The required query schemes "msauthv2" and "msauthv3" are not registered in the app's info.plist file. Please add "msauthv2" and "msauthv3" into Info.plist under LSApplicationQueriesSchemes without any whitespaces., MSALInternalErrorCodeKey=-42001}

So I added LSApplicationQueriesSchemes.

  • In console after added the previous info in info.plist show:

%@ TID=2218501 MSAL 1.0.7 iOS Sim 13.3 [2020-02-05 17:40:28] Default app's access group: "Masked(not-null)". %@ TID=2218501 MSAL 1.0.7 iOS Sim 13.3 [2020-02-05 17:40:28] Using "Masked(not-null)" Team ID. %@ TID=2218501 MSAL 1.0.7 iOS Sim 13.3 [2020-02-05 17:40:28] Init MSIDKeychainTokenCache with keychainGroup: Masked(not-null)

Is that correct?

And finally when I tried to authorize, the app open a web view with the correct page I insert the credentials but return NO token and this error:

Could not acquire token: Error Domain=MSALErrorDomain Code=-50000 "(null)" UserInfo={MSALErrorDescriptionKey=Authentication response received without expected accessToken, MSALInternalErrorCodeKey=-42008, MSALCorrelationIDKey=0561E37D-1D5C-4B12-9862-6D9CC4798CB6}

But I think that is caused from some configurations errors.

PS: Is it possible to implement a custom native UI for signup, login ecc... without open a web view? If the answer is YES, how can I find some tutorial o guide?

Thank you very much!!

Safari cannot open the page because the address is invalid

I downloaded the project, configured it according to the documentation. All the values were copied from Azure and match the pattern in the example values.

Added a platform configuration in Azure:
image

Here is the error I am getting:
image

and in the console:

2022-01-23 10:52:40.452041-0500 MSALiOSB2C[40720:4488790] [BackgroundTask] Background Task 1 ("Interactive login"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.

How to configure kScope

Hello,

I'm trying to use this example to use my API, but it seems that I'm unable to determine how to include the kScope into my project.

Currently the app is able to show the login interface, and the user is capable of login, but when the login button is pressed, an error ocurres, that is as follow:

%@ TID=163667 MSAL 1.1.10 iOS 14.3 [2021-01-26 13:58:05 - 4FDAEE00-DB49-4A39-B5B8-FDB88CDF4236] Creating Error with description: Authentication response received without expected accessToken
%@ TID=163667 MSAL 1.1.10 iOS 14.3 [2021-01-26 13:58:05 - 4FDAEE00-DB49-4A39-B5B8-FDB88CDF4236] Unsuccessful token response, error MaskedError(MSIDErrorDomain, -51100)
%@ TID=163667 MSAL 1.1.10 iOS 14.3 [2021-01-26 13:58:05 - 4FDAEE00-DB49-4A39-B5B8-FDB88CDF4236] [MSAL] Interactive flow finished. Result (null), error: -51100 error domain: MSIDErrorDomain

I'm pretty sure that this error comes due to the fact that I'm not adding a kScope into the parameters (currently the kScope is with the default scope - the one that comes as example), but I'm not sure how to configure it. Could anyone explain to me how to configure the kScope?

Not able to acquire token silent

I tried saving account identifier while acquiring token interactively.
Now while getting account using below code does not return account

guard let account = try? application.account(forIdentifier: UserDefaults.standard.string(forKey: Constants.KEY_ACCOUNT)!) else {
                print("not able to get account")
                return
            }

That is needed to create object for MSALSilentTokenParameters which again needs to be sent in function acquireTokenSilent

Can anyone please help me getting this solved. I am tired of implementing ' acquiring token silently '

Documentation and sample not matching

The documentation in the ReadMe file does not match the code of the sample application. While there are similitudes the sample has quite a number of extra steps. Would be great to have coherence between the docs & sample.

The code in the documentation and in the sample are also apparently deprecated, we should be using MSALWebviewParameters(authPresentationViewController: …) instead of MSALWebviewParameters(parentViewController: …)

Authentication response received without expected accessToken

I am trying to run the sample provided to get the token. I have replaced the values as specified in the readme file like client id, Tenant name as per the configuration received while registering the app.

I successfully able to open the page in safari which took input to login (Email/Password). Login was successful but I am receiving below error :
Error Domain=MSALErrorDomain Code=-50000 "(null)" UserInfo={MSALErrorDescriptionKey=Authentication response received without expected accessToken, MSALInternalErrorCodeKey=-42008, MSALCorrelationIDKey=CDCBABDA-856F-482A-96FE-538DC46729E9}
Screenshot 2020-10-09 at 11 23 09

Is the B2C instance running?

I'm trying to implement this in my Swift/iOS application using Xcode 12.5 and iOS 14.5. When I run try running the code against my tenant, I am getting "Safari cannot open the page because the address is invalid." I tried running the sample, but I'm getting a similar error and it appears that the B2C tenant that the sample is using is not running either. Is this sample still valid for using MSAL to authenticate against a B2C tenant?

Sign in with Apple does not work

Hi , Apple requires to support "Sign in with Apple" option to Azure B2C
Then we integrated it
we tested with browser, it's ok,
but got problem when test on application.
Got Stuck at appleid.apple.com
Screen Shot 2020-07-09 at 2 15 00 PM

and no callback in application.acquireToken

Do you have any suggestion?

Thanks

Cannot run sample application

Hi, I read all document but still cannot run demo app with my tenant
always get invalid url when try to authorise.
Please help . thanks
Screenshot 2020-02-15 at 11 08 15 PM

Simulator Screen Shot - iPhone X - 2020-02-15 at 23 11 13

Not able to retrieve silent access token using reset password flow in iOS

we're not able to retrieve silent access token using reset password flow and in our app, we are using 3 authorities as mentioned below code. we're able to retrieve silently access token when we use signup/sign Inflow but not get silent access token when we use reset password flow but it's working in android

I have set up my context object as mentioned below

do {
let signInSignupAuthority = try getAuthority(authorityString: UserDefinedVariable.azureAuthoritySignupSignin.valueFromInfoPlist())

        let passwordChangeAuthority =  try getAuthority(authorityString: UserDefinedVariable.azureAuthorityPasswordChange.valueFromInfoPlist())
        
        let passwordResetAuthority = try  getAuthority(authorityString: UserDefinedVariable.azureAuthorityPasswordReset.valueFromInfoPlist())
        
        let config = MSALPublicClientApplicationConfig(clientId: UserDefinedVariable.azureClientId.valueFromInfoPlist(), redirectUri: nil, authority: signInSignupAuthority)
        config.knownAuthorities = [signInSignupAuthority, passwordChangeAuthority, passwordResetAuthority]
        application = try MSALPublicClientApplication(configuration: config)
    }
    catch {
        
    }

I'm using the below code to acquire tokens silently

if let clientApp = application,
let accountIdentifier = accountIdentifier,
let account = try? application?.account(forIdentifier: accountIdentifier)){
let msalSilentTokenparameters = MSALSilentTokenParameters(scopes: [MSALAuthManager.scope], account: account)
clientApp.acquireTokenSilent(with: msalSilentTokenparameters) { (result, error) in
guard let result = result else { failure(); return }

            success(result.accessToken)
        }
        
    } else {
        failure()
    }

Authorization cycling for webviewType == .wkWebView/.safariViewController

Hello,

I have authorization with MSAL within my project. The problem is the following, that it works fine with webviewType == .default, but it uses ASWebAuthenticationSession, which asks user permission for SSO, I don't have SSO and I just want to get rid of this prompt, the way I found is to set webviewType as wkWebView or safariViewController. But it seems, that, potentially, it requires some additional config, cause when I click even "Cancel" on the webview screen, it closes and opens again automatically.

So my question is how to avoid cycling for .wkWebView/.safariViewController or how to get rid of prompt for ASWebAuthenticationSession

Thanks for your answer

-canOpenURL: failed for URL: "msauthv2://broker"

I'm not able to execute MSAL SDK. I'm getting below mentioned issue while redirecting to SignIn.

My System Configuration :*

  • Mac OS : macOS High Sierra
  • XCode Ver : Version 10.1 (10B61)

Issue :

2020-07-20 19:16:48.965067+0530 qwerty[66144:4049892] -canOpenURL: failed for URL: "msauthv2://broker" - error: "The operation couldn’t be completed. (OSStatus error -10814.)"
2020-07-20 19:16:49.311753+0530 qwerty[66144:4052462] Failed to query AuthBrokerAgent Task <49DC4AA3-FAC7-4268-94DA-41FE68FD584F>.<1>
2020-07-20 19:16:49.313138+0530 qwerty[66144:4052462] CredStore - performQuery - Error copying matching creds.  Error=-25300, query={
    class = inet;
    "m_Limit" = "m_LimitAll";
    ptcl = htsx;
    "r_Attributes" = 1;
    srvr = "intpxy1.hk.hsbc";
    sync = syna;
}
2020-07-20 19:16:49.319596+0530 qwerty[66144:4052462] Failed to get applicable proxy auth Task <49DC4AA3-FAC7-4268-94DA-41FE68FD584F>.<1>
2020-07-20 19:16:49.455326+0530 qwerty[66144:4050095] Task <49DC4AA3-FAC7-4268-94DA-41FE68FD584F>.<1> HTTP load failed (error code: 311 [4:-2097])
2020-07-20 19:16:49.455602+0530 qwerty[66144:4052461] Task <49DC4AA3-FAC7-4268-94DA-41FE68FD584F>.<1> finished with error - code: 311
App error: Error Domain=kCFErrorDomainCFNetwork Code=311 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2097, _kCFStreamErrorDomainKey=4}
2020-07-20 19:18:49.052179+0530 qwerty[66144:4052475] Received XPC error Connection interrupted for message type 3 kCFNetworkAgentXPCMessageTypePACQuery
2020-07-20 19:18:49.052957+0530 qwerty[66144:4052475] Received XPC error Connection invalid for message type 3 kCFNetworkAgentXPCMessageTypePACQuery

Please help me to resolve this issue.

issue_001

Please help me to resolve this issue.

Instructions for App Registration take you to a link for registering web applications, is that correct?

The instructions for App Registration say to "Follow instructions here" which take you to a page to "Tutorial: Register a web application in Azure Active Directory B2C". If I'm creating an iOS application why is the tutorial for registering a web application. Is that correct?

The linked page says:

A "web application" refers to a traditional web application that performs most of the application logic on the server. They may be built using frameworks like ASP.NET Core, Maven (Java), Flask (Python), and Express (Node.js).

There is also another statement:

If you're using a native app instead (e.g. iOS, Android, mobile & desktop), learn how to register a native client application.

Which takes you to Add a native client application to your Azure Active Directory B2C tenant. Do we follow the page referenced in the instructions or follow that link to the native app instructions?

When registering an application, aside from entering a Redirect URI, there is a dropdown for platform which includes:

  • Public client/native (mobile & desktop)
  • Web
  • Single-page application (SPA)

I am trying to build a mobile app, but the instructions say "select Web" and put "https://jwt.ms" in the Redirect URI text box.

For example, in the link from the directions there is a section on Create a client secret where it says:

For a web application, you need to create an application secret. The client secret is also known as an application password. The secret will be used by your application to exchange an authorization code for an access token.

I'm not creating a web application, so this is a little confusing. I will follow them as the instructions say, but it's hard to reconcile the differences. In the App Registration section of the GitHub instructions it says:

Once done, you will need add the redirect URI of msal<your-client-id-here>://auth

but the instructions from the link said to make the Redirect URI, https://jwt.ms

It looks like that didn't work because I get this screen:
image

kgraphURI not accepted

IOS 14.1
SWIFT 5
When SINGUP_SIGNIN_Flow Triggered,
Screen Shot 2020-11-08 at 12 31 45 AM
Screen Shot 2020-11-08 at 12 32 03 AM

'TID=406019 MSAL 1.1.7 iOS Sim 14.1 [2020-11-08 05:27:28 - 920EAB47-CB73-45A3-BA67-C2383BC5F8A6] [MSAL] -[MSALPublicClientApplication acquireTokenWithParameters:(
"https://redacted.onmicrosoft.com/redacted/User.Read"
)
extraScopesToConsent:(null)
account:Masked(null)
loginHint:Masked(null)
promptType:MSALPromptTypeSelectAccount
extraQueryParameters:(null)
authority:<MSALB2CAuthority: 0x600003a8a0e0>
webviewType:MSALWebviewTypeDefault
customWebview:No
correlationId:(null)
capabilities:(null)
claimsRequest:(null)]
%@ TID=406019 MSAL 1.1.7 iOS Sim 14.1 [2020-11-08 05:27:28 - 920EAB47-CB73-45A3-BA67-C2383BC5F8A6] [MSAL] Beginning interactive flow.
TID=406019 MSAL 1.1.7 iOS Sim 14.1 [2020-11-08 05:27:28 - 920EAB47-CB73-45A3-BA67-C2383BC5F8A6] [MSAL] Beginning interactive flow.
%@ TID=406019 MSAL 1.1.7 iOS Sim 14.1 [2020-11-08 05:27:28 - 920EAB47-CB73-45A3-BA67-C2383BC5F8A6] [MSAL] Resolving authority: Masked(not-null), upn: Masked(null)
TID=406019 MSAL 1.1.7 iOS Sim 14.1 [2020-11-08 05:27:28 - 920EAB47-CB73-45A3-BA67-C2383BC5F8A6] [MSAL] Resolving authority: Masked(not-null), upn: Masked(null)
%@ TID=406019 MSAL 1.1.7 iOS Sim 14.1 [2020-11-08 05:27:28 - 920EAB47-CB73-45A3-BA67-C2383BC5F8A6] [MSAL] Resolved authority, validated: NO, error: 0
TID=406019 MSAL 1.1.7 iOS Sim 14.1 [2020-11-08 05:27:28 - 920EAB47-CB73-45A3-BA67-C2383BC5F8A6] [MSAL] Resolved authority, validated: NO, error: 0
%@ TID=406019 MSAL 1.1.7 iOS Sim 14.1 [2020-11-08 05:27:28] Start background app task with type 0
TID=406019 MSAL 1.1.7 iOS Sim 14.1 [2020-11-08 05:27:28] Start background app task with type 0
2020-11-08 00:27:28.626406-0500 oauthtest[16421:406019] Simulator user has requested new graphics quality: 100
2020-11-08 00:28:03.567826-0500 oauthtest[16421:406019] [BackgroundTask] Background Task 1 ("Interactive login"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.

Sample Project - MSALiOSB2C is not working

Hi Author,
I downloaded the active-directory-b2c-ios-swift-native-msal as zip.
After unzipping, I proceeded with the Installation steps specified in Readme.md.
Once its done, I executed the code with the default configuration values(I did not integrate my configuration values) and I was launched in the Sign-In page.
Since I do not have any account to Sign-In, I went for Sign-Up.
Once I tapped the Create Button, the application crashed.

Help me in addressing this issue. Thanks

Getting Error after hitting Authorize "Could not acquire token"

Hi Team,
Using Xcode 11.1
MacOS Cataline 10.15

I clone this "active-directory-b2c-ios-swift-native-msal" and try to run getting Error "Could not acquire token: Error Domain=MSALErrorDomain Code=-50000 "(null)" UserInfo={MSALErrorDescriptionKey=Failed to start an interactive session, MSALInternalErrorCodeKey=-42008, MSALCorrelationIDKey=C9207A45-6A7D-416B-90E4-93E08F28A637}"
After changing B2C details same issue getting .
Please let me know what is issue, Is this issue for Xcode/OS/MSAL version ??

Build fails on XCode 9.3

Build is failing on my environment.

Jonnys-Mac:ADALSample jonny$ git clone https://github.com/Azure-Samples/active-directory-b2c-ios-swift-native-msal.git
Cloning into 'active-directory-b2c-ios-swift-native-msal'...
remote: Counting objects: 145, done.
remote: Total 145 (delta 0), reused 0 (delta 0), pack-reused 145
Receiving objects: 100% (145/145), 36.00 KiB | 341.00 KiB/s, done.
Resolving deltas: 100% (80/80), done.
Jonnys-Mac:ADALSample jonny$ ls
active-directory-b2c-ios-swift-native-msal
Jonnys-Mac:ADALSample jonny$ cd active-directory-b2c-ios-swift-native-msal/
Jonnys-Mac:active-directory-b2c-ios-swift-native-msal jonny$ ls
Cartfile		LICENSE			MSALiOSB2C.xcodeproj
Cartfile.resolved	MSALiOSB2C		README.md
Jonnys-Mac:active-directory-b2c-ios-swift-native-msal jonny$ carthage update
*** Fetching microsoft-authentication-library-for-objc
*** Checking out microsoft-authentication-library-for-objc at "5d8590cbf8edbddcb052433ffd57a46b56b3b398"
*** xcodebuild output can be found in /var/folders/_5/fz2d2r154c5b3ms1_gfmz06r0000gp/T/carthage-xcodebuild.vFCjs4.log
*** Building scheme "MSAL (Mac Framework)" in MSAL.xcworkspace
*** Building scheme "MSAL (iOS Framework)" in MSAL.xcworkspace
Build Failed
	Task failed with exit code 65:
	/usr/bin/xcrun xcodebuild -workspace /Users/jonny/Documents/ADALSample/active-directory-b2c-ios-swift-native-msal/Carthage/Checkouts/microsoft-authentication-library-for-objc/MSAL.xcworkspace -scheme MSAL\ (iOS\ Framework) -configuration Release -derivedDataPath /Users/jonny/Library/Caches/org.carthage.CarthageKit/DerivedData/9.3_9E145/microsoft-authentication-library-for-objc/5d8590cbf8edbddcb052433ffd57a46b56b3b398 -sdk iphoneos ONLY_ACTIVE_ARCH=NO BITCODE_GENERATION_MODE=bitcode CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES archive -archivePath /var/folders/_5/fz2d2r154c5b3ms1_gfmz06r0000gp/T/microsoft-authentication-library-for-objc SKIP_INSTALL=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=NO CLANG_ENABLE_CODE_COVERAGE=NO STRIP_INSTALLED_PRODUCT=NO (launched in /Users/jonny/Documents/ADALSample/active-directory-b2c-ios-swift-native-msal/Carthage/Checkouts/microsoft-authentication-library-for-objc)

This usually indicates that project itself failed to compile. Please check the xcodebuild log for more details: /var/folders/_5/fz2d2r154c5b3ms1_gfmz06r0000gp/T/carthage-xcodebuild.vFCjs4.log

In that log file I find this:

/Users/jonny/Documents/ADALSample/active-directory-b2c-ios-swift-native-msal/Carthage/Checkouts/microsoft-authentication-library-for-objc/MSAL/src/MSALErrorConverter.m:104:154: error: values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead [-Werror,-Wformat]
            MSID_LOG_ERROR(nil, @"MSALErrorConverter could not find the error code mapping entry for domain (%@) + error code (%ld).", msidError.domain, msidError.code);
[carthage-xcodebuild.vFCjs4.log]

Full log file: (https://github.com/Azure-Samples/active-directory-b2c-ios-swift-native-msal/files/1939494/carthage-xcodebuild.vFCjs4.log)

Thanks.

Keychain autofill for sign in

Hi, I have a question, is it possible to somehow implement for MSAL b2c iOS library password storing in Keychain as it works in native applications?

Thanks a lot for you answer

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.