GitHub REST API to create Issues with creator parameter - node.js

NodeJS APP:
I try to create github issues from my nodeJS application using Github REST API "https://github.com/api/v3/repos/{owner}/{repo}/issues" with the following parameter and Token. I am passing the parameter "creator" to display who created/commented this issue. But it is displaying the owner of the gitHub Access token as the creator of the issue. How to fix this
request.post({
url: githubApiEndpoint + "/repos/" + options.orgName + "/" + options.repoName + "/issues",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + options.accessToken
},
body: JSON.stringify({
title: "creating issue",
body: "description of issue",
creator: "username",
labels: ["question"]
})
}, callback);

As per the documentation you cannot. creator is no valid parameter. Besides that your example is syntactically incorrect.

You can't. OAuth protocol aims to provide a way to do actions in the name of a specific user, the user who owns the token you get.
So, if you create an issue, the author/creator will be the token owner. You cannot do actions in behalf of another person if you don't have his token

Related

Auth0 Only receiving access token from token end point

I am following the guide to retrieving the id, access, and refresh token for a nodejs project. I am utilizing authorization_code flow, where the user logs in via the default auth0 account login(non-3rd party login).
When I make the request successfully I only receive the users access token, but not the id token.
I am making the request to the /oauth/token with the authorization code present.
Here is the guide I am following: Call Your API Using the Authorization Code Flow
Here is my server code:
const getAuth0Tokens = async(code)=>{
console.log(`code => here ${code}`)
var options = {
method: 'POST',
url: 'https://********.us.auth0.com/oauth/token',
headers: {'content-type': 'application/x-www-form-urlencoded'},
data: new URLSearchParams({
client_id: '*************clientId**********',
client_secret: '*************clientSecret**********',
audience: 'https://localhost:3000/login.html',
grant_type: 'authorization_code',
redirect_uri:"https://localhost:3000/login.html",
code:`${code}`
})
};
return await axios.request(options).then(function (response) {
console.log("data from auth0 token call " + JSON.stringify(response.data));
const {id_token,access_token, refresh_token, token_type, expires_in} = response.data;
return {id_token, access_token, refresh_token, token_type, expires_in}
}).catch(function (error) {
console.error(error);
});
Here is the response:
The request is returning successfully with 200 status response. For more context I am on the free subscription account tier.
Could the error be due to mu auth0 account configuration? or maybe something else.
You need to specify the scope with offline_access in order to retrieve the refresh_token. It is also mentioned in the same guide which you have linked above
Include offline_access to get a refresh token (make sure that the Allow Offline Access field is enabled in the Application Settings).
So you can just add new parameter scope: offline_access along with your other params
It looks like your scope is empty. You might need to add openid and profile to the scope param to get the id token.
It would help if you could show your authorize request too (step 1 in that guide).
Then, ya, what Umakanth said about the refresh token. Need to add offline_access to the scope.
Include offline_access to get a refresh token (make sure that the Allow Offline Access field is enabled in the Application Settings).

Graph API does not accept my application permissions' scope

Edit:
The problem was a simple typo in the Header. You're probably wasting your time here
In essence, I have the same problem as described here. It's a somewhat different usecase and I'll try to provide as much context as I can in the hopes that someone will be able to solve the problem.
So, this has to do with Azure, which seems to be an Alias for "Crazy problem generator". My apologies.
I'm trying to write a Service in NodeJS which has the purpose of synchronizing another app's database with data from Azure.
For that reason, I'm using msal-node's Client Credential Flow as described here.
I find their comment // replace with your resource quite ridiculous, as I have not found a single full example online that specifies the format that should be used.
Intuitively, I would use something like
['GroupMember.Read.All']
//or
['https://graph.microsoft.com/GroupMember.Read.All']
Unfortunately, this does not work. Luckily, I get an error that describes the problem (even if only when this is the only scope I use, othewise the error is garbage):
{
// ...
errorMessage: '1002012 - [2022-05-23 11:39:00Z]: AADSTS1002012: The provided value for scope https://graph.microsoft.com/bla openid profile offline_access is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).\r\n'
}
Okay, let's do that:
['https://graph.microsoft.com/GroupMember.Read.All/.default']
Now, the app actually performs a request, but unfortunately, I get
{
// ...
errorCode: 'invalid_resource',
errorMessage: '500011 - [2022-05-23 11:42:31Z]: AADSTS500011: The resource principal named https://graph.microsoft.com/GroupMember.Read.All was not found in the tenant named <My company name, not an ID as shown in some places>. This can happen if the application has not
been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant.\r\n' +
'Trace ID: <some id>\r\n' +
'Correlation ID: <some id>\r\n' +
'Timestamp: 2022-05-23 11:42:31Z - Correlation ID: <some id> - Trace ID: <some id>',
}
And yet it is there
And I am able to get a token for the .default scope. That's just not good for anything.
The important parts of the actual code:
import fetch from 'isomorphic-fetch';
import * as msal from '#azure/msal-node';
// got env variables using dotenv package
// this is Typescript
const msalConfig = {
auth: {
clientId: process.env.OAUTH_APP_ID!,
authority: process.env.OAUTH_AUTHORITY!,
clientSecret: process.env.OAUTH_APP_SECRET!
},
system: {
loggerOptions: {
loggerCallback(loglevel: any, message: any, containsPii: any) {
console.log(message);
},
piiLoggingEnabled: false,
logLevel: msal.LogLevel.Verbose,
}
}
};
const msalClient = new msal.ConfidentialClientApplication(msalConfig);
const allCompanyMembersGroupId = '<some id>';
const tokenRequest = {
scopes: ['https://graph.microsoft.com/GroupMember.Read.All/.default']
};
msalClient.acquireTokenByClientCredential(tokenRequest).then(response => {
console.log('Got token:', response);
fetch(`https://graph.microsoft.com/v1.0/groups/${allCompanyMembersGroupId}/members`, {
method: 'GET',
headers: {
Authority: `Bearer ${response!.accessToken}`
}
}).then((res: any) => {
console.log('Got response:', res);
})
});
As mentioned, the request isn't performed with my GroupMember.Read.All scope. With the default scope, I get a 401 unauthorized error.
So, these are my questions:
How to fix this?
Okay, if it you don't know how to fix it, what is the exact format required for the scope? Is the prefix https://graph.microsoft.com correct, even for my specific app?
Is this the correct library to use, or is this just broken code or not intended for such use? The other question I linked to above mentions that requests were successful using Postman, just not this lib...
Thanks heaps for any advice!
It's a problem with the headers. It should be Authorization instead of Authority.
The error is in the following variable:
const tokenRequest = {
scopes: ['https://graph.microsoft.com/GroupMember.Read.All/.default']
};
the correct one would be:
const tokenRequest = {
scopes: ['https://graph.microsoft.com/.default']
};
Note: When using Client Credentials flow, it is a must to specify the scope string tailing with "/.default".
For eg:
If you are trying to get an access-token using client credentials
flow for MS Graph API, the scope should be
"https://graph.microsoft.com/.default".
If you are trying to get an
access-token using client credentials flow for a custom API which is
registered in AAD, the scope should be either
"api://{API-Domain-Name}/.default" or
"api://{API-Client-Id}/.default".

Cypress SSO Azure without Client_secret

I'm struggling to solve an issue that I got on trying to login via Single Sign On from Microsoft Azure using Cypress. It is possible to do it without using the Client_Secret? How can I do it?
I've been spending more than a week trying to solve this situation...
I'm a junior on this, so if you could help-me I would be very grateful.
Thanks a lot,
Yes, you can. Navigate to your AD App in the portal -> Authentication -> set Allow public client flows to Yes like below.
Then in the blog, in step Cypress utility for mimicking react-adal, it uses the client credential flow, there is a comment post by #Bryce Kolton under the blog, he uses the ROPC flow, in this flow, you could use it without Client_Secret via a public client App as you changed above(Allow public client flows), just refer to it.
/* eslint-disable no-underscore-dangle */
import { AuthenticationContext } from ‘react-adal’;
import { azTenantId, azClientId } from ‘../../server/config/environment’;
// Need to get data points from server’s environment, not src
const adalConfig = {
tenant: azTenantId,
clientId: azClientId,
cacheLocation: ‘localStorage’,
replyUrl: ‘/’,
endpoints: {
api: ”,
},
};
const authContext = new AuthenticationContext(adalConfig);
export default async function doLogin() {
// getCachedToken also does an expiration check so we know for sure the tokens are usable
if (
!authContext.getCachedToken(adalConfig.endpoints.api)
|| !authContext.getCachedToken(adalConfig.clientId)
) {
const response = await cy.request({
method: ‘POST’,
url:
‘https://login.microsoftonline.com/mercedesme.onmicrosoft.com/oauth2/token’,
// qs: { ‘api-version’: ‘1.0’ }, // uncomment if your consuming resource expects the ‘aud’ to have a prefix of ‘sn:’
headers: {
‘cache-control’: ‘no-cache’,
‘content-type’:
‘multipart/form-data; boundary=—-WebKitFormBoundary7MA4YWxkTrZu0gW’,
},
form: true,
body: {
grant_type: ‘password’,
response_type: ‘code’,
client_id: ‘[[yourappsclientid]]’,
username: ‘[[yourtestuzseremail]]’,
password: ‘[[yourtestuserpassword]]!’,
scope: ‘openid’,
resource: ‘[[some-resource-id]]’,
},
});
// Store the token and data in the location where adal expects it
authContext._saveItem(authContext.CONSTANTS.STORAGE.IDTOKEN, response.body.access_token);
authContext._saveItem(
authContext.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + adalConfig.endpoints.api,
response.body.access_token,
);
authContext._saveItem(
authContext.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + adalConfig.clientId,
response.body.access_token,
);
authContext._saveItem(
authContext.CONSTANTS.STORAGE.EXPIRATION_KEY + adalConfig.endpoints.api,
response.body.expires_on,
);
authContext._saveItem(
authContext.CONSTANTS.STORAGE.EXPIRATION_KEY + adalConfig.clientId,
response.body.expires_on,
);
authContext._saveItem(
authContext.CONSTANTS.STORAGE.TOKEN_KEYS,
[adalConfig.clientId].join(authContext.CONSTANTS.RESOURCE_DELIMETER)
+ authContext.CONSTANTS.RESOURCE_DELIMETER,
);
}
}
To use the ROPC flow successfully, make sure your scenario meets the requirements below, e.g. your user account is not MAF-enabled.

Hue API remote Basic Authentication

I'm having issues using the Basic Authentication method for the Hue remote API.
When POSTing to https://api.meethue.com/oauth2/token?code={code}&grant_type=authorization_code with the built Authorization-header I get this response:
{
"fault": {
"faultstring": "Invalid client identifier {0}",
"detail": {
"errorcode": "oauth.v2.InvalidClientIdentifier"
}
}
}
I assume then that I am building the token in the wrong way, but the docs (see Basic Authentication) is a bit vague on what to actually do.
The docs says that I should send a header via this format: Authorization: Basic <base64(clientid:clientsecret)> and that it should be encoded in base-64:
you would need to send a Basic authorization header that includes a base64 encrypted hash of your clientid and clientsecret.
And from the Digest-method, I assume MD5 is used and then digested to base-64.
Here's what I've tried, all with the same error-code:
'Basic ' + crypto.createHash('md5').update(clientId + clientSecret).digest('base64')
'Basic ' + crypto.createHash('md5').update(clientId + ':' + clientSecret).digest('base64')
'Basic ' + (clientId + ':' + clientSecret).toString('base64')
'Basic ' + (clientId + clientSecret).toString('base64')
What more is there to try?
#Tokfrans
you can create a test token with clientid:secret by using the site
https://www.base64encode.org/
it will give you a valid token that you can use with Basic authentication
keep in mind that you first need to get a code which you can then use to get a accesstoken
https://api.meethue.com/oauth2/auth?clientid=xxxxxx&appid=xxxxx&deviceid=xxxx&devicename=xxxx&state=xxxx&response_type=code

SP.Utilities.Utility.SendEmail access denied

I am using CSOM("SP.Utilities.Utility.SendEmail") to send email to the members of my site collection.
var deferred = $q.defer();
$http({
url: webUrl + "SP.Utilities.Utility.SendEmail",
method: "POST",
data: data,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": xdigestdata.d.GetContextWebInformation.FormDigestValue,
"content-Type": "application/json;odata=verbose"
}
}).then(function(result, status) {
console.log("Email Sent!");
deferred.resolve(result);
}, function(result, status) {
console.log("sendEmails: " + JSON.stringify(result2))
deferred.reject(result);
});
I got no problem using it, I wass able to send and receive the email I am sending but I got problem when the application I created was being used by a user that only has "Members" permission. I am getting the following error. Note when I switch back my test account as Site Owner I was able send again my email. Is there any specific permission that I need to give to members group to send email or is there any specific list that members group should have access to, to send email?
"-2147024891, System.UnauthorizedAccessException"
message
:
lang
:
"en-US"
value
:
"Access denied. You do not have permission to perform this action or acc
Users need to have the Manage Alerts - Manage alerts for all users of the Web site Permission on the site level to send emails. See this and this for more details on the Manage Alerts permission.
You will need to enable this for the group or users in Permission Levels : Edit Permission Level

Resources