Azure Enterprise App Registration - Certificate Based Authentication with JWT Assertion - azure

Referred Azure Article URL : https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-certificate-credentials
Problem statement : Followed steps as per the above mentioned article, but getting error like as below
Postman Request
Payload
Method : POST
URL : https://login.microsoftonline.com/{tenantId}/oauth2/token
x-www-form-urlencoded :
client_assertion_type : urn:ietf:params:oauth:client-assertion-type:jwt-bearer
client_assertion : { JWT Token }
tenant : XXXXXXXXXXXXXXXXXXXXXXXXXXX
client_id : XXXXXXXXXXXXXXXXXXXXXXXXXXX
grant_type : client_credentials
Postman Response
{
"error": "invalid_client",
"error_description": "AADSTS700027: Client assertion contains an invalid signature. [Reason - The provided signature value did not match the expected signature value., Thumbprint of key used by client: **'Thumbprint-Certificate-ID'**, **Found key 'Start=01/03/2022 05:06:02, End=01/03/2023 05:26:02',** Please visit the Azure Portal, Graph Explorer or directly use MS Graph to see configured keys for app Id 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'. Review the documentation at https://learn.microsoft.com/en-us/graph/deployments to determine the corresponding service endpoint and https://learn.microsoft.com/en-us/graph/api/application-get?view=graph-rest-1.0&tabs=http to build a query request URL, such as 'https://graph.microsoft.com/beta/applications/XXXXXXXXXXXXXXXXXXX'].\r\nTrace ID: 300527eb-a871-4e6f-8f5b-031ec6940902\r\nCorrelation ID: 6364e88b-3717-48cd-abcf-df7c971d1fc9\r\nTimestamp: 2022-01-05 05:36:41Z",
"error_codes": [
700027
],
"timestamp": "2022-01-05 05:36:41Z",
"trace_id": "300527eb-a871-4e6f-8f5b-031ec6940902",
"correlation_id": "6364e88b-3717-48cd-abcf-df7c971d1fc9",
"error_uri": "https://login.microsoftonline.com/error?code=700027"
}

Related

Microsoft OAuth 2.0 Authentication Failure - token_url Bad Request Error

I want to ensure that my OAuth 2.0 authentication credentials. So, I have client_id, client_secret, tenant_id, scope, token_url and auth_url. I am using third party app in order to send a email but, I get error in OAuth 2.0 part as Bad Request Error for token_url.
In this case, when grant_type='client_credentials', how can I fix token_url domains or subdomains?
-> token_url like that https://login.microsoftonline.com/<tenant_id>/oauth2/v2.0/token
If you are dominate the this subject, Could you please mention about OAuth 2.0 process?
I tried to changed grant_type parameter as client_credentials. Default was 'refresh_token'.
In this case, it returned like that error:
(530, b'5.7.57 Client not authenticated to send mail. Error: 535 5.7.3 Authentication unsuccessful [ZR2P278CA0041.CHEP278.PROD.OUTLOOK.COM 2023-02-14T08:10:26.343Z 08DB0DEF6EA5D39B]', 'myemail#myemail.com')
2023-02-14 11:10:26,378 INFO [decorators] [send_email] StatusMessage: An error occurred while sending the email: (530, b'5.7.57 Client not authenticated to send mail. Error: 535 5.7.3 Authentication unsuccessful [ZR2P278CA0041.CHEP278.PROD.OUTLOOK.COM 2023-02-14T08:10:26.343Z 08DB0DEF6EA5D39B]', 'myemail#myemail.com')
2023-02-14 11:10:26,379 INFO [decorators] [send_email] StatusMessage: Done with sending email...
So, what is the main problem in this case?
Thank you for your attention,
I tried to reproduce the same in my environment and got the results as below: 
I created an Azure AD Application and granted admin consent to Mail.Send API permission:
  
Based on your requirement you can make use of Client Credential Flow or Authorization Code Flow.
If you want user interaction then make use of Authorization Code Flow.
If you want to send mail as Application then make use of Client Credential Flow. 
I generated the access token via Client Credential Flow by using parameters like below:
https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
client_id:ClientID
client_secret:ClientSecret
scope:https://graph.microsoft.com/.default
grant_type:client_credentials
 
 To send the mail, I used below query:
https://graph.microsoft.com/v1.0/users/FromAddress/sendMail 
{
"message": {
"subject": "Test mail",
"body": {
"contentType": "Text",
"content": "Test"
},
"toRecipients": [
{
"emailAddress": {
"address": "****"
}
}
],
"ccRecipients": [
{
"emailAddress": {
"address": "****"
}
}
]
},
"saveToSentItems": "false"
}
 
 Reference: 
user: sendMail - Microsoft Graph v1.0 | Microsoft Learn

Unable to call `/oauth2/v2.0/token` even with the correct redirect/reply URL

I am following this document and currently stuck at 3rd step, Get a token:
I have no issue with the 2nd step, Get authorization as I could sign in (from the browser) and it responded with the code for the next step (3rd step).
BUT when it gave me the response below when sending a POST request (/common/oauth2/v2.0/token):
{
"error": "invalid_client",
"error_description": "AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application: 'afef958a-7070-4b2d-9006-65b28c9aed43'.\r\nTrace ID: 2e478767-2adc-468c-b716-6134ca2d3a04\r\nCorrelation ID: 7117f8d0-2a9f-4110-8257-b32753876afb\r\nTimestamp: 2022-01-06 08:22:48Z",
"error_codes": [
50011
],
"timestamp": "2022-01-06 08:22:48Z",
"trace_id": "2e478767-2adc-468c-b716-6134ca2d3a04",
"correlation_id": "7117f8d0-2a9f-4110-8257-b32753876afb",
"error_uri": "https://login.microsoftonline.com/error?code=50011"
}
My request in Postman here
My Azure config here
My response on browser here
My code (PHP):
$response = $client->request(
"POST",
"/common/oauth2/v2.0/token",
[
"headers" => [
"Content-Type" => "application/x-www-form-urlencoded",
],
"form_params" => [
"tenant" => $tenantId,
"client_id" => $clientId,
"grant_type" => "authorization_code",
"scope" => "User.Read",
"code" => $_GET["code"],
"redirect_uri" => $replyUrl,
"client_secret" => $clientSecret,
]
]
);
Note:
I have tried with Accounts in any organizational directory and Accounts in any organizational directory and personal Microsoft accounts, both of them are giving me the same response
I am sure the client secret is correct
I am sure the redirect/reply URL is correct too
I have done enough research online, but no similar solutions that could solve this issue
This occurs when the login code in your app (js/ts) is not setting the redirectUrl value to something that matches what your app is configured to answer as a redirect Url in your Azure portal. You haven't sent enough code to see what your redirect looks like, but it's not clear why you're doing it by hand (instead of using MSAL), and also why you've tagged this as "microsoft-teams" - this is important because, if you are building a Teams tag, then the usual process is a little different for Teams.
Update: the original question makes it clear now that this is a PHP scenario, which my answer above does not address - fyi to anyone reading this answer.

Expected OAuth 2 access token while importing VAPID Push subscriptions into Firebase

I am trying to import vapid push subscriptions into firebase. I found some solution in https://developers.google.com/instance-id/reference/server#import_push_subscriptions. It thew following error. Please help me regarding this.
POST : https://iid.googleapis.com/v1/web/iid
Headers :
Content-Type:application/json
Authorization:key=MY_SERVER_KEY
BODY:
{
"endpoint" : "https://fcm.googleapis.com/fcm/send/my_sub_key",
"keys" : {
"p256dh" : "hidden_key",
"auth" : "hidden_auth"
}
}
}
Response:
"error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "status": "UNAUTHENTICATED" }

Microsoft graph return "access token is empty"

I post this request:
POST https://login.microsoftonline.com:443/{my-tennant-here}/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id={client id here}
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_secret={client secret here}
&grant_type=client_credentials
This returns:
{
"token_type": "Bearer",
"expires_in": 3599,
"ext_expires_in": 0,
"access_token": "eyJ0eX......
}
I have decoded the token using jwt.io and it definitely is not empty. It contains 14 claims. aud, iss, tid etc...
I then use the access token in this request
GET https://graph.microsoft.com/v1.0/users
Athorization: Bearer eyJ0eX...
I then get a 401 Unauthorized with this body:
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token is empty.",
"innerError": {
"request-id": "",
"date": "2018-08-14T15:41:44"
}
}
}
Expected result was a 200 Ok with a body containing a list of users
Does this simply mean that my app is Unauthorized, and the error message is just misleading (access token is empty)?
Or have I done something wrong?
Update:
I have noted that the although the token does contain claims it does not have a scope claim which seems a bit weird to me. I would assume that it had the User.Read.All scope. The application (client id/client secret) should have this permission.
The claims in the token I receive have the following claims:
aud: "https://graph.microsoft.com",
iss: "https://sts.windows.net/my tennant id",
iat: timestamp
nbf: timestamp
exp: timestamp
aio: looks like some kind of signature
app_displayname: "the expected app name"
appid: "the expected appid"
appidacr: "1"
idp: "https://sts.windows.net/...."
oid: "GUID"
sub: "GUID"
tid: "my tennant id"
uti: "value"
ver: 1.0
The Authorization header was misspelled.
So "Access token is empty" probably actually meant not present or even "No authorization header in request".
For me, my issue was that I had put a linebreak between the request url and the Authorization header, making it the body instead.
Wrong:
GET https://graph.microsoft.com/v1.0/users
Authorization: Bearer {{token}}
Correct:
GET https://graph.microsoft.com/v1.0/users
Authorization: Bearer {{token}}
A stupid mistake, but easy to overlook - if you get to this post you have probably done a silly mistake like OP (typo) or this. Look through your request syntax again!
One URL works while the other doesn't.
This works:
endpoint = "https://graph.microsoft.com/v1.0/reports/getOffice365ActiveUserDetail%28period%3D%27D7%27%29"
headers = {"Authorization": 'Bearer ' + access_token_gmc}
response = requests.get(endpoint, headers=headers)
But this one doesn't:
endpoint = "https://graph.microsoft.com/v1.0//users/myuserid/calendars"
headers = {"Authorization": 'Bearer ' + access_token_gmc}
response = requests.get(endpoint, headers=headers)
Please make sure the spellings are correct.
I was getting the same error in my angular application where I use MSAL.
And it was all because of the wrong API scope provided in the MSALAngularConfigFactory. I was having the environment as preceding.
export const environment = {
production: false,
clientId: 'clientid',
redirectUrl: 'http://localhost:4200',
graphApiUrl: 'https://graph.microsoft.com/v1.0',
graphGetUserImage: '/me/photo/$value',
protectedResourceMap: [
['http://localhost:65498/api', ['api.access']],
['https://graph.microsoft.com/beta', ['user.read']]
] as [string, string[]][],
authority: 'https://login.microsoftonline.com/organizations'
};
As you can see that I have given https://graph.microsoft.com/beta in the protectedResourceMap, which is wrong. Instead, we should give https://graph.microsoft.com/v1.0/. So here is the correct environment.
export const environment = {
production: false,
clientId: 'clientid',
redirectUrl: 'http://localhost:4200',
graphApiUrl: 'https://graph.microsoft.com/v1.0',
graphGetUserImage: '/me/photo/$value',
protectedResourceMap: [
['http://localhost:65498/api', ['api.access']],
['https://graph.microsoft.com/v1.0/', ['user.read']]
] as [string, string[]][],
authority: 'https://login.microsoftonline.com/organizations'
};
And I use it in the app.module.ts as below.
function MSALAngularConfigFactory(): MsalAngularConfiguration {
return {
popUp: false,
protectedResourceMap: environment.protectedResourceMap,
};
}
For User.Read.All scope you can't have a user consent. It must be admin consent. It looks like you may have missed consenting your app using an admin account.
To do this hit:
GET https://login.microsoftonline.com/{tenant}/adminconsent
?client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&state=12345
&redirect_uri=http://localhost/myapp/permissions
Then get an access token and you should get the scopes the admin has consented users for.

Authorize a client to browse Office365 Graph API

I am trying to develop a webapp to let a user browse his Active Directory contacts.
I have two accounts: one to register the application (developer account) and the other that would be the general user who have access to Office365 (user account).
I have set up a Javascript client following the Azure AD Graph API documentation.
By now, I am able to prompt the user to login and retrieve an access token, but when I try to make a request, I always get a 401 error.
I am pretty new to Azure, so I don't really understand if the problem is in my application configuration or in my code.
I am able to browse the Graph API explorer with my user account, so I don't think he's missing the authorization to access it.
I am really confused.
I try to add all the steps I am doing, hoping someone could point out the error.
Request 1:
Url: https://login.windows.net/{my tenant id or common (both are working) }/oauth2/authorize
Method: GET
Params:
redirect_uri // my redirect url, the same I registered in my application. It is just a page that returns the content of the URL
client_id // my client id
response_type // code
state // a random generated string, not required, but reccomanded
resource // https://graph.windows.net
Response 1:
code // A long string
state // The string I sent in the request
session_state // Another string
Request 2:
Url: https://login.windows.net/{my tenant id or common (both are working) }/oauth2/token
Method: POST
Params:
redirect_uri // it won't be necessary, but in some post they reccomand to add it
client_id // my client id
client_secret // my client secret
code // the code retrieved from Request 1
grant_type // authorization_code
state // a random generated string
resource // https://graph.windows.net
Response 2:
token_type // Bearer
access_token // a long token
id_token // exploring it with the JWT tool, shows it has the correct app id
refresh_token // a long code
resource // the same I sent in the request
scope // Directory.Read UserProfile.Read
expires_in
expires_on
a couple of other irrelevant keys
Request 3:
Url: https://graph.windows.net/{the domain the logged account belong to}/contacts
Method: GET
Headers:
Authorization: Bearer {the access token retrieved from request 2}
Params:
api-version = 1.5 // The value suggested in the documentation.
Response 3:
{
"odata.error": {
"code": "Authentication_MissingOrMalformed",
"message": {
"lang": "en",
"value": "Access Token missing or malformed."
},
"values": null
}
}
This is the content of my Access Token:
{
typ: "JWT",
alg: "RS256",
x5t: "foofoofoofoo"
}.
{
aud: "https://graph.windows.net",
iss: "https://sts.windows.net/<SOMEGUID>/",
iat: 1418224761,
nbf: 1418224761,
exp: 1418228661,
ver: "1.0",
tid: "<SOMEGUID>",
amr: [
"pwd"
],
idp: "https://sts.windows.net/<SOMEGUID>/",
email: "myuseremail#contoso.com",
unique_name: "myuseremail#contoso.com",
sub: "barbarbarbar",
altsecid: "<an-id>",
family_name: "Last Name",
given_name: "First Name",
appid: "<MY APP ID>",
appidacr: "1",
scp: "Directory.Read UserProfile.Read",
acr: "1"
}
Answer
So, it looks like user must have the "can consent" authorization to authenticate to his own active directory, and this can be provided just by the administrator.
I posted the same request on the MSDN forum and I got the same answer.
I want sincerely thank #Jason Johnston and #Dan Kershaw since this problem was driving me nut and I would never be able to sort it out without their help.
Unfortunately I can award the bounty to just one of them, so I decided to give it #Jason Johnston for the great patience he had in supporting me in this and another discussion.
I believe if you actually want to browse the Active Directory, and not just read the authenticated user's profile, you need administrator consent for a web app. See http://msdn.microsoft.com/en-us/library/azure/b08d91fa-6a64-4deb-92f4-f5857add9ed8#BKMK_Graph
If you already knew that, then maybe it's a problem with how you've registered your app or the token itself. Make sure you've selected the appropriate permissions per that link in your app registration. If those look right, then you can check the token. There's a handy little token parser here: http://jwt.calebb.net/. Just paste in the value of your token and it will show you the decoded JSON. Look at the scope or scp parameters.
{
"typ": "JWT",
"alg": "RS256",
"x5t": "asdfsadfasdfsa"
}
{
"aud": "https://graph.windows.net/",
"iss": "https://sts.windows.net/<SOMEGUID>",
"iat": 1418158549,
"nbf": 1418158549,
"exp": 1418162449,
"ver": "1.0",
"tid": "<SOMEGUID>",
"amr": [
"pwd"
],
"oid": "<SOMEGUID>",
"upn": "admin#contoso.com",
"unique_name": "admin#contoso.com",
"sub": "askdljalsdfs",
"puid": "1003BFFD88937280",
"family_name": "Administrator",
"given_name": "MOD",
"appid": "<YOUR APP ID>",
"appidacr": "0",
"scp": "Directory.Read user_impersonation UserProfile.Read",
"acr": "1"
}
The token you've pasted is missing the OID and UPN, and that'll probably be why you are seeing this error. I'll have to go back and check how this access token could have been issued without those claims.

Resources