Auth0 getting powerBI token - azure-active-directory

I am authentocating using Auth0 and my provider is wadd
I am trying to get the token to use with PowerBi, I have tried the follow console app (token, is from the above, clientId and Secret are the same as what is used in my Auth0 connector for the connection to my AzureAD
var cred = new ClientCredential(clientId, secret);
var access_token_from_client_side = token;
var context = new AuthenticationContext("https://login.windows.net/common");
var res = context.AcquireTokenAsync("https://analysis.windows.net/powerbi/api",
functionCred, new UserAssertion(access_token_from_client_side)).ConfigureAwait(false).GetAwaiter().GetResult();
Console.WriteLine(res.AccessToken);
I get the following error
{"error":"invalid_grant","error_description":"AADSTS50013: Assertion failed signature validation. [Reason - The provided signature value did not match the expected signature value., Thumbprint of key used by client: '...', Found key 'Start=12/26/2019 00:00:00, End=12/25/2024 00:00:00']\r\nTrace ID: ...\r\nCorrelation ID: ...\r\nTimestamp: 2020-02-25 21:13:48Z","error_codes":[50013],"timestamp":"2020-02-25 21:13:48Z","trace_id":"...","correlation_id":"b890dfad-1d6f-4e4a-ab15-34328818c295","error_uri":"https://login.microsoftonline.com/error?code=50013"}
My goal is to get a Token to use for PowerBI starting with my AzureAD auth token. I have allow the application permissions for PowerBI from Azure
What am I missing?

Related

Forbidden error when calling Microsoft Graph from Java Application using Application ID

List SCOPES = Arrays.asList("https://graph.microsoft.com/.default");
final ClientSecretCredential credential = new ClientSecretCredentialBuilder()
.clientId(applicationId)
.clientSecret(secret)
.tenantId(tenantId)
.build();
final TokenCredentialAuthProvider authProvider_new = new TokenCredentialAuthProvider(SCOPES, credential);
GraphServiceClient graphClient = GraphServiceClient
.builder()
.authenticationProvider(authProvider)
.buildClient();
graphClient.users().buildRequest().get();
With
compile group: 'com.microsoft.azure', name: 'azure-spring-boot', version: '2.3.5'
compile group: 'com.google.guava', name: 'guava', version: '28.2-jre'
compile group: 'com.azure', name: 'azure-identity', version: '1.2.5'
compile group: 'com.microsoft.graph', name: 'microsoft-graph', version: '3.5.0'
I've added all the necessary permissions to the application, and it's been consented in Active Directory, but same response.
It works using this code, after I sign in with a user account:
final DeviceCodeCredential credential1 = new DeviceCodeCredentialBuilder()
.clientId(applicationId)
.challengeConsumer(challenge -> System.out.println(challenge.getMessage()))
.build();
But I want to use ClientSecretCredential and use the client secret, not create a challenge.
Update: The error message I get is
SEVERE: Throwable detail: com.microsoft.graph.http.GraphServiceException: Error code: Authorization_RequestDenied
Error message: Insufficient privileges to complete the operation.
GET https://graph.microsoft.com/v1.0/users
SdkVersion : graph-java/v3.5.0
403 : Forbidden
Here's a link of the permissions the app has in API Permissions
I also have the following permissions to Azure Rights Management Services in case it helps
Application.Read.All, Content.DelegatedReader, Content.SuperUser
Based on your granted permission you missed the User.ReadWrite and User.ReadWrite.All Please add that permission .
For more details refer this document:

Service account request to IAP-protected app results in 'Invalid GCIP ID token: JWT signature is invalid'

I am trying to programmatically access an IAP-protected App Engine Standard app via Python from outside of the GCP environment.
I have tried various methods, including the method shown in the docs here: https://cloud.google.com/iap/docs/authentication-howto#iap-make-request-python. Here is my code:
from google.auth.transport.requests import Request
from google.oauth2 import id_token
import requests
def make_iap_request(url, client_id, method='GET', **kwargs):
"""Makes a request to an application protected by Identity-Aware Proxy.
Args:
url: The Identity-Aware Proxy-protected URL to fetch.
client_id: The client ID used by Identity-Aware Proxy.
method: The request method to use
('GET', 'OPTIONS', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE')
**kwargs: Any of the parameters defined for the request function:
https://github.com/requests/requests/blob/master/requests/api.py
If no timeout is provided, it is set to 90 by default.
Returns:
The page body, or raises an exception if the page couldn't be retrieved.
"""
# Set the default timeout, if missing
if 'timeout' not in kwargs:
kwargs['timeout'] = 90
# Obtain an OpenID Connect (OIDC) token from metadata server or using service
# account.
open_id_connect_token = id_token.fetch_id_token(Request(), client_id)
print(f'{open_id_connect_token=}')
# Fetch the Identity-Aware Proxy-protected URL, including an
# Authorization header containing "Bearer " followed by a
# Google-issued OpenID Connect token for the service account.
resp = requests.request(
method, url,
headers={'Authorization': 'Bearer {}'.format(
open_id_connect_token)}, **kwargs)
print(f'{resp=}')
if resp.status_code == 403:
raise Exception('Service account does not have permission to '
'access the IAP-protected application.')
elif resp.status_code != 200:
raise Exception(
'Bad response from application: {!r} / {!r} / {!r}'.format(
resp.status_code, resp.headers, resp.text))
else:
return resp.text
if __name__ == '__main__':
res = make_iap_request(
'https://MYAPP.ue.r.appspot.com/',
'Client ID from IAP>App Engine app>Edit OAuth Client>Client ID'
)
print(res)
When I run it locally, I have the GOOGLE_APPLICATION_CREDENTIALS environment variable set to a local JSON credential file containing the keys for the service account I want to use. I have also tried running this in Cloud Functions so it would presumably use the metadata service to pick up the App Engine default service account (I think?).
In both cases, I am able to generate a token that appears valid. Using jwt.io, I see that it contains the expected data and the signature is valid. However, when I make a request to the app using the token, I always get this exception:
Bad response from application: 401 / {'X-Goog-IAP-Generated-Response': 'true', 'Date': 'Tue, 09 Feb 2021 19:25:43 GMT', 'Content-Type': 'text/html', 'Server': 'Google Frontend', 'Content-Length': '47', 'Alt-Svc': 'h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"'} / 'Invalid GCIP ID token: JWT signature is invalid'
What could I be doing wrong?
The solution to this problem is to exchange the Google Identity Token for an Identity Platform Identity Token.
The reason for the error Invalid GCIP ID token: JWT signature is invalid is caused by using a Google Identity Token which is signed by a Google RSA private key and not by a Google Identity Platform RSA private key. I overlooked GCIP in the error message, which would have told me the solution once we validated that the token was not corrupted in use.
In the question, this line of code fetches the Google Identity Token:
open_id_connect_token = id_token.fetch_id_token(Request(), client_id)
The above line of code requires that Google Cloud Application Default Credentials are setup. Example: set GOOGLE_APPLICATION_CREDENTIALS=c:\config\service-account.json
The next step is to exchange this token for an Identity Platform token:
def exchange_google_id_token_for_gcip_id_token(google_open_id_connect_token):
SIGN_IN_WITH_IDP_API = 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp'
API_KEY = '';
url = SIGN_IN_WITH_IDP_API + '?key=' + API_KEY;
data={
'requestUri': 'http://localhost',
'returnSecureToken': True,
'postBody':'id_token=' + google_open_id_connect_token + '&providerId=google.com'}
try:
resp = requests.post(url, data)
res = resp.json()
if 'error' in res:
print("Error: {}".format(res['error']['message']))
exit(1)
# print(res)
return res['idToken']
except Exception as ex:
print("Exception: {}".format(ex))
exit(1)
The API Key can be found in the Google Cloud Console -> Identity Platform. Top right "Application Setup Details". This will show the apiKey and authDomain.
More information can be found at this link:
Exchanging a Google token for an Identity Platform token

User is not getting authenticated (cookies not getting set) after SAML getting processed successfully

I am using an idp initiated SSO flow. I am using Kentor.AuthServices using OWIN middleware.
Most of the flow works except, user identity is not getting SET when the control reaches my callback method after successfully processing the SAML response.
Setting in web.config:
<kentor.authServices entityId="https://one-staging.com/MVSAMLServiceProvider"
returnUrl="https://5814a15e.ngrok.io/api/Account/UnsolicitedExternalLogin">
<identityProviders>
<add entityId="https://shibidp.edu/idp/shibboleth"
metadataLocation = "~/Providers/SAML2/Metadata/shibidp.edu.xml"
allowUnsolicitedAuthnResponse="false"
disableOutboundLogoutRequests="false"
binding="HttpRedirect">
</add>
<add entityId="abb:one:saml20:idp"
metadataLocation="~/Providers/SAML2/Metadata/abb.xml"
allowUnsolicitedAuthnResponse="true"
disableOutboundLogoutRequests="false"
binding="HttpRedirect">
</add>
</identityProviders>
</kentor.authServices>
Here is my Startup.cs:
public void ConfigureOAuth(IAppBuilder app)
{
app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
//For Dev enviroment only (on production should be AllowInsecureHttp = false)
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth2/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new CustomOAuthProvider(),
AccessTokenFormat = new CustomJwtFormat()
};
// OAuth 2.0 Bearer Access Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
{
ClientId = System.Configuration.ConfigurationManager.AppSettings["GoogleClientId"],
ClientSecret = System.Configuration.ConfigurationManager.AppSettings["GoogleClientSecret"],
Provider = new GoogleAuthProvider()
};
app.UseGoogleAuthentication(googleAuthOptions);
app.Use(async (Context, next) =>{await next.Invoke();});
app.UseKentorAuthServicesAuthentication(CreateSAMLAuthServicesOptions());
app.Use(async (Context, next) =>{await next.Invoke();});
}
Here are the Kentor logs (no errors in the logs):
DEBUG 2018-12-28 14:02:32,682 8859ms emv-authService-logger MoveNext - Received unsolicited Saml Response _t0r6DHtsGygxkYcfNzdkEs72.M which is allowed for idp abb:one:saml20:idp
DEBUG 2018-12-28 14:02:32,729 8906ms emv-authService-logger MoveNext - Signature validation passed for Saml Response _t0r6DHtsGygxkYcfNzdkEs72.M
DEBUG 2018-12-28 14:02:32,729 8906ms emv-authService-logger MoveNext - Extracted SAML assertion oN4v.k9x2GE7s5S8OdeNWS.93j9
DEBUG 2018-12-28 14:02:32,729 8906ms emv-authService-logger MoveNext - Validated conditions for SAML2 Response _t0r6DHtsGygxkYcfNzdkEs72.M
INFO 2018-12-28 14:02:32,729 8906ms emv-authService-logger ProcessResponse - Successfully processed SAML response _t0r6DHtsGygxkYcfNzdkEs72.M and authenticated 10035094
Finally my redirect method:
[OverrideAuthentication]
[HostAuthentication(DefaultAuthenticationTypes.ApplicationCookie)]
[AllowAnonymous]
[Route("UnsolicitedExternalLogin", Name = "UnsolicitedExternalLogin")]
public async void GetUnsolicitedExternalLogin()
{
bool isAuthenticated = User.Identity.IsAuthenticated; //getting false
}
I have unfortunately been stuck with this problem for a week now. I'm sure this is really close to getting done, so any help would be greatly appreciated.
Thanks!
Looking at the code, I think that there is a mismatch on authentication schemes.
In the pipeline setup, a cookie middleware for the external authentication scheme is setup. But in the GetUnsolicitedExternalLogin method, the ApplicationCookie scheme is referenced. Change it to reference the external scheme instead.
It is also a good idea to check if the redirect from ~/AuthServices/Acs to GetUnsolicitedExternalLogin sets an external authentication cookie.

How to configure IdentityServerAuthenticationOptions.Authority to use wildcards

I successfully setup IdentityServer4 with ASP.NET Core.
As a default config I had this:
IdentityServerAuthenticationOptions options = new IdentityServerAuthenticationOptions()
{
Authority = "http://localhost:5000",
ScopeName = "scope",
ScopeSecret = "ScopeSecret",
AutomaticAuthenticate = true,
AutomaticChallenge = true,
RequireHttpsMetadata = false,
};
Now, using this guide I configured to be read from configuration files and so they can be any numbers in production.
For example if I setup API to be running at http://*:5000 then the client can connect to it via the service IP address like http://192.168.1.100:5000.
Once the client obtains the Bearer token and tries to use it, an Internal Server Error occures with this exception:
Unable to obtain configuration from:
'http://*:5000/.well-known/openid-configuration'.
---> System.IO.IOException: IDX10804: Unable to retrieve document from: 'http://*:5000/.well-known/openid-configuration'.
---> System.UriFormatException: Invalid URI: The hostname could not be parsed.
What is the correct way to configure IdS4 to have dynamic authority?
Update
It seems the problem is with Issuer, any idea on this?
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidIssuerException:
IDX10205: Issuer validation failed. Issuer: 'http://192.168.1.100:5000'. Did not match: validationParameters.ValidIssuer: 'http://localhost:5000' or validationParameters.ValidIssuers: 'null'.
at Microsoft.IdentityModel.Tokens.Validators.ValidateIssuer(String issuer, SecurityToken securityToken, TokenValidationParameters validationParameters)
By a big surprise, all I needed, was to set a value (almost any value) for IssuerUri:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
////...
var identiyBuilder = services.AddIdentityServer(options =>
{
options.RequireSsl = false;
options.IssuerUri = "MyCompany";
});
////...
}
Now, by the above config, I can use the service by any IP address.
I didn't find I could just put in MyCompany
But in my log files I had the following:
Bearer was not authenticated. Failure message: IDX10205: Issuer validation failed. Issuer: 'https://crm.example.com'. Did not match: validationParameters.ValidIssuer: 'MyCompany' or validationParameters.ValidIssuers: 'null'.
I don't quite know what 'issuer' means but I was able to just take 'https://crm.example.com' and get things working with this :
options.IssuerUri = "https://crm.example.com";

Interface Between Google Sign-in and MailKit

I am writing an app in WPF (Windows 10 desktop) that should
include a component where the user can download message headers
and messages from G-Mail.
I am trying to use MailKit to interface with G-Mail via a secure
connection (without having to turn on "allow less-secure apps"
for G-Mail) and download messages with POP3. I am a bit confused
as to the proper procedure.
FYI: I know next to nothing about OAuth and TLS, so KISS please.
I have created and downloaded a JSON file for OAuth 2.0 from Google.
I have visited the FAQ for MailKit, and the following section
seems relevant, but I'm not sure as to what I should plug in
to the interface.
(Please see the code below.)
For "password", would that be the password for the account?
I'm not sure as to what to give for
"your-developer-id#developer.gserviceaccount.com".
.........................................................
https://github.com/jstedfast/MailKit/blob/master/FAQ.md#ProtocolLog
.........................................................
From the Q & A:
How can I log in to a GMail account using OAuth 2.0?
The first thing you need to do is follow Google's instructions for
obtaining OAuth 2.0 credentials for your application.
Once you've done that, the easiest way to obtain an access token is to
use Google's Google.Apis.Auth library:
var certificate = new X509Certificate2 (#"C:\path\to\certificate.p12", "password",
X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential (new ServiceAccountCredential
.Initializer ("your-developer-id#developer.gserviceaccount.com") {
// Note: other scopes can be found here: [links]
Scopes = new[] { "https mail google com " },
User = "username#gmail.com"
}.FromCertificate (certificate));
bool result = await credential.RequestAccessTokenAsync (CancellationToken.None);
// Note: result will be true if the access token was received successfully
// Now that you have an access token (credential.Token.AccessToken), you can
// use it with MailKit as if it were the password:
using (var client = new ImapClient ()) {
client.Connect ("imap.gmail.com", 993, true);
// use the access token as the password string
client.Authenticate ("username#gmail.com", credential.Token.AccessToken);
}
My next question: Would the user be able to access their own account(s)
with my app without having to follow the same procedure?
IOW: Will the credentials that I've downloaded work for any account?
... or allow access only to the account from which the credentials
were created?
If the credentials are only good for my own account, then I'll have to
do something else.
Would Google Sign-In be a better approach?
I've downloaded the example code for .NET from Google:
https://github.com/googlesamples/oauth-apps-for-windows
I've built and ran ran "OAuthConsoleApp", as well as "OAuthDesktopApp".
It would seem that I am getting a secure connection from those,
as I have gotten the following output:
.........................................................
redirect URI: http 127.0.0.1:64003
Listening..
Authorization code: qwerty ...
Exchanging code for tokens...
Send the request ...
GetRequestStream ...
await stream.WriteAsync ...
Get the response ...
responseText ...
{
"access_token": "qwerty ...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "qwerty ...",
"id_token": "qwerty ..."
}
Making API Call to Userinfo...
+++ userinfoResponseText : {
"sub": "117108120545711995673",
"name": "My Name",
"given_name": "My",
"family_name": "Name",
"picture": "qwerty ...",
"locale": "en"
}
.....................................................
I see that I have an "access_token" in the response and I thought
that I could plug that in to the "client.Authenticate" method for
MailKit as the password (as mentioned in the docs for MailKit):
string access_token = tokenEndpointDecoded["access_token"];
client.Connect ("pop.gmail.com", 995, SecureSocketOptions.SslOnConnect);
client.Authenticate ("username#gmail.com", access_token);
It threw an exception:
.....................................................
"POP3 server did not respond with a +OK response to the AUTH command."
at MailKit.Net.Pop3.Pop3Client.Authenticate(Encoding encoding,
ICredentials credentials, CancellationToken cancellationToken)
at MailKit.MailService.Authenticate(String userName, String
password, CancellationToken cancellationToken)
at
NS_MailKit_01.Pop3.cls_mailKit_Pop3_01.connect_and_authenticate(Object
p3_client, String p_access_token)
in :\Software_Develpoment_Sys_03_K\MIME_EMail\TEST_02\Mail_Kit_01\MailKit_01.cs:line
465
at
LIB1_01_G_Mail_Auth.cls_G_mail_authorization.str_token_NTRF.invoke_access_token(String
p_access_token)
in K:\Software_Develpoment_Sys_03_K\MIME_EMail\TEST_02\OAuth\oauth-apps-for-windows\OAuthConsoleApp\LIB1_01_G_Mail_Auth\G_Mail_Auth_01.cs:
line 95
at
LIB1_01_G_Mail_Auth.cls_G_mail_authorization.d__13.MoveNext()
in K:\Software_Develpoment_Sys_03_K\MIME_EMail\TEST_02\OAuth\oauth-apps-for-windows\OAuthConsoleApp\LIB1_01_G_Mail_Auth\G_Mail_Auth_01.cs:line
343
.....................................................
Does anyone know how I could get a "credential" object from
the Google interface that I could use with MailKit?
Any help would be appreciated.
Thanks!
For "password", would that be the password for the account?
No. It would be the password for your PKCS12 file containing your X.509 Certificate and your private key.
I'm not sure as to what to give for "your-developer-id#developer.gserviceaccount.com".
You need to register yourself and your application with Google's Developer program which will give you a developer id to use. You need to follow their directions.

Resources