OAuth2 Resource Owner Password Grant via API - c#

I am currently building an API which requires OAuth2, but cannot find a library to use that will handle the single sign on in a native mobile app via RESTful API only. Most I've found only have a web popup, which has been vetoed for this project. B2C, which is currently functioning, is not capable of using ROPG. Is there a way to easily set this up with another library using C#.NET and Azure?
UPDATE:
Attempting to use B2C per Fei Xue answer below, we got to the point of getting an access token from Microsoft Graph.
In the body of the POST, we did the following:
resource=https%3A%2F%2FGraph.windows.net&client_id=[B2C Settings -
Applications -
AppId]&grant_type=password&username=rob%40[tenant].onmicrosoft.com&password=[password]&client_secret=[B2C Settings - Applications - App Key - client_secret]
Our error with the namespace was due to the usernames we were trying. This is a B2C tenant using email as the username and that was the reason for the namespace error. The only way we got past that error was to create a B2C user with the email address ending in the tenant, like so:
rob#[tenant].onmicrosoft.com
We are getting an access token now, but that token does not authenticate with our azure app service api app, which was the original goal.
What we are trying to accomplish is to send the username and password that is valid for a B2C signin and get an IdToken or Access Token that is valid for the api app. The api app connects to B2C via App Service Authentication settings configured for AAD with the Client ID and secret setup from the B2C Settings Application.
UPDATE:
Attempting to pass through the graph.windows.net token for authentication in our Azure web api, we added in the https://Graph.windows.net allowed token audience in our App Service – Authentication – Active Directory Authentication configuration.
However, passing the graph access token in the Bearer header to the API still results in
“Authorization has been denied for this request”.
Found out that if we make the Issuer Url blank like in the example below, it now accepts the Graph token!
However, this causes issues when trying to hit
https://[our_web_app].azurewebsites.net/.auth/login/aad
It goes to the common Microsoft login now. Previously it directed to our B2C sign up in policy because the Issuer Url was set to:
https://login.microsoftonline.com/[tenantname].onmicrosoft.com/v2.0/.well-known/openid-configuration?p=[B2C_SignUpIn_Policy]
In fact, if we also pull up the policy from within our app (which was working before removing the Issuer Url) to the sign in policy, we can sign in, but that returned Access Token now always comes back as Unauthorized in the web API calls.
Should the Issuer Url be left blank?
Also, since making the Issuer Url blank, the server takes much longer to respond to API calls when we send a request using a Graph access token in the Header Authorization Bearer. It went from taking about 1-2 seconds (using a valid B2C access token obtained from MSAL or the web login above) to taking about 10-15 seconds to respond that it is an authenticated request. That kind of speed is a show stopper for us. Does validating a graph call in this manner normally take this long?

The feature is now available in preview and works pretty well:
https://learn.microsoft.com/en-us/azure/active-directory-b2c/configure-ropc
Important note: The POST url mentioned in the documentation is wrong.
https://login.microsoftonline.com/{{Aad_Tenant}}/b2c_1_ropc_auth/oauth2/v2.0/
Must be:
https://login.microsoftonline.com/{{Aad_Tenant}}/oauth2/v2.0/token?p=b2c_1_ropc_auth
The calling application must have native client enabled, otherwise you will get this error:
AADB2C90224: Resource owner flow has not been enabled for the application.

The Azure AD B2C has already support the Resource Owner Password Grant flow, you can send the HTTP request like below to using this flow:
POST: https://login.microsoftonline.com/{tenant}/oauth2/token
resource=https%3A%2F%2FGraph.windows.net&client_id={client_id}&grant_type=password&username={userName}&password={password}&client_secret={secret}
Note: this flow only work for the local accounts as social identity providers(Facebook, Google, etc) don't support this.
Update
The token above is acquiring the token for https://graph.windows.net. To pass through the authentication of web API which protect by Azure AD, we need to specify this as the ALLOWED TOKEN AUDIENCES like figure below:

Update to the answer from #AlexAIT.
The URL in the documentation now works for AD B2C.
https://<tenant-name>.b2clogin.com/<tenant-name>.onmicrosoft.com/B2C_1A_ROPC_Auth/oauth2/v2.0/token
https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-ropc-policy?tabs=app-reg-ga&pivots=b2c-user-flow#test-the-ropc-flow
If you get the error:
AADB2C90224: Resource owner flow has not been enabled for the
application
Navigate to application -> Authentication and select Enable the following mobile and desktop flows:.
Wait a few minutes and then it will start to work.
Github thread:
https://github.com/MicrosoftDocs/azure-docs/issues/50330

I work with Rob, and we did finally get the call to work with
https://login.microsoftonline.com/[tenant_ending_in_onmicrosoft.com]/oauth2/token
In the body of the POST, we did the following:
resource=https%3A%2F%2FGraph.windows.net&client_id=[B2C Settings - Applications - AppId]&grant_type=password&username=rob%40[tenant].onmicrosoft.com&password=[password]&client_secret=[B2C Settings - Applications - App Key - client_secret]
Our error with the namespace was due to the usernames we were trying. This is a B2C tenant using email as the username and that was the reason for the namespace error. The only way we got past that error was to create a B2C user with the email address ending in the tenant, like so:
rob#[tenant].onmicrosoft.com.
We are getting an access token now, but that token does not authenticate with our azure app service api app, which was the original goal. What we are trying to accomplish is to send the username and password that is valid for a B2C signin and get an IdToken or Access Token that is valid for the api app. The api app connects to B2C via App Service Authentication settings configured for AAD with the Client ID and secret setup from the B2C Settings Application.
UPDATE:
If I add ?p=[B2C SignUpIn Policy] to the POST, then we get the following error:
AADB2C90224: Resource owner flow has not been enabled for the
application.

Related

Creating a multitenant Azure app - MsalUiRequiredException

A little background:
I have a React SPA connected to a C# Dotnet Server. I am using OAuth with AzureAD as an identity platform.
I am creating an application that can be logged in by anyone with either an Organisation, Microsoft or personal account.
There are no restrictions in the tenant. I have enabled access for all users.
Permissions wise I have made sure all permissions don't require admin consent to allow all users including personal user (e.g xxxx#outlook.com) to sign in.
I have setup the react code to use MSAL to login & generate the token to be used in my API calls. Here is my authConfig.js file:
authConfig.js
NOTE: I am able to successfully login using the tenant admin account. This doesn't cause the error. However, using a newly created outlook account I will get a consent to accept and after that the error still occurs.
THE PROBLEM:
After signing in and fetching the token which are done successfully, when trying to use the token in the authorization header in my API calls it seems to 500 error. Looking at the server console it spits this error message out:
500 Error upon trying to use the generated MSAL token
Has anyone got a clue how to resolve this?

How to get user token silently for Azure DevOps and use it for accessing DevOps REST APIs?

Problem Statement:
I'm trying to create a module in C# console application that I intend to plug and use in Azure Bot once it is operational. I want to connect my bot with Azure DevOps. I am able to do that with PAT token but I need the bot to only display the resources from DevOps on which the logged in user has access.
Attempts:
I am able to get the necessary details using PAT token. It gives me all projects irrespective of the logged in user details.
I have tried to use the Azure AD token for the logged in user but it gives me unauthorized error on trying to use it to invoke Azure DevOps REST APIs
Referred this article but I am unable to get the auth code or token silently.
To summarize, I'm basically looking to:
Obtain a user token for Azure DevOps silently (without user confirming with a click)
Use REST APIs to fetch details like projects, work items etc.
A Personal Access Token inherits the permissions from the user that created it. So if you, as a project collection administrator, create a token, that token has the samwe permissions as you do.
Unfortunately there is no public REST API that you can use to create a token at runtime. They have to be created by a logged in user through the portal.
Another option is using OAuth. OAuth asks the user to login and then gives you a token that you can use in the REST APIs. Unfortunately that doesn't meet your criteria where a user doesn't have to do anything,
The only other way I see is adding the users to the resources they have permissions for. Then from your REST API you can use the admin PAT to check their permissions and then retrieve only what they are allowed to see. Which also isn't really pretty :-(

Getting graph api token using AcquireTokenByUsernamePassword method for a Federated user

I've tried acquiring token using ROPC with the username and password provided by client. But the error message was "parsing_wstrust_response_failed". Same as the error message (last error) described here
From this error message I understood my user is a federated user and cannot use this method. Is there any other way to acquire token for a federated user using username and password?
try
{
result = await app.AcquireTokenByUsernamePassword(scopes,
"joe#contoso.com",
securePassword)
.ExecuteAsync();
}
catch (MsalClientException ex) when (ex.ErrorCode=="parsing_wstrust_response_failed"){
}
No. There is no way.
You need to handle the authentication with another flow.
I mentioned this downside in my recent article: https://joonasw.net/view/ropc-grant-flow-in-azure-ad
First, a warning: You really should not use username/password in your app. In general, it's less secure and increases the risk you're exposing the associated environment to. It is also a brittle approach, as you will likely find Azure AD will require an interactive sign-in at some time in the future--probably at a very inconvenient time for you.
Second, a clarification: AcquireTokenByUsernamePassword will not always use the Resource Owner Password Credentials (ROPC) OAuth 2.0 flow. When MSAL discovers that the user is part of a federated domain name, the library will attempt a non-interactive username/password authentication if the federated identity provider publishes an metadata exchange document which includes an endpoint supporting this method. If this request succeeds, MSAL will then attempt to exchange the response (issued by the federated identity provider) for the normal token set from Azure AD (issued by Azure AD).
So, to answer your question: It depends. It is possible to use AcquireTokenByUsernamePassword with a federated user. However, it requires that the federated identity service support this. AD FS, which is the most common IdP to be federated with Azure AD, supports this is the "usernamemixed" endpoint.
Depending on what you are trying to build you could use the AcquireTokenByIntegratedWindowsAuth() instead. Our scenario was we needed a headless console app to be able to send emails and notifications to a Teams channel. We are also Federated, so username\password auth wouldn't work. But since we are running on on Windows we can use integrated auth.
I followed this guide to get the Access Token: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Integrated-Windows-Authentication
Our scenario did require a one time user consent, so the user the console app runs as had the proper permissions. https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize?client_id={clientId}&response_type=code&scope={scopes}

Getting AccessToken from Azure Ad via UserName & Password

I have a Native Client registered in our Azure AD.
When i'm using
var ar = _context.AcquireToken(resource, clientId, returnUri);
It opens the Prompt for Username and Password. If I enter them correctly I get a valid AccessToken and everything is fine.
When I'm now trying to enter the credentials in code, via UserCrendtial:
var credential = new UserCredential("username", "password");
var ar = _context.AcquireToken(resource, clientId, credential);
But both resulting in an Error when I'm trying it with the directly entered Credentials.
AADSTS65001: No permission to access user information is configured
for '4915f024-blah-blah-blah-f580ab5b0487' application, or it is
expired or revoked.
I have tried the normal (string, string) and the (string, SecureString) overload of the UserCredential.
I have tried it with the exact same combination of username & password, which I have entered in the Prompt, of the first overload from AcquireToken.
I have also tried to give the Application in Azure all the Delegated Permissions:
Read directory data
Read and write directory data
Access your organization's directory
And added Windows Azure Service Management API Application with Permission:
Access Azure Service Management
Nothing helped.
As a sidenote, the Application in the Azure has permissions to a SharePoint O365 Tenant. To Read and Write ListItems I don't know if this is relevant. The Resource i'm passing through is the SharePoint Adress.
I don't need any user access over the Graph Api to the Azure. I only need that AccessToken to access our SharePoint Online.
Edit:
Architecture:
Description:
We have a Web Api Project which handles the User Authorization, Load Balancing etc. This Web Api Project, will be queried by either Native Dekstop Clients or Hybrid HTML5 & Javascript Mobile Device Apps.
The Web Api Project needs to Read, Create, Update & Delete Data from our SharePoint O365 Tenant. So this where I need the AccessToken to init a ClientContext or send i via a rest response.
Since the Web Api handles the User authorization, there is an endpoint for users to login already and in this endpoint I want to acquire the Token. That's why I want it to be silent, because the "flexbile browser popup" is already there.
Maybe I don't need in this scenario the Token acquiring with Username / Password, but then I don't know how to configure the Azure App right to work with all the different native client's.
not sure if it's your case but you can use :
built in auth (setting 'on' in webapp options; then create express app or/and then chose advanced mode with same apps ids);
then add AD native client app;
login to old classic portal there select native app and in config add access to you express/advacsed web app;
after that you will able login in browser; and with adal lib will able login to access you api from mobile devices;
for more see ms docs and samples;
The direct use of username and password has important limitations, please make sure you are not stumbling on any of the ones listed in http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-users-via-usernamepassword/.
Also note, nothing that requires displaying a user consent screen (as all the permissions you described will) or specific disambiguation steps (like trying to use a guest user from X to access a resource protected by tenant Y) will work.
What is your scenario? Any specific reason for which you want to use username/password instead of the more flexible browser popup?

How to get current token from Azure ActiveDirectory application

I have an ASP.NET Application created using the Visual Studio 2013 project template. For security, I chose Azure Active Directory. I have all of the login working, but I'd like to start using the Graph API to manage users in my application. I have created an Application Key to use with Azure AD, but I'm not quite sure how to go about making graph calls.
I've studied the code at https://github.com/AzureADSamples/WebApp-GraphAPI-DotNet, but using the graph API in that way requires a token.
Is there a way to get a token from my ASP.NET application after it has successfully logged into AD that I can use to call the graph API? Maybe by adding a method to Global.asax?
Is there another way to call the graph API from an ASP.NET application created with this project template?
Indeed, you do need an OAuth token using which your web application can access the Graph API, on behalf of the logged in user. If you're using .Net, you are looking at the correct sample - OpenID Connect is the recommended protocol to sign-in the user and get an authorization code to access Graph API: https://github.com/AzureADSamples/WebApp-GraphAPI-DotNet.
The OpenIDConnect (SSO + Auth Code Grant flow) begins when the user clicks Sign-in link. See the _LoginPartial view (https://github.com/AzureADSamples/WebApp-GraphAPI-DotNet/blob/master/WebAppGraphAPI/Views/Shared/_LoginPartial.cshtml) and the SignIn Action in the AccountController.
The main magic happens in Startup.Auth.cs (https://github.com/AzureADSamples/WebApp-GraphAPI-DotNet/blob/master/WebAppGraphAPI/App_Start/Startup.Auth.cs): It configures a delegate on the event AccessCodeReceived to redeem the OAuth Access Code for a Refresh Token and Access Token for the resource (Graph API) and puts the tokens in the token cache.
See AuthUtils class (https://github.com/AzureADSamples/WebApp-GraphAPI-DotNet/blob/master/WebAppGraphAPI/Utils/AuthUtils.cs): The GetAuthToken method first tries to retrieve an access token from the token cache. If the access token and refresh tokens have expired, it re-authenticates the user to populate the token cache with fresh refresh token.
See TokenCacheUtils class (https://github.com/AzureADSamples/WebApp-GraphAPI-DotNet/blob/master/WebAppGraphAPI/Utils/TokenCacheUtils.cs): It calls the AAD token endpoint to get an Access token for the resource (Graph API in your case), using the Refresh token using the code
Hope this helps

Categories