From where can I get the parameters for OAuth to consume confluence rest APIs
oauth_dict = {
'access_token': '',
'access_token_secret': '',
'consumer_key': '',
'key_cert': ''}
I need to automate creating page on confluence.
PS. its not a personal space but an organization space, so would I need special permissions ??
Thanks in advance!
Related
Graph API request for which you are seeing the problem
https://graph.microsoft.com/v1.0/me/messages
Graph API error message
{
'error': {
'code': 'InvalidAuthenticationToken',
'message': 'Access token validation failure. Invalid audience.',
'innerError': {
'request-id': '12e4940d-58af-4d64-98ab-4b3fe645afb8',
'date': '2020-05-05T13:57:38'
}
}
}
Description :
Implementing use case where user can extract emails in our application to download and consolidate attachments to central location using Microsoft graph.
Web application fronted is developed in angular and back-end is developed in spring boot REST API.
Integrating MSAL in angular to authenticate user and get valid tokens.
code configuration :
MsalModule.forRoot({
clientID: '83de5e6f-6a5b-48f4-8b64-5e8d6e70aa9d',
authority: 'https://login.microsoftonline.com/common/',
redirectUri: 'http://localhost:4200/TestLawyer/mail',
cacheLocation: 'localStorage',
// storeAuthStateInCookie: isIE, // set to true for IE 11
popUp: true,
consentScopes: ['user.read'],
unprotectedResources: ['https://www.microsoft.com/en-us/'],
protectedResourceMap: protectedResourceMap,
// logger: loggerCallback,
correlationId: '1234',
piiLoggingEnabled: true
})
I got the tokens in localstorage. In my solution i want to pass token to our spring boot rest server to extract emails using Microsoft Graph.
can you please help me on this like any tutorials or guidance to implement this use case.
The resource or scope of your token is incorrect.
You should set https://graph.microsoft.com/.default in the consentScopes.
You can decode your access token in https://jwt.io to see if the token includes the correct resource/scope.
I created an app in Azure and set it up to use Access and ID tokens.
I want to connect to different tenants and read SharePoint sites. Here are the permissions I've requested and received Admin Consent for:
For now, I have set up an App Secret but I do plan to move to a certificate later.
I have this code to get the access token and I do get an access token back:
const params = new URLSearchParams();
params.append("grant_type", "client_credentials");
params.append("scope", "https://graph.microsoft.com/.default");
params.append("client_id", process.env.client_id);
params.append("client_secret", process.env.client_secret);
var url = `https://login.microsoftonline.com/${tenant}/oauth2/v2.0/token`;
const response = await fetch(url,
{
method: 'POST',
body: params,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
);
However when I try to read the root site below
var url = "https://graph.microsoft.com/v1.0/sites?search=*";
const response = await fetch(url,
{
method: 'GET',
headers: { 'Authorization': `Bearer ${access_token}` }
}
);
I get this error:
error: {
code: 'AccessDenied',
message: 'Either scp or roles claim need to be present in the token.',
innerError: {
'request-id': 'ec47913f-2624-4d1c-9b27-5baf05ccebfd',
date: '2019-08-16T14: 15: 37'
}
}
I checked the token at https://jwt.io/ and indeed I do not see any entry for roles or scp.
It looks like I missed a step but I cannot figure out which step.
I am getting the token like this:
https://login.microsoftonline.com/${tenant}/oauth2/v2.0/token
What am I doing incorrectly?
The first thing to understand is that you cannot receive both Application and Delegated permissions in the same token, it is an either/or scenario. Which type you receive depends entirely on which OAuth Grant you used to request the token:
Authorization Code and Implicit return Delegated tokens with an scp property
Client Credentials return Application tokens with a roles property
The second thing is that you've requested scopes to two different APIs. Based on what you've selected, you won't have access to SharePoint through the Microsoft Graph because you've only requested access to the legacy SharePoint API. More importantly, you've only requested the Delegated User.Read scope for Graph so when you use Client Credentials to obtain the token, that token won't have any permissions.
In order to obtain an Application token for reading SharePoint sites, you'll need Sites.Read.All Microsoft Graph Application permission selected.
I am trying to wrap my head around using json webtoken (jwt) based authentication on a server coupled to using a third party (say google) to authenticate the user. Originally I've managed to build my own login and jwt handling scheme with jsonwebtoken on my nodejs server, but we need a client running on an iOS system to interact with it and started looking around for a solution where we don't have to code so much client code (requesting new token when expired etc.) and thought that we would use a third party library to do this for us.
The thing is I did not find anything that would do this for us. I found libraries that could handle connecting the client to a google api for the client, I found user identification handled by google, but didn't find anything that would handle actually getting a jwt that the server would except as a genuine user.
My question is essentially this: we have an iOS client and a nodejs server and would like to use google to authenticate our users and have the client call api-s on our nodejs server, with as much of the authentication process handled by some third party library (google's?), how should we get around to this?
As a note, I've seen passport but that seems to operate with sessions only, and I would have to solve the jwt handling by myself were I to use that.
The iOS part is not ready, but I managed to use google to authenticate and authorize without a session in the browser. The idea is, that the client logs in to google (see here for web app) and google graciously also gives you a token with the login, which will be good for the server. On the nodejs side I used passport and the google-id-token strategy (see on github). There are quite a few strategies for google out there, but this one works. Although, this has a shortcoming, it can't accept the token in the header, but I fixed that in a pull request (see here).
Since I had a bit of a problem of how to use the User.findOrCreate part of all the passport examples, I'll put in my code here that covers a full working example:
var passport = require('passport');
var GoogleTokenStrategy = require(passport-google-id-token)
passport.use(new GoogleTokenStrategy({
clientID: config.googleAuth.clientID,
clientSecret: config.googleAuth.clientSecret,
},
function(parsedToken, googleId, done) {
console.log(parsedToken);
console.log(googleId);
User.findOne({ 'google.id': googleId }, function (err, user) {
if (!user) {
var testuser = new User({
name: parsedToken.payload.name,
givenName : parsedToken.payload.givenName,
familyName : parsedToken.payload.familyName,
nameunderscore : parsedToken.payload.name.split(' ').join("_"),
admin: false,
email: parsedToken.payload.email,
settings: {save_folder:"default"},
'google.id' : googleId,
'google.email' : parsedToken.payload.email,
});
testuser.save(function(err) {})
}
return done(err, user);
});
}
));
User comes from mongodb in a separate js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('User', new Schema({
name: String,
nameunderscore : String,
givenName: String,
familyName: String,
admin: Boolean,
settings: {
save_folder: String
},
email: String,
google: {
id: String,
email: String
}
}));
And this is how I added the passport strategy to a router (note that session is set to false):
var apiRoutes = express.Router();
apiRoutes.use(passport.authenticate('google-id-token',{ session: false }));
Now every call to any route in apiRoutes must send on id_token with a valid google token to get access.
I have an email application for sending emails that was written in house. We have set it with the option to use OAuth 2.0 with GMail (personal and business accounts) and Outlook.com accounts without issues.
We can also authentication with user ids and passwords but we prefer OAuth 2.0 as we don't save passwords anywhere that way.
We now have requests to do this for Office365 accounts.
I notice that the hello message on the Office365 smtp server (smtp.office365.com port 587) does not offer the XOAUTH2 option.
250-BY2PR0601CA0005.outlook.office365.com Hello [xx.xx.xx.xx]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-AUTH LOGIN
250-8BITMIME
250-BINARYMIME
250 CHUNKING
But, the SMTP server for outlook.com does:
250-BLU436-SMTP14.smtp.hotmail.com Hello [xx.xx.xx.xx]
250-TURN
250-SIZE 41943040
250-ETRN
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-8bitmime
250-BINARYMIME
250-CHUNKING
250-VRFY
250-AUTH LOGIN PLAIN XOAUTH2
250 OK
Is this possible to do with Office365? If not, can we point Office365 users to the outlook.com smtp server (smtp-mail.outlook.com) or are they totally different?
We'd rather not use the APIs just for sending emails if possible as the RESTful APIs for each provider will of course be quite different.
The reason for using OAuth 2.0 when sending email with an Office365 account is that we don't want to have to store passwords on our server. Also, if the user changes their password, we won't know unless they tell us or manually update it on our system side.
Using OAuth 2.0 this would solve this problem and allow the application to flow like with other email providers.
I really wanted this feature too. It would make Office365 apps that need to send mail that much easier!
I did some hunting, and found this which appears to be as close to an official answer as we are going to get (and the answer is a flat no).
Not sure if I'm missing something, but isn't this what you want? Looks like this was posted back in February. Interestingly, this article says that Oauth is supported for M365, but NOT for outlook.com users.
https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth
I made one example using javax.Mail and OAuth for desktop application. It opens logon screen to get acccessToken. I followed multiple instructions so probably there are too many permissions and props in JavaMail but I succeeded to send mail.
My example program (Github)
PHP Example with OAuth2.
[On GitHub] (https://github.com/larsonnn/php_smtp_xoauth2_microsoft.php)
<?php
/* composer.json
"require": {
"phpmailer/phpmailer": "^6.6",
"league/oauth2-client": "^2.6",
"thenetworg/oauth2-azure": "^2.1"
}
*/
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\OAuth;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\PHPMailer;
use TheNetworg\OAuth2\Client\Provider\Azure;
require "vendor/autoload.php";
$mail = new PHPMailer(true);
$provider = new Azure([
'clientId' => '',
'clientSecret' => '',
"scopes" => ["https://outlook.office.com/SMTP.Send"],
"tenant" => "",
"defaultEndPointVersion" => Azure::ENDPOINT_VERSION_2_0,
]);
$mail->setOAuth(
new OAuth(
[
'provider' => $provider,
'clientId' => '',
'clientSecret' => '',
'refreshToken' => '',
'userName' => 'mymail#office_365_email.tld',
]
)
);
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'smtp.office365.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->AuthType = 'XOAUTH2';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->CharSet = PHPMailer::CHARSET_UTF8;
//Recipients
$mail->setFrom('mymail#office_365_email.tld', 'name');
$mail->addAddress('spam#example.tld', 'Spam');
//Content
$mail->Subject = 'Here is the subject';
$mail->Body = 'Hallo';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
I've been stuck on this for awhile. Does anyone know how to authenticate the Twitter Streaming API requests using OAuth? As of right now I'm authenticating via Basic Authentication, and I would like to completely switch over to OAuth. Also, I'm using Ruby on Rails if that helps.
Thanks
Connecting to the Twitter Streaming API via OAuth is done much the same as connecting via the REST API. Assuming you've already negotiated an access token, you sign and issue the request using the same signing algorithm as for a REST request. With the Streaming API, it's best to use header-based OAuth rather than query-string based.
Here's an example of a signed OAuth-based request for the sample end point:
GET http://stream.twitter.com/1/statuses/sample.json
Signature Base String example:
GET&http%3A%2F%2Fstream.twitter.com%2Fstatuses%2Fsample.json&oauth_consumer_key%3Dri8JxYK2ddwSV5xIUfNNvQ%26oauth_nonce%3DUJb0f3nHhFQkpkWkJzxnFT65xX1TZeuGjww6Q2XWs4%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1306947138%26oauth_token%3D819797-torCkTs0XK7H2Y2i1ee5iofqkMC4p7aayeEXRTmlw%26oauth_version%3D1.0
Authorization Header after signing:
Authorization: OAuth oauth_consumer_key="ri8JxYK2ddwSV5xIUfNNvQ", oauth_nonce="UJb0f3nHhFQkpkWkJzxnFT65xX1TZeuGjww6Q2XWs4", oauth_signature="bN14zlBIdCZCSl9%2B8UV8dB2VWjI%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1306947138", oauth_token="819797-torCkTs0XK7H2Y2i1ee5iofqkMC4p7aayeEXRTmlw", oauth_version="1.0"
Matt Harris has some sample code in PHP demonstrating connecting to the streaming API via OAuth: https://github.com/themattharris/tmhOAuth/blob/master/examples/streaming.php
After you register your application on http://dev.twitter.com this is how it's done in Perl:
#!/usr/bin/perl
use strict;
use AnyEvent::Twitter::Stream;
if ($ENV{FIREHOSE_SERVER}) {
$AnyEvent::Twitter::Stream::STREAMING_SERVER = $ENV{FIREHOSE_SERVER};
}
my $done = AE::cv;
binmode STDOUT, ":utf8";
my $streamer = AnyEvent::Twitter::Stream->new(
consumer_key => 'KEY',
consumer_secret => 'SECRET',
token => 'TOKEN',
token_secret => 'TOKEN SECRET',
method => "filter",
track => "KEYWORDS TO TRACK",
on_tweet => sub {
# CUSTOM CODE HERE
},
on_error => sub {
my $error = shift;
warn "ERROR: $error";
$done->send;
},
on_eof => sub {
$done->send;
},
);
$done->recv;
Try the OmniAuth gem which supports many external providers https://github.com/intridea/omniauth
You should use this gem : Tweetstream which sits on top of em-twitter