I would like to connect my app with Microsoft Graph. I created my web-app in Azure (I have my client_id and client_secret). I am able to send a request to get the authorization code from https://login.microsoftonline.com/common/oauth2/v2.0/authorize.
The problem is that when I send a POST request in order to get the acess token from https://login.microsoftonline.com/common/oauth2/v2.0/token (exactly like said here in the "Using permissions" section) using Postman (with form-data option), I get an "AADSTS9000410: Malformed JSON" error:
{
"error": "invalid_request",
"error_description": "AADSTS9000410: Malformed JSON.\r\nTrace ID: f5c1dd4b-ad43-4265-91cb-1b7392360301\r\nCorrelation ID: 1dea54ed-bb43-4951-bc9e-001877fe427b\r\nTimestamp: 2019-01-14 21:38:42Z",
"error_codes": [9000410],
"timestamp": "2019-01-14 21:38:42Z",
"trace_id": "f5c1dd4b-ad43-4265-91cb-1b7392360401",
"correlation_id": "1dea54ed-bb43-4951-bc9e-001878fe427b"
}
Moreover, when I send the same request with a raw option in Postman, I get "AADSTS900144: The request body must contain the following parameter: 'grant_type'":
{
"error": "invalid_request",
"error_description": "AADSTS900144: The request body must contain the following parameter: 'grant_type'.\r\nTrace ID:a7c2f8f4-1510-42e6-b15e-b0df0865ff00\r\nCorrelation ID:e863cfa9-0bce-473c-bdf6-e48cfe2356e4\r\nTimestamp: 2019-01-1421:51:29Z",
"error_codes": [900144],
"timestamp": "2019-01-14 21:51:29Z",
"trace_id": "a7c2f8f4-1510-42e6-b15e-b0df0865ff10",
"correlation_id": "e863cfa9-0bce-473c-bdf6-e48cfe2356e3"
}
However, when I remove application/json in my header in Postman, and I put x-www-form-urlencoded option, everything looks fine.
I can only send POST requests with a JSON format in my application.
Does Microsoft Graph support JSON format for POST requests?
Is it a Postman issue?
I ran into a similar issue, but realized that there was a mismatch between the Content-Type: application/x-www-form-urlencoded header and the JSON-formatted request body. If you refer to this documentation, you'll see that the request body needs to be URL encoded (concatenated with ampersands, encoded entities, etc.), which ultimately resolved my issue. So, I don't believe this is an issue with Postman or MS APIs but, rather, just incorrect formatting of your request body.
I'm not sure what language your app uses, but here's an example using Node and Express that works for me:
const fetch = require('node-fetch')
const { URLSearchParams } = require('url')
async function getAccessToken(req, res, next) {
try {
const response = await fetch('https://login.microsoftonline.com/common/oauth2/v2.0/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
// Previously I was doing `body: JSON.stringify({...})`, but
// JSON !== URL encoded. Using `URLSearchParams` (or whatever
// the equivalent is in your language) is the key to success.
body: new URLSearchParams({
client_id: YOUR_CLIENT_ID_HERE,
scope: 'User.Read Calendars.Read',
redirect_uri: YOUR_REDIRECT_URL_HERE,
grant_type: 'authorization_code',
client_secret: YOUR_CLIENT_SECRET_HERE,
code: req.query.code
}
})
const json = await response.json()
// `json` will have `access_token` and other properties
} catch (err) {
throw err
}
}
Hope that helps!
It is neither a Microsoft nor a Postman issue, it is simply how OAuth defines the token workflow. This is defined in RFC 6749 - Section 4.1.3:
The client makes a request to the token endpoint by sending the following parameters using the application/x-www-form-urlencoded format per Appendix B with a character encoding of UTF-8 in the HTTP request entity-body
Related
I must be really stupid, But I have been struggling for weeks to try solve this issue, and all the digging I have done (in Stack overflow and MS Documentation) has yielded no results (or I'm too stupid to implement auth correctly)
I have a dotnet service which needs to act as an API - both for an application to post data to (an exe which logs exception data), and for a UI (react app) to get the posted exceptions
the exe can successfully send data to the dotnet app after first getting a token from login.microsoftonline.com and then sending the token (and secret) in the http request.
A sample postman pre-request script of the auth used (I've set all the secret stuff as environment variables):
pm.sendRequest({
url: 'https://login.microsoftonline.com/' + pm.environment.get("tenantId") + '/oauth2/v2.0/token',
method: 'POST',
header: 'Content-Type: application/x-www-form-urlencoded',
body: {
mode: 'urlencoded',
urlencoded: [
{key: "grant_type", value: "client_credentials", disabled: false},
{key: "client_id", value: pm.environment.get("clientId"), disabled: false},
{key: "client_secret", value: pm.environment.get("clientSecret"), disabled: false}, //if I don't configure a secret, and omit this, the requests fail (Azure Integration Assistant recommends that you do not configure credentials/secrets, but does not provide clear documentation as to why, or how to use a daemon api without it)
{key: "scope", value: pm.environment.get("scope"), disabled: false}
]
}
}, function (err, res) {
const token = 'Bearer ' + res.json().access_token;
pm.request.headers.add(token, "Authorization");
});
Now in React, I am using MSAL(#azure/msal-browser) in order to login a user, get their token, and pass the token to one of the dotnet endpoints using axios as my http wrapper, but no matter what I do, it returns http status 401 with WWW-Authenticate: Bearer error="invalid_token", error_description="The signature is invalid".
A simplified code flow to login user and request data from the API:
import {publicClientApplication} from "../../components/Auth/Microsoft";//a preconfigured instance of PublicClientApplication from #azure/msal-browser
const data = await publicClientApplication.loginPopup();
// ... some data validation
publicClientApplication.setActiveAccount(data.account);
// .. some time and other processes may happen here so we don't access token directly from loginPopup()
const activeAccout = publicClientApplication.getActiveAccount();
const token = publicClientApplication.acquireTokenSilent(activeAccount).accessToken;
const endpointData = await api()/*an instance of Axios.create() with some pre-configuration*/.get(
'/endpoint',
{ headers: {'Authorization': `bearer ${token}`} }); // returns status 401
The dotnet service has the following configurations
public void ConfigureServices(IServiceCollection services){
...
var authScheme = services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme);
authScheme.AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"));
...
}
namespace Controllers{
public class EndpointController : ControllerBase{
...
[Authorize]
[HttpGet]
public IActionResult GetEndpoint(){
return Ok("you finally got through");
}
}
}
I've literally tried so many things that I've lost track of what I've done...
I've even cried myself to sleep over this - but that yielded no results
i can confirm that running the request in postman, with the pre request script, it is possible to get the response from the endpoint
So....
After much digging and A-B Testing I was able to solve this issue.
I discovered that I was not sending the API scope to the OAuth token endpoint. To do this I needed to change the input for acquireTokenSilent.
The updated code flow to login user and request data from the API:
import {publicClientApplication} from "../../components/Auth/Microsoft";//a preconfigured instance of PublicClientApplication from #azure/msal-browser
const data = await publicClientApplication.loginPopup();
// ... some data validation
publicClientApplication.setActiveAccount(data.account);
// .. some time and other processes may happen here so we don't access token directly from loginPopup()
const activeAccout = publicClientApplication.getActiveAccount();
const token = publicClientApplication.acquireTokenSilent({scopes:["api://XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/.default"],account:activeAccount}).accessToken;//here scopes is an array of strings, Where I used the api URI , but you could directly use a scope name like User.Read if you had it configured
const endpointData = await api()/*an instance of Axios.create() with some pre-configuration*/.get(
'/endpoint',
{ headers: {'Authorization': `bearer ${token}`} }); // returns status 401
I'm trying to get the Content-Disposition header in a response from an external API using axios.
Despite the header being present in Chrome DevTools Network Response, I can't seem to have access to that specific header from server.
I found this article talking about exposing the Content-Disposition header through Access-Control-Expose-Headers but I'm not quite sure how to implement it in Nextjs.
I tried editing the next.config.js file like below, by following directions from this Nextjs Documentation page, regarding security headers, but had no luck
/** #type {import('next').NextConfig} */
module.exports = {
reactStrictMode: true,
async headers() {
// to allow specific headers to appear in requests
// https://nextjs.org/docs/advanced-features/security-headers
const securityHeaders = [
// important
{ key: "Access-Control-Expose-Headers", value: "Content-Disposition" },
]
return [
{
source: '/:path*', // req path
headers: securityHeaders
}
]
}
}
This is the API call I made using axios:
// lib/utils.js
export async function downloadFile(collectionName: string, documentId: string) {
const res = await axios.get(
`https://api.myapiendpoint.com/file/${collectionName}/${documentId}`
);
console.log(res.headers);
}
Chrome DevTools log:
console.log output:
// these are the only headers I receive
{
"content-length": "195687",
"content-type": "text/csv; charset=utf-8",
"last-modified": "Thu, 10 Feb 2022 16:00:05 GMT"
}
I am 99.99% sure and I believe this is most probably backend issue. I had the exact same problem when i needed to implement download pdf/csv logic (with file name) which required content-disposition header to be accessed from response.
Now, no matter what I tried I always got to see that header in dev tools and also in postman but not in my console. After lots of efforts and convincing my backend team member, it turned out that backend didn't expose it.
Check your backend (whatever technology it uses), the problem lies there ;)
I'm almost embarassed to be asking this question due to CORS support out there on SO but I can't get by:
Access to XMLHttpRequest at 'https://a93xxxxx.execute-api.eu-west-1.amazonaws.com/dev[object%20Object]' from origin 'https://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I've even published my React project with Amplify and attempted it from the real domain name to even eliminate anything to do with the development environment (Cloud 9 running npm version 6.14.8)
I've also made a test running Chrome with the --disable-web-security flag.
My Lambda function contains the following (out of the box stub)
exports.handler = async (event) => {
// TODO implement
const response = {
statusCode: 200,
// Uncomment below to enable CORS requests
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers" : "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With",
"Access-Control-Allow-Methods" : "OPTIONS,POST,GET,PUT"
}
,
body: JSON.stringify("Hello from Lambda!")
};
return response;
};
Note that I've uncommented the CORS request part and the response statusCode is set to 200.
The code in my application that execute when a submission form is sent from the client:
uploadcontactusdata = async data => {
try {
console.log("Contact Us pressed")
const settings = {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
const fetchResponse = await API.post('econtactus', settings);
Notification({
title: 'Success',
message: 'Notification has been sent',
type: 'success'
});
}
catch (err) {
console.log("unable to send");
console.error(err)
}
}
I created the API Gateway + Lambda using Amplify (version 4.41.2). Not sure where else to look now. Any clues will be appreciated. Thanks
You can completely get past the need for api gateway by using appsync.
amplify add api
Choose graphql (I have not tried using rest but you shouldn't need it) choose the basic schema, edit it if you'd like, and publish. Once it's published you can create your own method. You can view this inside the AppSync UI under Schema.
type Mutation {
yourMethod(input: Input!): TableName <-- add your method to the list
}
Now inside Appsync choose Data Sources and add datasource. Give it a name, choose lambda as the type, then find your lambda in the list. Once it's added go back to your schema and find the method you created above. On the right side bar locate your method and click the attach link. Find the data source you just added. Fill out the region and lambda ARN. MAKE SURE you choose new role and not an existing one.
You might need to configure the request and response templates.
For request:
{
"version" : "2017-02-28",
"operation": "Invoke",
"payload": $util.toJson($context.args)
}
For response:
$util.toJson($context.result)
Now you can call your lambda directly from the UI and return your result without worrying about CORS or managing API Gateway.
I am trying to return user data from a login with Polymer. I have it working with Postman, but am having trouble translating it into Polymer.
In Postman this returns a JSON object, but in Polymer it is returning undefined.
Polymer Client Code [Connecting to node.js server]
<iron-ajax id="ajaxUser"
url="http://localhost:8080/login"
method="post"
handle-as="json"
content-type="application/json"
headers='{"Access-Control-Allow-Origin": "*"}'
params="[[params]]"
on-response="saveUserCredentials"
last-response="{{user}}"></iron-ajax>
...
<paper-input id="username"></paper-input>
<paper-input id="password"></paper-input>
<paper-button on-tap="loginUser"></paper-button>
...
loginUser() {
this.params = {"username": this.$.username.value, "password": this.$.password.value};
console.log(this.params); // logs this.params as populated JSON
let request = this.$.ajaxUser.generateRequest();
request.completes.then(req => {
console.log(req); // logs <iron-request></iron-request>
console.log(this.user); // logs []
})
.catch(rejected => {
console.log(rejected.request); // not returned
console.log(rejected.error); // not returned
})
}
saveUserCredentials() {
console.log(this.user);
}
Node, Express, mssql Server Code [Connecting to SQL Server database]
app.post("/login", (req, res) => {
session.login(req, res)
})
...
exports.login = (req, res) => {
sql.connect(config.properties)
.then(pool => {
pool.request()
.input('user', sql.VarChar(50), req.body.username)
.input('password', sql.VarChar(50), req.body.password)
.query("SELECT role FROM Login WHERE username = #user AND password = #password")
.then(response => res.send(response))
.catch(err => res.send(err))
})
}
Error
SyntaxError: Unexpected token # in JSON at position 0 .
at JSON.parse ()
at createStrictSyntaxError (C:\node_modules\body-parser\lib\types\json.js:157:10)
at parse (C:\node_modules\body-parser\lib\types\json.js:83:15)
at C:\node_modules\body-parser\lib\read.js:121:18 .
at invokeCallback (C:\node_modules\raw-body\index.js:224:16)
at done (C:\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (events.js:159:13)
at endReadableNT (_stream_readable.js:1062:12)
at process._tickCallback (internal/process/next_tick.js:152:19)
The first issue appears to be that your server is expecting a JSON object in the request, but the server sees the request as a string due to a missing Content-Type header on your request. To set the Content-Type for JSON requests, set <iron-ajax>.contentType to application/json:
<iron-ajax content-type="application/json" ...>
OK, I was able to get a server response by setting content-type=application/json as an iron-ajax property. Am now getting Unexpected token # in JSON at position 0 as a server side error...
That sounds like the request is not actually valid JSON (since it contains a # as the first character). Use the Chrome DevTools Network Panel to inspect the actual contents of the payload. I wouldn't rely solely on console.log in your code.
Also, it is now making two requests when I submit. One with the content-type set, which resolves to 200, and one with that resolves to 400 with parsing error.
The first message is likely the preflight request, which is sent (as part of CORS) to the server to check whether content-type="application/json" is an allowed header. The second message is the intended data request, but that fails with the following error.
And a client side error of No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4001' is therefore not allowed access. The response had HTTP status code 400.
Your server needs to enable CORS requests. There are various ways to accomplish this, but the simplest Node solution might be to use the cors package:
const cors = require('cors');
const app = express();
app.use(cors());
i have encountered a weird problem in Google App Engine developing, every time is carry a body content in my post request, app engine failed to auth my account, but get request works.
can anybody help me? i'm using oauth library ChromeExOAuth in chrome extension developing.
oauth.authorize(function(){
var request = {
'method': 'POST',
'headers': {
"Content-Type" : "application/x-www-form-urlencoded"
},
'parameters': {
},
'body': "a=b"
};
oauth.sendSignedRequest("http://mytabshub.appspot.com/tabshub", function(resp, xhr){
console.log("responding from test server", xhr.responseText);
}, request);
});
For POST requests you must pass the oauth parameter url-encoded in the request body. The relavant code in the SDK is this (dev_appserver_oauth.py):
def _Parse(self, request, base_env_dict):
"""Parses a request into convenient pieces.
Args:
request: AppServerRequest.
base_env_dict: Dictionary of CGI environment parameters.
Returns:
A tuple (method, path, headers, parameters) of the HTTP method, the
path (minus query string), an instance of mimetools.Message with
headers from the request, and a dictionary of parameter lists from the
body or query string (in the form of {key :[value1, value2]}).
"""
method = base_env_dict['REQUEST_METHOD']
path, query = dev_appserver.SplitURL(request.relative_url)
parameters = {}
if method == 'POST':
form = cgi.FieldStorage(fp=request.infile,
headers=request.headers,
environ=base_env_dict)
for key in form:
if key not in parameters:
parameters[key] = []
for value in form.getlist(key):
parameters[key].append(value)
elif method == 'GET':
parameters = cgi.parse_qs(query)
return method, path, request.headers, parameters
See that the query is only parsed in GET requests. For POST, it must be in the body.