Microsoft login from oauth2 issue - azure

I have a React app using axios library for handling request. So following the next post:
How to login with username/password using OAuth2 and microsoft login and HTTP request
I could perform the action on Postman.
Then I set up the axios library to perform the POST
const dataForBody = `${'grant_type=password&' +
'username='}${encodeURI(userName)}&` +
`password=${encodeURI(userPassword)}&` +
`client_id=${encodeURI(clientID)}&` +
`resource=${encodeURI('https://graph.microsoft.com')}&` +
`client_secret=${encodeURI(clientSecret)}`;
const messageHeaders = {
'Content-Type': 'application/x-www-form-urlencoded'
};
axios({
method: 'post',
url: 'https://login.microsoftonline.com/{tenant}/oauth2/token',
headers: messageHeaders,
data: dataForBody,
})
.then((response) => {
});
but I get the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
https://login.microsoftonline.com/{tenant}/oauth2/token.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
I tried adding:
'Access-Control-Allow-Origin': 'https://login.microsoftonline.com',
to the headers, but it did not work.
So adding Allow-Control-Allow-Origin: *​​​ chrome extension fixed my problem.
The thing is, my app is to be published on azure, so I tested the request on other web browsers and it did not work. So I don't want my users to install the extension.
Is there something wrong with my request? Why postman can do it without setting up headers?
Is there any other approach to achieve it?
PS: I read about using adal.js but I dont want to use the login screen from microsoft, because I know user and pass for the app, and I want to avoid manual login.

The problem you face is due to you trying to call the token endpoint via AJAX, which it won't accept due to the CORS header missing. You can't add it, it's missing from the response from Azure AD.
What you need to do is instead of getting the access token from the token endpoint, you must use the OAuth Implicit Grant Flow. This flow allows you to get the tokens directly in the authorization stage, and is especially designed for JavaScript-based apps. More info here: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-dev-understanding-oauth2-implicit-grant.
What this means is that you can't use the Password Grant Flow as you are doing now, unless you make the calls from your backend instead of the frontend.

Related

authentication header vs query parameter in google cloud endpoints

I have tried everything, yet I cannot access my API using google cloud endpoints using a Authentication:Bearer header. According to Cloud Endpoints Docs:
When you send a request using an authentication token, for security reasons, we recommend that you put the token in the Authorization:Bearer header.
it also says:
If you cannot use the header when sending the request, you can put the authentication token in a query parameter called access_token.
I can perfectly access the API using access_token=" +idToken in my URL. However, when I try to send an HTTP request with the Authentication header like this:
const url =
"https://<PROJECTNAME>.appspot.com/getbalance";
axios
.get(url,{headers:{'Authentication':'Bearer '+idToken}})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
I get this error:
JWT validation failed: Missing or invalid credentials
Is sending the token in a query parameter as safe as sending it in the header?
Your code example shows you setting an Authentication header, not an Authorization header. You should not typically use a query parameter as it will likely get logged in Cloud Console.
When using "Authorization: Bearer ", you would need to use an access token obtained through OAuth 2.0 authentication.
This can be illustrated if you use the Oauth Playground agains any of the Google APIs.
Keep in mind that if you want to access your Firebase database using the Oauth Playground, you would need to configure the client ID and client Secret of your Firebase project on the gear icon at the top right of the playground screen.
Also make sure to use these scopes:
https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/firebase.database
After completing all the steps, you will be able to make a REST request using the authorization header with the obtained access token.

Intercom integration auth python

I am not able to authorize in accessing users from intercom using get request. This is what I have done:
import requests
headers = {
'Authorization': 'Bearer {my accsess token}',
'Accept': 'application/json',
'Content-Type': 'application/json',
}
res = requests.get("https://api.intercom.io/users",headers=headers)
Error I am getting:
{"code":"token_unauthorized","message":"Not authorized to access
resource"}
Please tell me what I am doing wrong.
Thanks in advance.
I ran into this problem and it was due to a typo with my 'https://app.intercom.io/oauth' URL. This was hard to debug because the redirect URL was entered in an earlier command when you apply for a code, to get the bearer token. In my case, since I had a default Redirect URL when I applied for the OAuth, I just dropped the redirect URL from my call to 'https://app.intercom.io/oauth'.
Micheál here from the support team at Intercom 👋
Access tokens for the Intercom REST API have the concept of scopes i.e permissions levels. Some operations require a token with elevated scopes. Listing all users is one such operation.
You can read more about access tokens including how to apply for elevated scopes here: https://developers.intercom.com/docs/personal-access-tokens
If you're still having issues please drop us a line at team#intercom.io and we can investigate further 🙂 

CORS Oauth Request in JQuery to Azure AD to Access Power BI api

I am working on FreshDesk based client apps,
Facts and my problem:
FreshDesk widgets/apps only allow jQuery/JS and HTML, doesn't give any server side support yet for developers.
I am looking get list of Power BI reports in the widget.
This requires Azure AD Oauth Token, thus I am having trouble making a CORS request.
I some how asked freshdesk to whitelist the domains required for microsoft domain's oauth request calls.
I still get the following error
XMLHttpRequest cannot load
https://login.microsoftonline.com/common/oauth2/authorize?. Response
to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://xxxx.freshdesk.com' is therefore not allowed
access.
My code is as below
jQuery.ajax({
type: 'GET',
url: authorizeURL,
headers: headers1,
beforeSend: function(xhr){xhr.setRequestHeader('Access-Control-Allow-Origin','https://login.microsoftonline.com');},
success : function(text1)
{console.log(text1);}
});
Freshdesk now supports OAuth in a different way.
Provide the following in OAuth_config.yaml
client_id: "5eXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXc8d1"
client_secret: "q8NbXXXXXXXXXXXXXXXX1p1"
Authorize_url: "https://login.domain.com/authorize"
token_url: "https://login.domain.com/token"
options:
scope: "read"
token_type: "account"
More information available at https://developers.freshdesk.com/docs/oauth/

MS Graph API: invalid authentication token

I'm trying to use the Microsoft Graph API to query an Outlook/O365 mailbox for messages. I registered my app in the Azure portal and received the necessary information to query the API. The app has the Mail.Read permission. (I don't have access to the Azure portal, I was told it was set up this way.) When I get my token from the OAuth endpoint, however, it doesn't work in any subsequent calls. I'm using Python's requests module for testing right now.
Why is this call failing? It seems like I'm passing all of the correct information but I'm clearly missing something.
I'm getting the token by performing a POST on:
https://login.microsoftonline.com/my.domain/oauth2/token
I pass the necessary parameters:
data = {'grant_type': 'client_credentials', 'client_id': CLIENTID, 'client_secret': SECRET, 'resource': APPURI}
and I get a response like this:
{
'resource': 'APPURI',
'expires_in': '3599',
'ext_expires_in': '3600',
'access_token': 'TOKENHERE',
'expires_on': '1466179206',
'not_before': '1466175306',
'token_type': 'Bearer'
}
I try to use that token, however, and it doesn't work for anything I call. I'm passing it as a header:
h = {'Authorization': 'Bearer ' + TOKEN}
I'm calling this URL:
url = 'https://graph.microsoft.com/v1.0/users/my.email.address#example.com/messages'
Specifically, I use this:
r = requests.get(url, headers=h)
The response is a 401:
{
'error': {
'innerError': {
'date': '2016-06-17T15:06:30',
'request-id': '[I assume this should be removed for privacy]'
},
'code': 'InvalidAuthenticationToken',
'message': 'Access token validation failure.'
}
}
in your login request, the resource parameter should be https://graph.microsoft.com
It seems to be the case, that tokens issued from the v1 endpoint aren't valid for atleast some requests with MS Graph API.
Instead try to get the token form the v2 endpoint by calling https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token.
In case you are working with oidc discovery documents, you'll find the one for v2 at https://login.microsoftonline.com/{tenant}/v2.0/.well-known/openid-configuration
I think you will need to register app from here "https://apps.dev.microsoft.com" instead of from Azure Portal.
Unless you are an using Client Credentials, you cannot access the messages another account's mailbox. Make sure that my.email.address#example.com is the same account you are authenticated with and that this address is also the userPrincipalName for the account.
You can also use a simplified URI for requesting your messages and bypassing determining the account's userPrincipalName by using /me. In this case the GET request would be https://graph.microsoft.com/v1.0/me/messages
It's worth noting that even if MS's Azure documentation does not specify the need for listing the resource, I could never get to work without listing the resource.
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols-oauth-client-creds.
There is a supplementary document specifiy to two-legged Auth for MS Graph that actually uses the 'resource' in the example.
https://developer.microsoft.com/en-us/graph/docs/authorization/app_only
Happy hunting!

JWT token issue on Azure Management API

I've been trying to use the Azure Service Management API in order to list the Hosted Services with no success.
In the first place, I was able to set up the authentication using PowerShell as the Microsoft documentation states here: https://msdn.microsoft.com/en-us/library/azure/dn790557.aspx
My first step was to request an access token using OAuth2 making a POST request to this URL:
https://login.windows.net/<MY_TENANT_ID>/oauth2/token
and passing these parameters:
grant_type: client_credentials
client_id: <THE_CLIENT_ID_OF_THE_APP_REGISTERED_THROUGH_POWERSHELL>
client_secret: <THE_PASSWORD_OF_APP_REGISTERED_THROUGH_POWERSHELL>
resource: https://management.core.windows.net
so, I receive a valid response and an access_token included in the response. So far so good.
Then, I want to make a simple call to the Management API; I would like to list my Hosted Services (Cloud Services), so I make a GET request to this URL:
https://management.core.windows.net/<MY_SUBSCRIPTION_ID>/services/hostedservices
Including the following headers:
Authorization: Bearer <THE_ACCESS_TOKEN_RECEIVED_IN_THE_PREVIOUS_STEP>
x-ms-version: 2014-10-01 (I've also tested with different versions)
but, what I get is a 401 Unauthorized error, with the following message:
The JWT token does not contain expected audience uri 'https://management.core.windows.net/'
I also tried with a Native Application registered directly in the Azure Portal (with Permissions set to use the Service Management API) and requesting a token using the grant_type = authorization_code. I get the access_token correctly and a refresh_token, but when I try to make a request to the above URL, I get the same error message.
On a side note, I am able to use the Azure Insights API successfully; the issue above is with the Azure Service Management API.
Anyone knows what I am missing?
I faced the same problem today. Complete the resource url with '/' https://management.core.windows.net
See the mismatch between the url in your resource and the one in the error message 'https://management.core.windows.net/'

Resources