Get a token for the current logged in user, using MSAL.NET - azure-active-directory

I'm trying to get a token for the current logged in user, using MSAL.NET
I'm getting a reference to PublicClientApplication, using the following API:
_clientApp = PublicClientApplicationBuilder.Create(ClientId)
.WithAuthority(AzureCloudInstance.AzurePublic, Tenant)
.WithBroker()
.WithDefaultRedirectUri()
.Build();
Then, later in the code, I'm trying to call AcquireTokenSilent with the following code:
var firstAccount = Microsoft.Identity.Client.PublicClientApplication.OperatingSystemAccount;
authResult = await _clientApp.AcquireTokenSilent(scopes, firstAccount)
The call to AcquireTokenSilent thow an exception, with the following details:
Microsoft.Identity.Client.MsalServiceException
HResult=0x80131500
Message=WAM Error Microsoft.Identity.Client.Platforms.Features.WamBroker.AadPlugin
Error Code: WAM_aad_provider_error_3399614466
Error Message:
WAM Error Message: V2Error: invalid_request AADSTS90002: Tenant '75950cd6-4468-4918-b750-966c6b4fa3d1' not found. Check to make sure you have the correct tenant ID and are signing into the correct cloud. Check with your subscription administrator, this may happen if there are no active subscriptions for the tenant.
Interestingly, the SID '75950cd6-4468-4918-b750-966c6b4fa3d1' is NOT my tenant ID, and actually, I do not have this string anywhere in my code.
In the application registration, I set up the redirect URI to:
ms-appx-web://microsoft.aad.brokerplugin/<my application SID>. The application is registered for domain only, and the my device is domain joined.
What am I doing wrong?
Update
Answer a comment from #Sridevi.
I'm following this demo almost to the letter: https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-windows-desktop
With the following changes:
As a redirect URI, I wrote: ms-appx-web://microsoft.aad.brokerplugin/<client SID>
When building the MSAL application, I added .WithBroker() as mentioned above
For firstAccount, I do not take the first account from the list of acounts as in the tutorial (it is empty the first time), but I'm using the enum OperatingSystemAccount, mentioned above as well.
I would appreciate a sample or tutorial for getting this token otherwise.

Related

Unable to fetch using RoleManagement API endpoints in azure graph-api

I'm trying to use the azure Graph API to fetch the users having a particular role. Code snippet below as how I generated the authToken
AuthenticationContext authenticationContext = new AuthenticationContext(_authString, false);
ClientCredential clientCred = new ClientCredential(_clientId, _clientSecret);
AuthenticationResult authenticationResult;
if (_authenticationResult == null || true == CanAcquireToken)
{
authenticationResult = authenticationContext.AcquireTokenAsync(_resAzureGraphAPI, clientCred).GetAwaiter().GetResult();
_authenticationResult = authenticationResult;
}
return _authenticationResult.AccessToken;
Snapshot of the list of permissions the Graph API has on my application:
GraphAPI permissions on application
I did my reading from https://learn.microsoft.com/en-us/graph/api/rbacapplication-list-roleassignments?view=graph-rest-beta&tabs=http to understand the API endpoint and the required set of permissions for the Graph API on the corresponding appRegistration.
I have provided the graph API with required permission set on the application which is under review.
However, the API request to
https://graph.microsoft.com/{{beta}}/roleManagement/directory/roleAssignments?$filter=roleDefinitionId eq '{{roleDefnId-Guid}}'
always keeps failing with the error details
Access token validation failure. Invalid audience
Note: The generated auth token is successfully fetching me info from "https://learn.microsoft.com/en-us/graph/api/approleassignment-get?view=graph-rest-beta&tabs=http" mentioned calls
The permission of your app is correct, Directory.ReadWrite.All application permission is enough. I also test your code, it works fine.
Make sure the _resAzureGraphAPI in your code is https://graph.microsoft.com (just confirm it again, I know if it is wrong, you will not be able to call the api in your Note). I can just reproduce your issue with a wrong one, e.g. https://graph.windows.net.
If the _resAzureGraphAPI is correct, decode your token in https://jwt.io/, see it is the same as below.

invalid_grant error when obtaining access token

I am trying to build a website where a user can log in via Azure AD B2C. After logging in, I'm trying to present a secure area where the user can change their Azure B2C user attributes (first name, last name, etc) via the Microsoft Graph API.
I am attempting to follow along with the Get a Token documentation
Everything is working up to step #3, where a call gets made out to https://login.microsoftonline.com/common/oauth2/v2.0/token to obtain an access_token using the code I received on my return URL.
Here's the general flow of what I am doing:
End user clicks a login link on my localhost site that links out to my Azure B2C tenant policy. Link looks something like this:
https://login.microsoftonline.com/mytenantname.onmicrosoft.com/oauth2/v2.0/authorize
?client_id=[MyAppID]
&response_type=code+id_token
&redirect_uri=http%3A%2F%2Flocalhost%3A17000%2Fprocessing%2Findex
&response_mode=query
&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.write
&state=[MyCustomState]&p=[MyCustomPolicy]
User logs in and gets redirected to the redirect_uri.
redirect_uri successfully recieves code, id_token, and state values.
I take the code value from that and makes a POST https://login.microsoftonline.com/common/oauth2/v2.0/token request with the following body:
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
HTTP/1.1
grant_type=authorization_code
&code=[code]
&client_secret=[application secret]
&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.readwrite
&redirect_uri=http%3A%2F%2Flocalhost%3A17000%2Fprocessing%2Findex
The response code I receive back from that endpoint is the above error message.
{
"error": "invalid_grant",
"error_description": "AADSTS9002313: Invalid request. Request is malformed or invalid.\r\nTrace ID:6d7a8e32-bcbf-4fc4-a37a-87dae4781b00\r\nCorrelation ID:252912b7-5775-491a-968f-00ab03696dd9\r\nTimestamp: 2019-06-2722:11:18Z",
"error_codes": [9002313],
"timestamp": "2019-06-27 22:11:18Z",
"trace_id": "6d7a8e32-bcbf-4fc4-a37a-87dae4781b00",
"correlation_id": "252912b7-5775-491a-968f-00ab03696dd9"
}
Other StackOverflow posts mention verifying that the redirect_uri's have to match between the initial login and the subsequent access_token requests. They appear identical to me, but I am still receiving errors.
Any ideas what could be going wrong?
This is something you need to understand about OAuth on B2C before you are able to successfully request for a token.
This error means that the requested scope (resource) can’t be accessed by you (login user) because of the lack of permissions.
So, to fix that, you need to grant these required permissions to access that resource, by following these steps:
Define a new scope.
Grant Admin consent on that scope.
Request that scope when you request for a token.
In other words, in B2C-->App Registrations--> (Your App), shown in the image below, start with “Expose an API”, here you define a new scope of access, scope of resources or API, just a metadata that you know it represents some resources or API.
Then you click on “API Permissions”, here you will add the scope you just created and grand admin access in needed. But al least you need to add permissions to your newly defined scope.
The third and last step is when you hit: https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/{policy}/oauth2/v2.0/token
Make sure to pass the scope that you added. (Use the scope that you added)
The details are explained in here but I can simplify it for you.
configure b2c
So you need to go to your B2C
Seems you are trying to get access token using Authorization Code Grant V2.0
Your request doesn't match with Authorization Code Grant V2.0 format and you have encountered that error.
You should send token request for Authorization Code Grant V2.0 is like below:
Token Endpoint: `https://login.microsoftonline.com/common/oauth2/v2.0/token`
client_id:b603c7be-_YourApp_ID-e6921e61f925
scope:https://graph.microsoft.com/User.ReadWrite.All
redirect_uri:https://www.getpostman.com/oauth2/callback
grant_type:authorization_code
client_secret:Vxf1SluKbgu4P_YourAppSecret_DSeZ8wL/Yp8ns4sc=
code:OAQABAAIAAADCoMpjJXrxTq9VG9te-7FXrnBIp82sWR1nC
See Screen shot for details:

Keycloak delete user give me an 401 Unauthorized error

I am trying to delete a user from a realm using keycloak admin client api.
I am following an example from here:
https://gist.github.com/thomasdarimont/43689aefb37540624e35
Here is what my code looks like:
Keycloak kc = KeycloakBuilder.builder().serverUrl("https://localhost:8445/auth")
.realm("sensorcloud-auth").username("admin").password("admin").clientId("admin-cli")
.clientSecret("b6b4f0ec-9936-46a2-9f40-69c207e2e0f2")
.resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build()).build();
kc.realm("sensorcloud-auth").users().get("a3fdac49-f7eb-4be7-a81f-b48b09a6694c").remove();
I can login to keycloak admin console using username admin and password admin, and I am pretty sure there is no typo with other parameters, but every time when I try to delete the user with that userId, I will be given a 401 Unauthorized error. Can someone help me figure out what is going on?
Not sure which version of keycloak admin client api you are using, with current API there is no remove operation.
It should be kc.realm(realmName).users().delete(id) . You can check the REST API for Delete User
We kept getting HTTP 401 status code responses when the hostname stamped on the iss field of the bearer's/user's access token had a different case i.e. lowercase vs. uppercase than the url used to post an HTTP request to keycloak's token endpoint.
While creating Keycloak instance, Realm should be master realm.
After creating instance with Master Realm, you can delete the user by using your code.

DocuSign Rest API login issue

I get JSON response {"errorCode": "USER_DOES_NOT_BELONG_TO_SPECIFIED_ACCOUNT", "message": "The specified User is not a member of the specified Account."} when we deployed application on a new SF sandbox with a different DocuSign account. Obviously I have changed the user/password and integration key for the new account. And after I make token request I get access token back, but I can not make post request due to above.
Can you guys help me understand why is this?
Users who want to send documents need a DocuSign account. It sounds like you've changed the username and password credentials however it is still pointing to the previous account hence the error. To resolve you need to update the integration to point to the new account.

The user or administrator has not consented to use the application with ID '<APPID>'

We started having this problem shortly after we started using DYN365O Update 3. Our code worked for a while then one day in mid-January stopped working. We have a ticket into Microsoft but was hoping someone has found a workaround. The following error happens when our code tries to connect:
Response Code (1004) {"error":"AADSTS65001: The user or administrator
has not consented to use the application with ID ''. Send an
interactive authorization request for this user and resource.\r\nTrace
ID: d1775f71-ac60-4d12-ace5-39b52452a5c7\r\nCorrelation ID:
38e3b5c6-52c2-4ea9-9ad1-67230e246b40\r\nTimestamp: 2017-01-29
21:42:43Z"}
I was able to use the code here (https://github.com/Microsoft/Dynamics-AX-Integration) to recreate the problem. Here is the relevant section:
string aadTenant = ClientConfiguration.Default.ActiveDirectoryTenant;
string aadClientAppId = ClientConfiguration.Default.ActiveDirectoryClientAppId;
string aadResource = ClientConfiguration.Default.ActiveDirectoryResource;
AuthenticationContext authenticationContext = new AuthenticationContext(aadTenant);
// OAuth through username and password.
string username = ClientConfiguration.Default.UserName;
string password = ClientConfiguration.Default.Password;
// Get token object
var userCredential = new UserPasswordCredential(username, password);
AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(
aadResource,
aadClientAppId,
userCredential).Result;
When pointing to our Update 2 (August Update) DYN365O instance
everything works perfectly.
Changing the URI to point to Update3 we begin to see these errors.
I have searched the internet and I have done everything suggested including:
Setting oauth2AllowImplicitFlow = true in the manifest for the Azure
App.
Under permissions for the APP in AAD I have used the Grant
Permissions to "grant permissions for all accounts in the
directory".
Altering the call to AcquireTokenAsync to include
"prompt=admin_consent". I am presented with the prompt screen but
even after entering the AAD admin userid/password I get the same
error.
Tried other users for 3.
Verified that the user in DYN365O (under System Administration >>
Users) is identical in both our Update2 and Update3 instances and is
a System Administrator.

Resources