SharePoint 2013 Unauthorized exception for provider-hosted Apps - host

I receive "Unauthorized" exception on the host side for a provider-hosted App for SharePoint 2013.
Uri hostWeb = new Uri(Request.QueryString["SPHostUrl"]);
using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity))
{
clientContext.Load(clientContext.Web, web => web.Title);
clientContext.ExecuteQuery();
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
Certificates were installed, Anonymos access was disabled. I can't understand the reason of this problem.

I have ran into the exact same problem before... i resolved it by implementing OAuth and have it redirect to the app main page with "write" permission.
Response.Redirect(TokenHelper.GetAuthorizationUrl("mysharepoint.com", "Web.Write", "myapp.com/default.aspx"));
Basically what this does is that it'll authentication the login user with your sharepoint site, once it's authenticated, it'll redirect (with write permission) to your app site.
Here is how to implement OAuth: http://msdn.microsoft.com/en-us/library/office/jj687470(v=office.15).aspx

Looks like this is High Trust App. If you have exhausted the tips at http://msdn.microsoft.com/en-us/library/fp179932.aspx, then there is an illformed SPTrustedSecurityTokenIssuer. You can find out all of them using the below PS. Ideally it should be IssuerId#Realm. If there is one which is not, then remove that. But remember not to remove first one which is for workflows
Get-SPTrustedSecurityTokenIssuer | select Name,RegisteredIssuerName

First you have to Check user in 'Request.LogonUserIdentity'. actually this happens when your user does not have access to your site in IIS.
so to set the correct user in 'Request.LogonUserIdentity' follow the below steps:
open your IIS --> Authentication -->Anonymous Authentication --> edit--> Specific user [ User which you get in 'Request.LogonUserIdentity']. --> iisreset
now user have permission to access your IIS site.

Related

Struggling to get Playwright to work with Azure Active Directory Conditional Access

I'm working on standing up a Playwright testing framework around our front-end PHP application to prototype automated testing for our team. Our authentication is managed by Azure Active Directory with 2FA as well as Conditional Access for our devices. The problem I'm encountering is the conditional access not liking the pseudo-incognito Chromium browser used by Playwright. Below is the message I get while attempting my login in the Edge InPrivate window (same error message as Chromium):
I've gone through the authentication section on Playwright's documentation as well as searching, but I'm not having any luck with getting past the conditional access issue. The failing TypeScript code I'm currently running is:
import test from "#playwright/test";
const { chromium } = require('playwright');
test('Log into Application', async () => {
const userDataDir = '\UserData';
const context = await chromium.launchPersistentContext(userDataDir, { headless: false });
const page = await context.newPage();
await page.goto('https://MyApplication.com');
await page.pause();
})
Any help would be deeply appreciated.
According to last bulleted point in Grant controls | Microsoft Docs.
Conditional Access cannot consider Microsoft Edge in InPrivate mode as
a compliant device or an approved client app.
In normal chromium browser (not in private mode ) to work,you need to install and run a supported browser, based on your operating system. If you're using Windows 10, the supported browsers include Microsoft Edge, Internet Explorer, and Google Chrome.If you're using a different operating system, you can check the complete list of supported browsers.
(Or)
The error message may be because the Global admin was created an conditional access policy in the Office 365 tenant at your company due to security reason, so only specific device registered in Azure, will be allowed to use for you. So, in that case you should talk with the "IT HelpDesk" department at your company, and you should ask them to configure and allow all browsers there.
An administrator can make use of access controls to either grant or block access to resources : Grant controls
You may need to contact the admin to raise a support ticket from the Office 365 admin center for further investigation
Reference: Troubleshooting compliance error
If you have global admin rights,You can troubleshoot unexpected
sign-in outcomes related to Conditional Access using error messages
and Azure AD sign-ins log.
You can click on more details and see the information.
Sign in to the Azure portal as a global administrator, security administrator, or global reader
Browse toAzure Active Directory > Sign-ins.
Find the event for the sign-in to review. Add or remove filters .
The Conditional Access tab will show the specific policy or policies that resulted in the sign-in interruption.
You can see and check basic info, device details whether registered or not and other policy details that are not compliant .
For complete details of troubleshooting. Please check this Troubleshooting | Microsoft Docs for complete details of troubleshooting.
Reference:
You Can’t Get There From Here – Vince's Server Stuff (vincecarbone.com)

How to access multiple salesforce orgs with same connected app

I am trying to access the multiple communities in multiple salesforce sites with same connected-app but could not.
For example: I have created the two salesforce sites A and B. And created connected-app in A. To access rest API of A, i could authenticate with connected-app in A, But how to connect with B with using the same client_secret and client_id by differs in user_name and password?
Or is there any way to connect with REST API with username and password as creds?
Example: There is community_A1, community_A2 in Site A and community_B1 , community_B2 in Site B.
I need to access communities in both the Sites
This should work out of the box, what errors you're getting?
You can have 1 set of consumer key and secret and (if admin in target org didn't block it) you could use this to login to any SF in the world, sandbox or production, core SF or community.
Imagine being a developer of mobile app that pulls data from salesforce. You'd want to have just 1 pair of keys, not install separate key for every org people might install your app...
All org-specific stuff you need is username, password and login url. For community the login url will look like https://sandboxName-MyDomain.cs123.force.com/communityName
Once you have that, you can inspect all the OAuth2 stuff at https://sandboxName-MyDomain.cs123.force.com/communityName/.well-known/openid-configuration
Have you played with https://openidconnect.herokuapp.com/ ?
Paste your community url, for now keep the client and secret as is, click next. Login to community and keep clicking next. It should work fine and at the end - give you access_token / session id.
Now close this browser completely / open new incognito window and do it again. This time give your login url but also client and secret. Next, Next... Check the user's login history, it should mention your connected app now.
Now close this and do it last time, with the other community's login url and another user's credentials but still with your client and secret.
is there any way to connect with REST API with username and password
as creds?
Not for community. Internal users can get access in one go with https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_username_password_flow.htm&type=5 but community/experience users need this interactive login, there has to be a human consent / password typing step. And anyway it's not very secure flow. "Experience Cloud sites don’t support the OAuth 2.0 username-password flow."
In a pinch you could try the SOAP API's login method but from what I remember you may need to pass the community's Id in the message then
Connected-app is global metadata in salesforce. Once we create a connected-app in one org, then can access any salesforce site with the same client_id,client_secret, unless the admin has blocked the access.
I needed to add the custom profile into the community members to allow the access to the community via API (Community workspace -> administration -> members -> profiles.)

How to enable "remember me" with Sql Authentication Method ActiveDirectoryInteractive?

Use case: A native(.NET desktop) app that connects to Azure SQL Database using Azure Active Directory authentication.
Since .NET 4.7.2 there is new SqlAuthenticationMethod.ActiveDirectoryInteractive setting for opening a connection to DB. This setting results in a pop-up dialog for sign in, which works well.
E.g. Some documentation example here
Problem: Each time the desktop app is restarted - the sign-in popup appears again, asking for password again, which is frustrating for people who prefer "remember me on this PC" kind of behavior.
Is there a way to enable "remember me" in this scenario ? I didn't find anything in the documentation / web / SO ...
P.S. I assume I can implement it myself if I work with JWT tokens and not with ActiveDirectoryInteractive, but before I do that asking here.
I came across a Token Cache option from here.
Which eventually helps with the problem of sign-in popup upon each restart, due to caching the token.
Get the FilesBasedAdalV3TokenCache class and then provide it when initializing AuthenticationContext:
...
AuthenticationContext authContext = new AuthenticationContext(parameters.Authority, new FilesBasedAdalV3TokenCache(".\\Token.dat"));
...

Unable to use "Query Editor" in developer console

While trying to use the query editor in developer console.
"SELECT ID FROM ACCOUNT"
It throws an erorr saying "This session is not valid for use with the REST API".
Any idea what excatly tthe issue here. Earlier it workerd fine.
The same problem when i click on "Open" dialog of developer console and select objects.
"CANNOT LOAD OBjects.This session is not valid for use with the REST API"
I ran into this same issue, where I could open Visualforce pages, Apex, etc but it would give me the error "This session is not valid for use with the REST API" any time I tried to use the Query Editor or create a new Trigger (which needs the object list) via the Developer Console. I tried every browser, flushing cookies, logging in as other users, etc with the same results.
I found that our org has API white listing enabled (https://help.salesforce.com/HTViewHelpDoc?id=security_control_client_access.htm&language=en_US) which blocks the API calls access unless explicitly granted.
From the Salesforce Documentation
"Contact Salesforce to enable API Client Whitelisting. After it’s enabled, all client access is restricted until explicitly allowed by the administrator. This restriction might block access to applications that your users are already using. Before you enable this feature, you should configure and approve connected apps for any client applications you want users to continue using, or give the users a profile or permission set with “Use Any API Client” enabled."
So adding the "Use Any API Client" permission set to your user profile should fix the issue.
To do this via a Permission Set, you can go to Setup > Users > Permission Sets and create a new one. Add a System Permission of 'Use Any API Client'.
There may be a way to enable API access for the Developer Console via whitelisting or the app settings but I was not able to easily find a way. You would definitely want to test whatever functionality you are creating with a user that does not have that permission enabled.
This is happening because of connected app is not configured correctly.
On 'API (Enable OAuth Settings)' panel, move 'Access and manage your data (api)' option from left to right of Selected OAuth Scopes field and then save the setting.
Wait for few minute and then try. It should work.
Looks like just the session is expired. Did you try to close developer console, relogin to your SF sandbox and open developer console again?
Create a Permission Set, and add a System Permission of 'Use Any API Client'.
And associate this permission set to users. It will solve the problem.

What is the 'sign-on url' in a Windows Azure Active Directory application?

I have configured my first application in Windows Azure Active Directory and everything works fine: I can login using accounts in my directory.
However, I'm not entirely clear on all the concepts yet, especially the sign-on url. The tooltip says:
The URL where users can sign in and use your app. You can change this later.
But users sign in somewhere on login.windows.net and furthermore, it doesn't matter what I enter here, authentication keeps working. So what is this 'sign-on url'?
If you visit http://aka.ms/myapps, you'll find a long list of applications that have access to your account. If you click on these apps, you should be redirected to a home page where the sign-in process could be initialized. However, if the app doesn't declare a signInUrl in its manifest, you'll get an error that says the app is misconfigured.
something went wrong...
You cannot access this application because it has been misconfigured. Contact your IT department and include the following information:
Undefined Sign-On URL for application "BlahBlahBlah"
In the new Azure portal UI, the "SIGN-ON URL" is now called "Home page URL", which you can find under Branding in the app registration configuration.
I can see why this may be confusing. I think you can look at this as the URL where the whole sign-in process starts (i.e. your app's URL, which, if they're not logged in, will sends them to login.windows.net).
Also, even if for now you might be able to enter anything and authentication still works, I'd try to make it point to the right place just in case things change in the future.
It appears to me that It has significance with respect to wsFederation realm value when user sign out and redirected to Active directory sign in page.
When you add your application to azure ad, it gives you client id and key. When you use that in MVC webappp, you will see that there is an entry like below in web.config:
<system.identityModel.services>
<federationConfiguration>
<cookieHandler requireSsl="true" />
<wsFederation passiveRedirectEnabled="true" issuer="https://login.windows.net/{some guid}/wsfed" realm="https://localhost:44304/" requireHttps="true" />
</federationConfiguration>
</system.identityModel.services>
Copy the value of user to sign-on url.

Resources