So I'm trying to get an access token in order to delete a user.
var options = {
method: 'POST',
url: 'https://dev-owihjaep.auth0.com/oauth/token',
headers: {'content-type': 'application/json'},
data: {
grant_type: 'client_credentials',
client_id: 'RGPTciPqTAlJSDoO3zkL4GT1HV3fsptj',
client_secret: process.env.AUTH0_CLIENT_SECRET,
audience: 'https://dev-owihjaep.auth0.com/api/v2/'
}
};
let accessTokenResponse = await axios.request(options)
It worked in localhost but for some reason for my deployed app I'm getting status: 401, statusText: 'Unauthorized' and data: { error: 'access_denied', error_description: 'Unauthorized' }. I created client grants for my client, made sure Authorized was switched for my Application in Machine to Machine Applications in Auth0 Management API settings, and made sure Client Credentials was checked for Grant Types for my Application. How I can fix this error?
I had to add my .env environment variable(process.env.AUTH0_CLIENT_SECRET) to my Heroku Config Vars.
Related
My code to get the access token using a refresh token was working fine, but suddenly has stopped working and I'm getting exception as
unauthorized client and status code as 401.
Below is my sample code:
request({
method: 'POST',
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
data: {
client_id: XXXXX,
client_secret: XXXXX,
refresh_token: myRefresh_Token_Here,
grant_type: 'refresh_token'
},
URL: "https://oauth2.googleapis.com/token"
})
.then(response => {
resolve(response);
})
.catch(exception => {
reject(exception);
});
Below is the error what i get
this i get in below object
exception.response.data
{"error":"unauthorized_client","error_description":"Unauthorized"}'
No other info, also the status code is 401
unauthorized client
Normally means that the client id and client secret you are using to pair with a refresh token is not the pair that was used to create the refresh token in the first place.
I would double check you have the correct client id and client secret or that someone didn't regenerate your secret on Google cloud console.
I've registered as the Web app as required by the Reddit API for the Oauth access with identity, edit, flair, history, modconfig, modflair, modlog, modposts, modwiki, mysubreddits, privatemessages, read, report, save, submit, subscribe, vote, wikiedit, wikiread scopes.
I'd authorized my app and have exchanged the generated code for the access_token with 3600 seconds validity.
'use strict';
let request = require('request');
const USER_AGENT = 'web:com.example.server:v0.0.1 (by /u/sridharrajs)';
const token = '<my access_token within 3600 seconds validity>';
request({
method: 'POST',
url: 'https://www.reddit.com/api/vote',
headers: {
'User-Agent': USER_AGENT,
'Authorization': `bearer ${token}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
id: "t1_9qy47p",
dir: "1"
},
json: false
}, function (error, response, body) {
if (error) {
console.log('error', error);
} else if (body.error) {
console.log('body.error', body);
}
return console.log(body);
});
But when I try to upvote a reddit submission using API, I get an error.
{"message": "Forbidden", "error": 403}
The link that I'm trying to upvote is Tim Cook warns of ‘data-industrial complex’ in call for comprehensive US privacy laws
I tried switching both bearer and Bearer as per the answer in Reddit API returns HTTP 403, and tried using different User-Agent as suggested in 403 error when trying to get data from Reddit API. Nothing seem to work.
What am I missing?
Solved. I need to use https://oauth.reddit.com instead of www.reddit.com.
You may now make API requests to reddit's servers on behalf of that user, by including the following header in your HTTP requests:
Authorization: bearer TOKEN
API requests with a bearer token should be made to https://oauth.reddit.com, NOT www.reddit.com.
I keep getting an unauthenticated error back when submitting my request to the Google My Business API in my Node.js app. The 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"
}
}
For what it's worth, I'm using the request-promise client to make the request. My function is below. I just received the access token, so I'm fairly certain that it's good, and I can see it through the err.options.Authorization log. I know the location ID doesn't exist yet, but I don't think that's what the error is telling me.
const request = require('request-promise');
...
function checkLocation (loc) {
return request({
method: 'GET',
uri: `https://mybusiness.googleapis.com/v4/accounts/${ACCOUNT_ID}/locations/${loc._id}`,
Authorization: `OAuth ${ACCESS_TOKEN}`
})
.then(function (response) {
console.log(response);
})
.catch(function (err) {
console.error(err.error, err.options.Authorization);
});
}
Is my request formatted incorrectly or am I not sending all I need to be?
Update: I left out possibly crucial information that this is through the one time authorization process for server-side apps like outlined here: https://developers.google.com/identity/protocols/OAuth2. My trouble is wrapped up in the sentence on that page, "After an application obtains an access token, it sends the token to a Google API in an HTTP authorization header."
Turned out my header wasn't formatted correctly. The Authorization key should be in a headers object:
{
method: 'GET',
uri: `https://mybusiness.googleapis.com/v4/accounts/${ACCOUNT_ID}/locations/${loc._id}`,
headers: {
Authorization: `OAuth ${ACCESS_TOKEN}`
}
}
I am putting together an api integration with Dynamics CRM on premise (v8.1/8.2), on a IFD, using the password grant type.
I am retrieving an access token successfully, however when I then try to call endpoints (e.g /api/data/v8.2/contacts?$select=fullname,contactid ) I get 401 - access denied errors. When I log into the CRM with the user I can successfully view this data and the error occurs on all tested endpoints.
Interestingly this morning I realised the tokens retrieved cannot be base64 decoded - is that correct?
I could use some ideas on what to look at next to resolve the problem. Steps I've taken:
Triple checking the initial token request
Triple checked the Service Root URL
Tried on two CRM/Azure setups
Tried with my own (node) code and internet examples
A wide variety of token setups
Confirmed the user exists in Azure and the CRM
Confirmed user has sufficient permissions
Confirmed the application on Azure has all dynamics permissions granted
Confirmed I am on the same network as Azure and the CRM
It seems apparent that I have a configuration issue somewhere in Azure or the CRM. However no guide or question I can find suggests looking at problems I haven't already checked for and I could really use some input from those who have had to make adjustments in obscure settings ect.
Heres my token request:
var options = {
method: 'POST',
url: 'https://login.microsoftonline.com/<snip>/oauth2/token', //for 'intercity technology' (guid is unique)
headers:
{
'cache-control': 'no-cache',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' },
formData:
{
grant_type: 'password',
client_id: ‘<snip>’, //aplication id
client_secret: ‘<snip>’, //any key in the keys list
username: ‘<snip>’,
password: ‘<snip>’, // and their password
resource: ‘<snip>’ //application id
}
};
logger.debug(util.inspect(options));
request(options, function (error, response, body) {
...
Heres my current api request test:
var options = {
method: 'GET',
url: organisation_url + '/api/data/v8.2/contacts?$select=fullname,contactid',
headers: {
Authorization: 'Bearer '+token,
Accept: 'application/json',
'OData-MaxVersion':4.0,
'OData-Version': 4.0,
'Content-Type': 'application/json; charset=utf-8',
'Prefer': 'odata.maxpagesize=500',
'Prefer': 'odata.include-annotations=OData.Community.Display.V1.FormattedValue'
}
};
logger.debug(util.inspect(options));
request(options, function (error, response, body) {
...
You'll need to use a grant type of 'client_credentials' instead of 'password' as the later isn't supported.
Something like:
grant_type: 'client_credentials',
client_id: ‘<snip>’, //aplication id
client_secret: ‘<snip>’, //any key in the keys list
resource: ‘<snip>’ //CRM Url
Follow the guide here and all the links to ensure the AAD application is registered correctly and the CRM application user is in place.
** Disclaimer -- I'm new to the world of oAuth and OpenIDConnect -- please be patient if I'm asking a stupid question here.
I want to create a SPA that will request data from an API. Both the SPA and API are hosted on the same nodejs server. I want anyone accessing data and/or the app to be authenticated with our AzureAD tenant on Office365.
Currently, I have the authentication piece working using passport-azure-ad.OIDCStrategy. However, in my app, I would also like to be able to access information from the Microsoft GRAPH api in the server side api code. However, the OIDC connection that I've already made does not seem to be enough to allow me access to the GRAPH api. It appears that maybe I need a jwt bearer token.
My question is, do I need to use the access token from the OIDC response to get a bearer token? If so, how do I go about this (on the server side -- nodejs)?
I tried viewing the example listed in passport-auth-ad for BearerStrategy v2 endpoint. What confuses me though is that it uses OIDCStrategy! Does that also return a bearer token? If so, am I already receiving everything I need in my first OIDCStrategy call?
Thanks for whatever help you can offer!
Update
https.request({
hostname: "graph.microsoft.com",
path: '/v1.0/me/messages',
port: 443,
method: 'GET',
headers: {Authorization: 'Bearer ' + req.user.token, Accept: "application/json"}
},(rs) => {
console.log("HTTPS Response Status: ", rs.statusCode);
console.log("HTTPS Response Headers: ", rs.headers)
rs.on('data', (d) => {
res.send(d)
})
}).end();
Error Message:
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.", ...
I confirmed that the token is the same token that was passed as the id_token in the auth callback from Azure. Any thoughts?
Update 2
A few more code snippets to help in diagnosing where I may be going wrong.
Strategy Config
//Still test code so user management not fully implemented
passport.use("azure", new azureStrategy({
identityMetadata: 'https://login.microsoftonline.com/common/.well-known/openid-configuration',
clientID: "*********************",
responseType: 'code id_token',
issuer: "https://sts.windows.net/****************/",
responseMode: 'form_post',
redirectUrl: "https://localhost:5070/auth/azure/callback",
allowHttpForRedirectUrl: true,
clientSecret: "***************" ,
state: "************"
},
(iss, sub, profile, claims, accessToken, refreshToken, params, done) => {
process.nextTick(() => {
var user = usvc.findUserByAltId(profile.oid, "azure");
if(!user){
}
})
done(null, {id: profile.oid, name: profile.displayName, email: profile.upn, photoURL: "", token: params.id_token });
}));
Route Definitions
app.get("/auth/azure", azure.passport.authenticate(
'azure', {scope: ['Mail.Read','User.Read'], failureRedirect: '/'}))
app.post("/auth/azure/callback", azure.passport.authenticate(
"azure", {scope: ['Mail.Read','User.Read'], failureRedirect: "/error.html"}),
(req, res) => {res.redirect("/user")})
The OpenIDConnect work grand flow also will returns a JWT token for Authentication & Authorization. You can use the id_token in Authentication header for the resources. However, some operations in Graph APIs require an administrator permission.
You can try to run the following script in PowerShell to upgrade your Azure AD application's privilege.
Connect-MsolService
$ClientIdWebApp = '{your_AD_application_client_id}'
$webApp = Get-MsolServicePrincipal –AppPrincipalId $ClientIdWebApp
#use Add-MsolRoleMember to add it to "Company Administrator" role).
Add-MsolRoleMember -RoleName "Company Administrator" -RoleMemberType ServicePrincipal -RoleMemberObjectId $webApp.ObjectId