Forbidden error when calling Microsoft Graph from Java Application using Application ID - azure-active-directory

List SCOPES = Arrays.asList("https://graph.microsoft.com/.default");
final ClientSecretCredential credential = new ClientSecretCredentialBuilder()
.clientId(applicationId)
.clientSecret(secret)
.tenantId(tenantId)
.build();
final TokenCredentialAuthProvider authProvider_new = new TokenCredentialAuthProvider(SCOPES, credential);
GraphServiceClient graphClient = GraphServiceClient
.builder()
.authenticationProvider(authProvider)
.buildClient();
graphClient.users().buildRequest().get();
With
compile group: 'com.microsoft.azure', name: 'azure-spring-boot', version: '2.3.5'
compile group: 'com.google.guava', name: 'guava', version: '28.2-jre'
compile group: 'com.azure', name: 'azure-identity', version: '1.2.5'
compile group: 'com.microsoft.graph', name: 'microsoft-graph', version: '3.5.0'
I've added all the necessary permissions to the application, and it's been consented in Active Directory, but same response.
It works using this code, after I sign in with a user account:
final DeviceCodeCredential credential1 = new DeviceCodeCredentialBuilder()
.clientId(applicationId)
.challengeConsumer(challenge -> System.out.println(challenge.getMessage()))
.build();
But I want to use ClientSecretCredential and use the client secret, not create a challenge.
Update: The error message I get is
SEVERE: Throwable detail: com.microsoft.graph.http.GraphServiceException: Error code: Authorization_RequestDenied
Error message: Insufficient privileges to complete the operation.
GET https://graph.microsoft.com/v1.0/users
SdkVersion : graph-java/v3.5.0
403 : Forbidden
Here's a link of the permissions the app has in API Permissions
I also have the following permissions to Azure Rights Management Services in case it helps
Application.Read.All, Content.DelegatedReader, Content.SuperUser

Based on your granted permission you missed the User.ReadWrite and User.ReadWrite.All Please add that permission .
For more details refer this document:

Related

Access package assignment approval update via MSGraph API returns HTTP 403: Only user tokens are supported

I'm trying to call Access package assignment approval update via MSGraph Beta API (Java 0.51.0-SNAPSHOT). The call fails with following error:
2022-08-26 22:32:44.239 ERROR 10208 --- [nio-9999-exec-4] global : CoreHttpProvider[sendRequestInternal] - 408Graph service exception
2022-08-26 22:32:44.239 ERROR 10208 --- [nio-9999-exec-4] global : Throwable detail: com.microsoft.graph.http.GraphServiceException: Error code:
Error message: Only user tokens are supported
PATCH https://graph.microsoft.com/beta/identityGovernance/entitlementManagement/accessPackageAssignmentApprovals/aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa/steps/bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb
SdkVersion : graph-java/v0.51.0
[...]
403 : Forbidden
[...]
[Some information was truncated for brevity, enable debug logging for more details]
Based on the error message can I think, that Application tokens are not really supported, but the strange thing is, that I can call Access package assignment approval get without any issue. I have of course delegated the permission EntitlementManagement.ReadWrite.All to the Application user.
I tried to reproduce the same in my environment using Graph Explorer and got the below results:
I am able to retrieve the properties of an approval object successfully like this:
GET https://graph.microsoft.com/beta/identityGovernance/entitlementManagement/accessPackageAssignmentApprovals/<id>
Response:
To update those properties, I ran the same query as you like below, and it got updated successfully:
PATCH https://graph.microsoft.com/beta/identityGovernance/entitlementManagement/accessPackageAssignmentApprovals/<id>/steps/<id>
{
"reviewResult": "Approve",
"justification": "Please approve"
}
Response:
Make sure to pass 'Request body' with the PATCH query. Please check whether you are giving correct id's or not in the query.
The <id> before /steps/ in the query is the id of accessPackageAssignmentRequest that is in PendingApproval State.
To get that id, you can run the below query:
GET https://graph.microsoft.com/beta/identityGovernance/entitlementManagement/accessPackageAssignmentRequests?$expand=requestor($expand=connectedOrganization)&$filter=(requestState eq 'PendingApproval')
Response:
The <id> after /steps/ in the query is the step id that I got by running below query:
GET https://graph.microsoft.com/beta/identityGovernance/entitlementManagement/accessPackageAssignmentApprovals/<id_that_you _got_in_above_query>
Response:
UPDATE
Please note that, you cannot update Access package assignment approval using Application permissions. Application permissions are not supported for PATCH query.
You can refer this MsDoc to confirm that like below:
So, it will only work if you login with work or school account(personal-login)

Auth0 getting powerBI token

I am authentocating using Auth0 and my provider is wadd
I am trying to get the token to use with PowerBi, I have tried the follow console app (token, is from the above, clientId and Secret are the same as what is used in my Auth0 connector for the connection to my AzureAD
var cred = new ClientCredential(clientId, secret);
var access_token_from_client_side = token;
var context = new AuthenticationContext("https://login.windows.net/common");
var res = context.AcquireTokenAsync("https://analysis.windows.net/powerbi/api",
functionCred, new UserAssertion(access_token_from_client_side)).ConfigureAwait(false).GetAwaiter().GetResult();
Console.WriteLine(res.AccessToken);
I get the following error
{"error":"invalid_grant","error_description":"AADSTS50013: Assertion failed signature validation. [Reason - The provided signature value did not match the expected signature value., Thumbprint of key used by client: '...', Found key 'Start=12/26/2019 00:00:00, End=12/25/2024 00:00:00']\r\nTrace ID: ...\r\nCorrelation ID: ...\r\nTimestamp: 2020-02-25 21:13:48Z","error_codes":[50013],"timestamp":"2020-02-25 21:13:48Z","trace_id":"...","correlation_id":"b890dfad-1d6f-4e4a-ab15-34328818c295","error_uri":"https://login.microsoftonline.com/error?code=50013"}
My goal is to get a Token to use for PowerBI starting with my AzureAD auth token. I have allow the application permissions for PowerBI from Azure
What am I missing?

error through creating database in plesk by plesklib

I create subdomain in plesk by Install project from Nuget That is in the following link: https://github.com/c1982/plesklib
var client = new PleskClient("IP", "UserName", "Password");
var resultSubdomain = client.CreateSubdomain("subdomain.com","SubDomainName");
but when trying to create database in to the interface for a subdomain that was already present in the interface by this command:
var result= client.CreateDatabase("subdomain.com", "databaseName" ,"databaseType for example:mssql");
the following erro occurs:
Request is invalid. Error in line 5: Element 'webspace-id': '0' is not a valid value of the atomic type 'id_type'.
what is wrong?
Thanks in Advance...

How to configure IdentityServerAuthenticationOptions.Authority to use wildcards

I successfully setup IdentityServer4 with ASP.NET Core.
As a default config I had this:
IdentityServerAuthenticationOptions options = new IdentityServerAuthenticationOptions()
{
Authority = "http://localhost:5000",
ScopeName = "scope",
ScopeSecret = "ScopeSecret",
AutomaticAuthenticate = true,
AutomaticChallenge = true,
RequireHttpsMetadata = false,
};
Now, using this guide I configured to be read from configuration files and so they can be any numbers in production.
For example if I setup API to be running at http://*:5000 then the client can connect to it via the service IP address like http://192.168.1.100:5000.
Once the client obtains the Bearer token and tries to use it, an Internal Server Error occures with this exception:
Unable to obtain configuration from:
'http://*:5000/.well-known/openid-configuration'.
---> System.IO.IOException: IDX10804: Unable to retrieve document from: 'http://*:5000/.well-known/openid-configuration'.
---> System.UriFormatException: Invalid URI: The hostname could not be parsed.
What is the correct way to configure IdS4 to have dynamic authority?
Update
It seems the problem is with Issuer, any idea on this?
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidIssuerException:
IDX10205: Issuer validation failed. Issuer: 'http://192.168.1.100:5000'. Did not match: validationParameters.ValidIssuer: 'http://localhost:5000' or validationParameters.ValidIssuers: 'null'.
at Microsoft.IdentityModel.Tokens.Validators.ValidateIssuer(String issuer, SecurityToken securityToken, TokenValidationParameters validationParameters)
By a big surprise, all I needed, was to set a value (almost any value) for IssuerUri:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
////...
var identiyBuilder = services.AddIdentityServer(options =>
{
options.RequireSsl = false;
options.IssuerUri = "MyCompany";
});
////...
}
Now, by the above config, I can use the service by any IP address.
I didn't find I could just put in MyCompany
But in my log files I had the following:
Bearer was not authenticated. Failure message: IDX10205: Issuer validation failed. Issuer: 'https://crm.example.com'. Did not match: validationParameters.ValidIssuer: 'MyCompany' or validationParameters.ValidIssuers: 'null'.
I don't quite know what 'issuer' means but I was able to just take 'https://crm.example.com' and get things working with this :
options.IssuerUri = "https://crm.example.com";

Interface Between Google Sign-in and MailKit

I am writing an app in WPF (Windows 10 desktop) that should
include a component where the user can download message headers
and messages from G-Mail.
I am trying to use MailKit to interface with G-Mail via a secure
connection (without having to turn on "allow less-secure apps"
for G-Mail) and download messages with POP3. I am a bit confused
as to the proper procedure.
FYI: I know next to nothing about OAuth and TLS, so KISS please.
I have created and downloaded a JSON file for OAuth 2.0 from Google.
I have visited the FAQ for MailKit, and the following section
seems relevant, but I'm not sure as to what I should plug in
to the interface.
(Please see the code below.)
For "password", would that be the password for the account?
I'm not sure as to what to give for
"your-developer-id#developer.gserviceaccount.com".
.........................................................
https://github.com/jstedfast/MailKit/blob/master/FAQ.md#ProtocolLog
.........................................................
From the Q & A:
How can I log in to a GMail account using OAuth 2.0?
The first thing you need to do is follow Google's instructions for
obtaining OAuth 2.0 credentials for your application.
Once you've done that, the easiest way to obtain an access token is to
use Google's Google.Apis.Auth library:
var certificate = new X509Certificate2 (#"C:\path\to\certificate.p12", "password",
X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential (new ServiceAccountCredential
.Initializer ("your-developer-id#developer.gserviceaccount.com") {
// Note: other scopes can be found here: [links]
Scopes = new[] { "https mail google com " },
User = "username#gmail.com"
}.FromCertificate (certificate));
bool result = await credential.RequestAccessTokenAsync (CancellationToken.None);
// Note: result will be true if the access token was received successfully
// Now that you have an access token (credential.Token.AccessToken), you can
// use it with MailKit as if it were the password:
using (var client = new ImapClient ()) {
client.Connect ("imap.gmail.com", 993, true);
// use the access token as the password string
client.Authenticate ("username#gmail.com", credential.Token.AccessToken);
}
My next question: Would the user be able to access their own account(s)
with my app without having to follow the same procedure?
IOW: Will the credentials that I've downloaded work for any account?
... or allow access only to the account from which the credentials
were created?
If the credentials are only good for my own account, then I'll have to
do something else.
Would Google Sign-In be a better approach?
I've downloaded the example code for .NET from Google:
https://github.com/googlesamples/oauth-apps-for-windows
I've built and ran ran "OAuthConsoleApp", as well as "OAuthDesktopApp".
It would seem that I am getting a secure connection from those,
as I have gotten the following output:
.........................................................
redirect URI: http 127.0.0.1:64003
Listening..
Authorization code: qwerty ...
Exchanging code for tokens...
Send the request ...
GetRequestStream ...
await stream.WriteAsync ...
Get the response ...
responseText ...
{
"access_token": "qwerty ...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "qwerty ...",
"id_token": "qwerty ..."
}
Making API Call to Userinfo...
+++ userinfoResponseText : {
"sub": "117108120545711995673",
"name": "My Name",
"given_name": "My",
"family_name": "Name",
"picture": "qwerty ...",
"locale": "en"
}
.....................................................
I see that I have an "access_token" in the response and I thought
that I could plug that in to the "client.Authenticate" method for
MailKit as the password (as mentioned in the docs for MailKit):
string access_token = tokenEndpointDecoded["access_token"];
client.Connect ("pop.gmail.com", 995, SecureSocketOptions.SslOnConnect);
client.Authenticate ("username#gmail.com", access_token);
It threw an exception:
.....................................................
"POP3 server did not respond with a +OK response to the AUTH command."
at MailKit.Net.Pop3.Pop3Client.Authenticate(Encoding encoding,
ICredentials credentials, CancellationToken cancellationToken)
at MailKit.MailService.Authenticate(String userName, String
password, CancellationToken cancellationToken)
at
NS_MailKit_01.Pop3.cls_mailKit_Pop3_01.connect_and_authenticate(Object
p3_client, String p_access_token)
in :\Software_Develpoment_Sys_03_K\MIME_EMail\TEST_02\Mail_Kit_01\MailKit_01.cs:line
465
at
LIB1_01_G_Mail_Auth.cls_G_mail_authorization.str_token_NTRF.invoke_access_token(String
p_access_token)
in K:\Software_Develpoment_Sys_03_K\MIME_EMail\TEST_02\OAuth\oauth-apps-for-windows\OAuthConsoleApp\LIB1_01_G_Mail_Auth\G_Mail_Auth_01.cs:
line 95
at
LIB1_01_G_Mail_Auth.cls_G_mail_authorization.d__13.MoveNext()
in K:\Software_Develpoment_Sys_03_K\MIME_EMail\TEST_02\OAuth\oauth-apps-for-windows\OAuthConsoleApp\LIB1_01_G_Mail_Auth\G_Mail_Auth_01.cs:line
343
.....................................................
Does anyone know how I could get a "credential" object from
the Google interface that I could use with MailKit?
Any help would be appreciated.
Thanks!
For "password", would that be the password for the account?
No. It would be the password for your PKCS12 file containing your X.509 Certificate and your private key.
I'm not sure as to what to give for "your-developer-id#developer.gserviceaccount.com".
You need to register yourself and your application with Google's Developer program which will give you a developer id to use. You need to follow their directions.

Resources