Power BI - Programmatically sign in - authentication

I'm trying to write a web app which embeds some Power BI reports. The data is on-premises so I cannot use the new solution available (Power BI Embedded). Now the inconvenience of using the old approach (https://powerbi.microsoft.com/en-us/documentation/powerbi-developer-integrate-a-power-bi-tile-or-report/) is that the consumer of the web page needs to be a Power BI user which needs to sign in in order for the web app to finally get an authentication token (there is a couple of page redirections that need to happen before).
So my question is, is there a way to do the Power BI Sign In in a programmatic way? so in that way I can just use one Power BI account for getting the content.

I am also experimenting there,
this thread helped me with just that (see post #8):
http://community.powerbi.com/t5/Developer/How-to-use-Power-BI-Rest-API-without-GUI-authentication-redirect/m-p/14218#
Basically:
POST request to:
https://login.microsoftonline.com/common/oauth2/token
Body, form-url-encoded:
grant_type: "password"
scope: "openid"
resource: "https://analysis.windows.net/powerbi/api"
client_id: your client id
client_secret: your client secret
username: that username
password: that usernames password
Then you directly get the token.
Also it might be good to consider security concerns like described here: http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-users-via-usernamepassword/ under "When NOT to Use This Feature"

It's just a coincidence that I am doing the same. Actually Power BI provides a Rest API to do this very easily. You need to register an app at Azure portal which will provide you with a client id and client secret. Now you can use the rest API and these details.
POST: https://login.microsoftonline.com/common/oauth2/token
and in the body, you need to send these details and in the header, you need to set
Content type : application/x-www-form-urlencoded
data: {
grant_type: password
scope: openid
resource: https://analysis.windows.net/powerbi/api
client_id: {Client ID}
username: {PBI Account Username}
password: {PBI Account Username}
client_secret: {Enter client secret here}
}

Related

Clarification on Google Authentication and Authorization, with OAuth in 2022

I am writing an App and am trying to leverage Google for A&A. The app itself relies on access to the users Google Calendar, and so initially I leveraged their updated OAUTH2 library for A&A.
Here is my flow:
User goes to the index.html which has "https://accounts.google.com/gsi/client" script and google.accounts.oauth2.initCodeClient is called with my client_id, scopes, redirect url
<script src="https://accounts.google.com/gsi/client"></script>
<script>
let client;
function initClient() {
client = google.accounts.oauth2.initCodeClient({
client_id: 'xxxxx-xxxx.apps.googleusercontent.com',
scope:
'https://www.googleapis.com/auth/userinfo.profile \
https://www.googleapis.com/auth/userinfo.email \
https://www.googleapis.com/auth/calendar.readonly \
https://www.googleapis.com/auth/calendar.events',
ux_mode: 'redirect',
redirect_uri: 'http://localhost:5000/oauth2callback',
});
}
// Request an access token
function getAuthCode() {
client.requestCode();
}
The user clicks the login button, which kicks off requestCode() and they begin the login flow. They login or select their google account, then besides the unapproved app screen, they get to the consent screen with my requested scopes.
After, they are redirected to my expressjs endpoint and using the "googleapis" library I exchange with id_token for the access and refresh tokens.
...
const { tokens } = await oauth2Client.getToken(req.query.code); //exchange code for tokens
const userInfo = (
await oauth2Client.verifyIdToken({
idToken: tokens.id_token,
audience: config.google.clientID,
})
).payload;
if (!indexBy.email[userInfo.email]) { // check if user exists
const newUser = {
name: userInfo.name,
email: userInfo.email,
o_id: userInfo.sub,
picture: userInfo.picture,
r_token: tokens.refresh_token,
};
...
Ok, all good.... but not quite. The problem is, that next time the user wants to login to the app, they go through the entire flow again, including the consent screen (again).
So, after going through more docs, even looking at examples from google. I was surprised and I noticed that many of those apps used the passport oauth2 plugin :( Something i've done in the past, but was hoping to avoid that with the recently updated Google client and nodejs libraries.
Ok, how to not prompt for consent screen on subsequent logins?
Maybe separate A&A, so first I use "Sign In With Google" for Authentication, then when I get the user info, check if the user is already registered (hence I have already saved the refresh token) and they start the app.
On the other hand, if they are new (not in existing app user collection), after authenticating, I will then call the OAUTH2 authorization redirect, so again they on Googles site, this time to do the scopes api confirmation.
So, first question, is that the best practice with most apps with leverage a Google API via OAuth? To first Authenticate, then possibility Authorize (as needed). Hopefully this will still work ok when things come up with expired/invalid refresh token (fingers crossed the default google library handles that).
When doing the Authorize for consent, can I pass something from the previous Authenticate flow so they don't need to do that again.
Or maybe when doing the Authenticate process (Google Identity Service), there is some flag or param so that if they have already consented, they don't have to do that again on subsequent logins.
Incase I wasn't clear, in a nutshell the question is: should I be doing Authenticate for login, separately from Authorization (oauth2 token). Or should I go right into the Authorization flow, which first Authenticates the user, and can I skip the Authorization consent screens if they've already done that. Or maybe there's another way which is the best practice.
Thanks for your attention.
Background info
Authentication is the act where by a user logs in into a system using their login and password. With authentication we know that the user is behind the machine. For this we use Open id connect, which was built on top of Oauth2. Open id connect returns and id_token which can be used to identify the user, it is often a jwt containing some claims to identify the subject or the user behind the Authentication.
The scope used for open id connect is profile and email. open id connect grants you consent to access a users profile information.
This is an example of the decrypted id token returned by google from a simple call using profile scope only. All this id token is telling you is who the user behind the machine is.
{
"iss": "https://accounts.google.com",
"azp": "4074087181.apps.googleusercontent.com",
"aud": "4074087181.apps.googleusercontent.com",
"sub": "1172004755672775346",
"at_hash": "pYlH4icaIx8PssR32_4qWQ",
"name": "Linda Lawton",
"picture": "https://lh3.googleusercontent.com/a-/AOh14GhroCYJp2P9xeYeYk1npchBPK-zbtTxzNQo0WAHI20=s96-c",
"given_name": "Linda",
"family_name": "Lawton",
"locale": "en",
"iat": 1655219027,
"exp": 1655222627
}
In the same call google also returned an access token. Now my call contained only the scope for profile, due to the fact that its open id connect. This means that I will only have access to the data that the profile scope would grant access to. In this case most of what is behind the Google people api.
Note: The user does not see a consent screen with open id connect, even though they are consenting to profile scope. It is assumed by signing into your account that the system you are logging into would have access to your profile info.
Authorization
Authorization is the process by which a user grants your application authorization to access their private user data. The user is shown a consent screen where they consent to your application accessing data defined by some scopes.
In the case of google calendar api there are serval
https://www.googleapis.com/auth/calendar See, edit, share, and permanently delete all the calendars you can access using Google Calendar
https://www.googleapis.com/auth/calendar.events View and edit events on all your calendars
https://www.googleapis.com/auth/calendar.events.readonly View events on all your calendars
https://www.googleapis.com/auth/calendar.readonly See and download any calendar you can access using your Google Calendar
https://www.googleapis.com/auth/calendar.settings.readonly View your Calendar settings
In this case you are only given an access token this is again Oauth2 it is authorization to access the users calendar data it is not authentication this is not related to login.
Your question
So, first question, is that the best practice with most apps with leverage a Google API via OAuth? To first Authenticate, then possibility Authorize (as needed).
You would do both at the same time.
When you authencation your user make sure to include your google calendar scope then the access token and refresh token returned will grant you access to google calendar.
I am going to assume that you have some kind of user system. When you store the user be sure to store the refresh token that is returned.
As far as Authentication goes i will assume you either have a remember me system which will set a cookie on their machine and remember the user so that you can then get the refresh token from their system the next time they come back.
If they did not chose to select a remember me option then will then have to login every time they visit your site but part of the login will return the "sub": "1172004755672775346", this is the users id on google system so you can use that in your database to match the user when they come back.
Your question is quite complex and will depend upon the type of system you have what it is designed to do as well as what programming language you are using. That being said I hope this very long answer clears things up a bit.

Is there a way to know which aad to use for authenticating in advance?

I have a UWP app that needs to authenticate, and I would like to avoid asking the user to choose which national cloud to authenticate with. I could just try them all, but I hope there is a better way to tell which Azure Active Directory the user belongs to (.us or .com)
Native apps can discover the Azure AD endpoint for a national cloud by passing an instance_aware parameter in the authorization request to the global Azure AD endpoint. This is done in the acquireToken call, where you need to pass in instance_aware = true as an extra query parameter when initializing the Authentication context.
From the Authentication result, you can read and store the cloud_instance_host_name attribute to learn the correct Azure AD endpoint. You must pass this value as the authority to re-initialize the Authentication context for the subsequent acquireTokenSilent calls to succeed.
An example ADAL.Net code snippet is below:
var authenticationContext= new AuthenticationContext(Authority, false, new TokenCache());
var authenticationResult = await authenticationContext.AcquireTokenAsync(resource,
clientId,
redirectUri,
platformParameters,
userIdentifier,
"instance_aware=true"
);
Also, here are example OAuth request and responses using the instance_aware parameter:
Request:
https://login.microsoftonline.com/common/oauth2/authorize?
response_type=code&
client_id=f5d01c1c-abe6-4207-ae2d-5bc9af251724&
instance_aware=true&
redirect_uri=http://localhost/appcheck&
resource=00000002-0000-0000-c000-000000000000
Response:
http://localhost/appcheck?
code=AQABAAIAAQDnLpu3ikefR73l_aNlxt5x0ulCIcjaTlOoWp412SJ2Oxlih65_h_Ju3OdOqpEy-mz0giFzZtU2_MbIgSG12e6RjwxpcaXaVPene_lMtmR2DPexUZZ3QhFRl8Vgl76SidX_nJ1CN-hJAejCi139FG_YZit4ePbiNySC3zR9GcP3B3St7HDsdEhMh1Vi1XHSSKfpgVqzLnOiBSO_jXrm1WJVqXSlt4_M_KO92Gdpbpy8H7zpsRg0O6blbuSw_83YUcj0w1gEfByHZP2Hk5AToDy_DWepPqJ0GWOJYeKcfIiEFleNYaeyEJDDuMyFhV16IOT28mq1oNOWL0dnhjwr-OV0JnyajQCT_LZzapxp7Y-8jSPDgW6SR878sgrq6CS2z3Zos8_T31n4DucQaPqv2Ae_jxlGHHSENBFy2RhHy397B7BBohXGqhDj_OdIroimDOJGVewn612gQOA6-9p0llv-PNd7vj9VZL-9Q8kEuYuhTqaBsH3yKm6y9FfgxMWovVkYtDt4YgxbqCV2Wb_lzImtyTHKxazn6YhH6R2pCvFdVSAA&
cloud_instance_name=microsoftonline.us&
cloud_instance_host_name=login.microsoftonline.us&
cloud_graph_host_name=graph.windows.net&
msgraph_host=graph.microsoft.com&
session_state=899b8a55-034f-4dcd-8b4b-888b7874b041
One way to "spot check" which cloud/AAD environment the user belongs to is by making a call to the Azure AD OpenID Connect discovery endpoint:
https://login.microsoftonline.com/place_tenantname_or_tenantid_here/.well-known/openid-configuration
For Azure Government, "USG" or "USGov" as the value in the tenant_region_scope field will indicate tenants that should be using login.microsoftonline.us.
I hope this helps. Let me know if not.
Bernie

OAuth Implicit flow Access Token expires every hour

I'm having a problem with the OAuth Implicit flow for the Google Assistant.
I managed to set up a OAuth server and got it to work. Here's the flow:
The user Is redirected to my endpoint, authenticates with a Google account, and gets send back to the Assistant with an Acces Token and result code=SUCCES.
In my fullfilment I get the users email address by doing a https request to: https://www.googleapis.com/plus/v1/people/me?access_token=access_token.
I then find the matching user in my database and add the acces token to the database for this user.
The next time the user logs in I check the acces token and greet the user by their name.
Now the problem is that this is the Implict flow which according to the documentation should have an access token that never expires:
Note: Google requires that access tokens issued using the implicit
flow never expire, so you don't need to record the grant time of an
access token, as you would with other OAuth 2.0 flows.
But the Assistant forces me to re-authenticate every hour, meaning the access token did expire.
My question is: Is this flow correct or am I missing something? Is there something I've done wrong in my OAuth endpoint?
I based my endpoint on https://developers.google.com/identity/protocols/OAuth2UserAgent.
<html>
<head>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<meta name="google-signin-client_id" content="CLIENT_ID">
</head>
<body>
<script>
var YOUR_CLIENT_ID = 'CLIENT_ID';
function oauth2SignIn() {
// Google's OAuth 2.0 endpoint for requesting an access token
var oauth2Endpoint = 'https://accounts.google.com/o/oauth2/v2/auth';
// Create element to open OAuth 2.0 endpoint in new window.
var form = document.createElement('form');
form.setAttribute('method', 'GET'); // Send as a GET request.
form.setAttribute('action', oauth2Endpoint);
//Get the state and redirect_uri parameters from the request
var searchParams = new URLSearchParams(window.location.search);
var state = searchParams.get("state");
var redirect_uri = searchParams.get("redirect_uri");
//var client_id = searchParams.get("client_id");
// Parameters to pass to OAuth 2.0 endpoint.
var params = {
'client_id': YOUR_CLIENT_ID,
'redirect_uri': redirect_uri,
'scope': 'email',
'state': state,
'response_type': 'token',
'include_granted_scopes': 'true'
};
// Add form parameters as hidden input values.
for (var p in params) {
var input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', p);
input.setAttribute('value', params[p]);
form.appendChild(input);
}
// Add form to page and submit it to open the OAuth 2.0 endpoint.
document.body.appendChild(form);
form.submit();
}
oauth2SignIn();
</script>
</body>
</html>
It sounds like what you are doing is having the user log into your page, and using this to get an auth token from a Google service. You're then turning this around and passing this back to the Assistant and calling this the Identity Flow.
While clever - this isn't the Identity Flow.
This is you using the Auth Code Flow to authenticate the user with Google, and then returning this token to Google and pretending this is an Identity Flow token. However, since you're using the Auth Code Flow, the auth tokens that you get back expire after an hour. (You can check out the lifetime in the information you get back from Google.)
If you are trying to do Account Linking and not manage anything yourself, you need to actually implement an OAuth server that proxies the Auth Code Flow requests from the Assistant to Google and the replies from Google back to the Assistant. While doable, this may be in violation of their policy, and isn't generally advised anyway.
Update to address some questions/issues in your comment.
using the Google Auth endpoints doesn't store the session either, so you'd still have to re-authenticate every hour
Since the Google Auth endpoints use the Auth Code Flow, you can use the offline mode to request a refresh token. Then, when an auth token expires, you can use the refresh token to get a new auth token. So you still have a long-term authorization for access and can get the short-term token to do the work you need.
Trying to shoehorn this into the Identity Flow, however, doesn't work. (And would be a really bad idea, even if it did.)
Can you provide some clarification on how to create an endpoint for the implicit flow?
Beyond the step-by-step description of what your OAuth server code can do in the Assistant documentation, I'm not sure what clarification you need. Your OAuth server fundamentally just needs to:
Be able to have a user:
Connect to an HTTPS URL
Authenticate themselves
Authorize the Assistant to contact your service on their behalf
Return a code by redirecting the user to Google's URL with a code in the parameter
And the Action webhook needs to be able to:
Accept this code as part of the request from the Assistant and
Figure out who the user is from this code. (ie - map the code to a user account in your system.)
There are a variety of ways you can do all of that. The OAuth server and Action could be on the same server or separate, but they at least need to have some agreement about what that code is and how that maps to your user accounts.
If your primary need is to access Google APIs on behalf of your user - then the user account that you have will likely store the OAuth tokens that you use to access Google's server. But you should logically think of that as separate from the code that the Assistant uses to access your server.
(As an aside - those steps are for the Identity Flow. The Auth Code Flow has a few more steps, but the fundamentals are similar. Especially on the Action side.)

Access Power BI API with Python

My requirement is to push real time data into Power BI using Python to first read from a database and then send the data inside a Streaming dataset in Power BI.
The first thing I want is to make a simple "get" call to Power BI.
The official documentation explains the processes of connecting to Power BI via the REST API for either a Client App or a Web App.
However, I'm using Python - not sure if that is either a client app or a web app.
Anyway, I am able to get the accessToken using the adal library and the method .acquire_token_with_client_credentials, which asks for authority_uri, tenant, client_id and client_secret (notice this is not asking for username and password).
By the way, I've also tried getting the accessToken with .acquire_token_with_username_password, but that didn't work.
Unfortunately, when I use the below code with the obtained accessToken, I get a response 403.
#accessToken is received using the adal libary
headers = {'Authorization': 'Bearer ' + accessToken, 'Content-Type': 'application/json'}
read_datasets = requests.get('https://api.powerbi.com/v1.0/myorg/datasets', headers=headers)
#shockingly, this will result in a response 403
After reading other stackoverflow posts and looking at console apps, I believe the reason this doesn't work is because there is no user sign-in process.
This thread mentions that using Client Credentials is not enough (it is enough to get the accessToken, but not enough to use the APIs)
Not sure how to proceed, but what I need is perhaps a way to keep using this adal template that gives me the accessToken, and also to provide my username and password (if required), and together with the accessToken, to access the APIs.
I see that you've answered this over on the PowerBI forums:
https://community.powerbi.com/t5/Developer/Access-Power-BI-API-with-Python/m-p/190087#M6029
For future reference of anyone visiting this in the future:
Get your token using the python adal library and the appropriate method. Once you've got your token, you pass that in as part of your request headers like so:
url = f'{self.api_url}/v1.0/myorg/groups/{self.group_id}/datasets'
headers = {
'Authorization': f'Bearer {self.token["accessToken"]}'
}
Where api_url is https://api.powerbi.com, group_id is your group_id and token is the token dict you got from acquire_token_with_username_password.
From there you'll be able to make all the PowerBI API calls you need.

What is the accepted practice for URL login in API REST?

If I have: users, and I need to log in with api rest. What's the best way to do it?
1 /users/id/password
2 /users?id=id&password=pass
If I use the second option, I will need to validate if there are get parameters. If not, It will return all results.
This is not the answer I want now:
REST API Login Pattern
The link you added is valid, REST APIs are stateless, so they can't login in the traditional way, you MUST store the client session on the client side. If you use HTTPs you won't need login. If you don't, then your API won't be secure, so using password won't have any protection. I think that's all.
If you want to both stay stateless and send tokens, then you have to sign for example the user id on the server. So by the next request you can send both the user id and the signature instead of the email and password. This way the server will know that you have been logged in earlier to the account the user id belongs to. I don't recommend you to use the URI for sending sensitive data. It is better to use the request body with POST. The URI structure depends on your taste, I would use something like this:
POST /users/1/tokens/ {email: "..", password: ".."}
201 {id: 1, expires: "..", signature: ".."}
Be aware that you have to send every variables you signed, so, the id, the expiration time (added by the server), probably the ip address, a random number, etc... You MUST not store anything on the server (including the token), otherwise the communication will be stateful.
I am not a security expert, but I think this solution does not make sense in most of the cases, so you need to justify somehow, why your API needs it. It is used for example for signing each request coming from 3rd party clients. If you cannot justify it, I recommend you to use the default approach, which is using HTTPS, logging in on the client side and sending HTTP Authorization header with email and password by every request.
I would use a POST method with the login / password provided within the payload:
POST /login
Content-Type: application/json
{ username: 'some username', password: 'some password' }
In addition, the following link could give you some hints about authentication within RESTful services:
Implementing authentication with tokens for RESTful applications - https://templth.wordpress.com/2015/01/05/implementing-authentication-with-tokens-for-restful-applications/
Hope it helps you,
Thierry