Single Sign-On When Using PowerBI REST API - powerbi

I created a test asp.net mvc application to display PowerBI reports using the PowerBI REST API. I'm using Azure Active Directory authentication as the authentication mechanism for the site. Is there any way to re-use credentials from MVC Azure AD authentication framework to get access to the Power BI API? Currently, when the app makes the request to get the access token for the application, the user needs to log in again.

I was able to resolve this issue by following the example in: https://github.com/Azure-Samples/active-directory-dotnet-graphapi-web. They show code to authenticate against AAD and then use the token to access the graphAPI. I used their approach and used the token to access the PowerBI API.

When authenticating with Azure AD you should be getting a token back, you can use a Token Cache to store the users token for later. When you need to get an access token for the powerbi api you can use the refresh token from the initial token you got back.
public JsonResult GetPowerBiToken()
{
var clientId = ConfigurationManager.AppSettings["ida:ClientId"];
var appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
var aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
var tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
string Authority = aadInstance + tenantId;
var claim = CurrentUserClaims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
AuthenticationContext authContext = new AuthenticationContext(Authority, new AdalTokenCache(claim.Value));
var refresh_token = authContext.TokenCache.ReadItems().FirstOrDefault().RefreshToken;
ClientCredential credential = new ClientCredential(clientId, appKey);
var resp = authContext.AcquireTokenByRefreshToken(refresh_token, credential, "https://analysis.windows.net/powerbi/api");
return Json(new { Token = resp.AccessToken }, JsonRequestBehavior.AllowGet);
}
Hope this helps.

Related

How to get Facebook page feed and Filter its fields as Json using Google App script

I am trying to get a Facebook page feed through Google app script.
As of now I tried different scripts but I am getting only app token with the request and if i change it with a usertoken from graph api I got messages but no images and titles
How to get the user token and get the correct fields for as a json ,
var url = 'https://graph.facebook.com'
+ '/love.to.traavel/feed'
+ '?access_token='+ encodeURIComponent(getToken());
// + '?access_token=' + service.getAccessToken();
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var jsondata = JSON.parse(json);
Logger.log(jsondata); //check this and adjust following for loop and ht
var posts = {};
for (var i in jsondata) {
posts[i] = {"post":jsondata[i].message};
}
return posts;
You should use a Page Token, not a User Token
You need to ask for fields you want to get, with the fields parameter: https://graph.facebook.com/love.to.traavel/feed?fields=field1,field2,...&access_token=xxx
You get a user token by authorizing your App: https://developers.facebook.com/docs/facebook-login/platforms
Be aware that extended user tokens are valid for 60 days only, so you have to refresh it once in a while. There is no user token that is valid forever. You cannot authorize through code only, it needs user interaction. The easiest way is to just generate a user token by selecting your App in the API Explorer and authorize it, like you did already. Then hardcode it in the script code.
Alternatively, you can try implementing this with the manual login flow, check out the docs for that. You can try adding the functionality using this for a custom interface where you go through the login process: https://developers.google.com/apps-script/guides/html/
Since you donĀ“t own the page, you should read this too: https://developers.facebook.com/docs/apps/review/feature/#reference-PAGES_ACCESS

Unable to authenticate in accessing Dynamic CRM Online Web Service

I need to utilize Dynamic CRM Data Service Endpoint exposed to get data from one of the methods.
Service(microsoft) account has access to this service.
I've tried authenticating to Discovery Service and Organization Service using sample code provided here [https://msdn.microsoft.com/en-us/library/hh675404.aspx] and succeed. However am not able to use same authentication to access data Service as I could find anyway to relate Data Service with the other two. Doing basic authentication using Network Credentials does not work.
I have downloaded the CSDL exposed and added that as service reference to my project, which created an class of web service which extends from DataServiceContext. Am trying to retrieve data of one of the methods using LinQ queries. It returs following error:
"The response payload is a not a valid response payload. Please make sure that the top level element is a valid Atom or JSON element or belongs to 'http://schemas.microsoft.com/ado/2007/08/dataservices' namespace." On capturing using fiddle I realized that on hitting data service URL it is redirected to sign in page 'login.microsoftonline.com/'
Can anybody suggest a way to authenticate the user to access Data Serivce?
Adding code:
//<snippetAuthenticateWithNoHelp1>
IServiceManagement<IDiscoveryService> serviceManagement =
ServiceConfigurationFactory.CreateManagement<IDiscoveryService>(
new Uri(_discoveryServiceAddress));
AuthenticationProviderType endpointType = serviceManagement.AuthenticationType;
// Set the credentials.
AuthenticationCredentials authCredentials = GetCredentials(serviceManagement, endpointType);
String organizationUri = String.Empty;
// Get the discovery service proxy.
using (DiscoveryServiceProxy discoveryProxy =
GetProxy<IDiscoveryService, DiscoveryServiceProxy>(serviceManagement, authCredentials))
{
// Obtain organization information from the Discovery service.
if (discoveryProxy != null)
{
// Obtain information about the organizations that the system user belongs to.
OrganizationDetailCollection orgs = DiscoverOrganizations(discoveryProxy);
// Obtains the Web address (Uri) of the target organization.
organizationUri = FindOrganization(_organizationUniqueName,
orgs.ToArray()).Endpoints[EndpointType.OrganizationService];
}
}
//</snippetAuthenticateWithNoHelp1>
if (!String.IsNullOrWhiteSpace(organizationUri))
{
//<snippetAuthenticateWithNoHelp3>
IServiceManagement<IOrganizationService> orgServiceManagement =
ServiceConfigurationFactory.CreateManagement<IOrganizationService>(
new Uri(organizationUri));
// Set the credentials.
AuthenticationCredentials credentials = GetCredentials(orgServiceManagement, endpointType);
// Get the organization service proxy.
using (OrganizationServiceProxy organizationProxy =
GetProxy<IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials))
{
// This statement is required to enable early-bound type support.
organizationProxy.EnableProxyTypes();
// Now make an SDK call with the organization service proxy.
// Display information about the logged on user.
Guid userid = ((WhoAmIResponse)organizationProxy.Execute(
new WhoAmIRequest())).UserId;
SystemUser systemUser = organizationProxy.Retrieve("systemuser", userid,
new ColumnSet(new string[] { "firstname", "lastname" })).ToEntity<SystemUser>();
Console.WriteLine("Logged on user is {0} {1}.",
systemUser.FirstName, systemUser.LastName);
Uri x = new Uri("https://<MyOrgainzationName>.crm.dynamics.com/XRMServices/2011/OrganizationData.svc/");
MyOrgainzationContext saContext = new MyOrgainzationContext(x);
NetworkCredential nc = new NetworkCredential();
nc.UserName = "*****#microsoft.com";
nc.Password = "********";
saContext.Credentials = nc;
var query_where3 = from c in saContext.new_productSet
select new
{
ProductStatus = c.new_ProductStatus,
LineofBusiness = c.new_LineofBusiness
};
var temp = saContext.Entities;
foreach (var c in query_where3)
{
System.Console.WriteLine("ProductStatus: " +
c.ProductStatus +
"\t\t\t" +
"LineofBusiness: " +
c.LineofBusiness);
}
}
//</snippetAuthenticateWithNoHelp3>
}
MyOrganizationContext is the context class created on adding CSDL file exposed at service endpoints
Have a look at the CRM Web Api Preview: https://msdn.microsoft.com/en-us/dynamics/crm/webapipreview.aspx. You can call this endpoint from outside xRM and you can authenticate with OAuth 2.0.

New Google Drive Directory APIs error out: Bad request

I am using below piece of code to list all domain users in my simple Console application
var certificate = new X509Certificate2("D:\\3acf2c2008cecd33b43de27e30016a72e1482c41-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable);
var privateKey = certificate.Export(X509ContentType.Cert);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
ServiceAccountId = "877926787679-b7fd15en1sh2oc65e164v90cfcvrfftq#developer.gserviceaccount.com",
Scope = DirectoryService.Scopes.AdminDirectoryUserReadonly.GetStringValue(),
ServiceAccountUser = "user1#05.mygbiz.com"
};
var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
DirectoryService dirService = new DirectoryService(new BaseClientService.Initializer()
{
Authenticator = auth,
ApplicationName = "My APP"
});
Users users = dirService.Users.List().Execute();
Execute() method errors out saying Bad Request.
Questions:
How to overcome this issue?
Does this Admin SDK support trial version of Google APP account?
I have updated service account Client ID in Google Console and also updated in Admin Console with below scopes
https://www.googleapis.com/auth/admin.directory.group
https://www.googleapis.com/auth/admin.directory.user
and also set API access check box. Do I missing something in settings?
Like JoBe said, you should include the domain parameter.
happy_user = service.users().list(domain='mydomain.com').execute()
This has worked for me.

C# SDK posting to my own Page feed

The situation:
I have a website and creates "posts". As a new post is created I want to send the new post to my facebook pages feed. I have all of the code down to do this and it works fine as long as I get an access token from the graph API explorer tool. This is not going to work as it expires after about an hour. When I generate the access token from code, it appears that it is a app access token and it does not give me access to my page. So the big question is how do I obtain a user access token from code that will have access to post to my page.
Here is how I am getting the access token.
private static string GetApiAccessToken()
{
var client = new FacebookClient();
dynamic result = client.Get("oauth/access_token", new
{
client_id = SessionGetter.Instance.FacebookApiKey,
client_secret = SessionGetter.Instance.FacebookSecretKey,
grant_type = "client_credentials",
scope = "manage_pages"
});
return result.access_token;
}
Then I use the access token to try and get the Page access token and this is where it tells me that I don't have authorization and all I get back in the dictionary is an "id".
private static string GetPageAccessToken(string accessToken, string pageId)
{
try
{
var fb = new FacebookClient(accessToken);
var parameters = new Dictionary<string, object>();
parameters["fields"] = "access_token";
var result = (IDictionary<string, object>)fb.Get(pageId, parameters);
var pageAccessToken = (string)result["access_token"];
return pageAccessToken;
}
catch (FacebookApiException ex)
{
}
return null;
}
Now like I said, if I use the access token from the graph explorer, the code works fine.
Then the post is made to the graph API
var facebookClient = new FacebookClient(pageAccessToken);
var result = (IDictionary<string, object>)facebookClient.Post("me/feed", new Dictionary<string, object>
{{"message",postMessage}, {"picture", csLogo},
{"link", LinkHelper.AssignmentUrl(wrapper.Assignment)}});
Make sure the user access token has manage_pages extended permissions.
then make a request to me/accounts to the get the page access token.
Then post to {pageid}/feed using the page access token.

Authenticate with MS Crm Web Service

I'm looking for a way to authenticate a user (given a username and password) via the Microsoft CRM 4.0 Web Services API. Ideally, I'd like to filter down a list of projects based on which ones the logged in user has access to. i may be able to figure out the second part but I can't find a way to authenticate the user. The way all of the cals are currently made in the web service is via:
MyWebServices.CrmService svc = new MyWebServices.CrmService();
MyWebServices.CrmAuthenticationToken token = new MyWebServices.CrmAuthenticationToken();
token.OrganizationName = "MyCRM";
token.AuthenticationType = 0;
svc.CrmAuthenticationTokenValue = token;
svc.PreAuthenticate = true;
svc.Credentials = System.Net.CredentialCache.DefaultCredentials;
svc.Credentials = new NetworkCredential("hj", "mypass", "mydomain");
Then calls can be made via the service. I guess I could potentially try to authenticate to CRM via the user's username/password but it feels wrong somehow.
If you are in an on-premise environment, you should be able to use the following code to get a valid CRM service that can be used to retrieve your projects.
public static Microsoft.Crm.SdkTypeProxy.CrmService GetCrmService(string crmServerUrl, string organizationName, System.Net.NetworkCredential networkCredential)
{
// Setup the Authentication Token
CrmAuthenticationToken crmAuthenticationToken = new CrmAuthenticationToken
{
OrganizationName = organizationName,
AuthenticationType = 0
};
var crmServiceUriBuilder = new UriBuilder(crmServerUrl) { Path = "//MSCRMServices//2007//CrmService.asmx" };
// Instantiate a CrmService
var crmService = new Microsoft.Crm.SdkTypeProxy.CrmService
{
Url = crmServiceUriBuilder.ToString(),
UseDefaultCredentials = false,
Credentials = networkCredential,
CrmAuthenticationTokenValue = crmAuthenticationToken
};
return crmService;
}