Read google user detail with azure token - c#

I'm using Azure mobile services after login with google account i am getting azure access token, this token i am using to send request to service end. here is my code that return the access token and Sid,
MobileServiceClient client =new MobileServiceClient();
> var user = await client.LoginAsync(Forms.Context, provider);
But now i have azure access token but i need the google access token to get user detail. So please help me how i can get the google user detail with Azure access token.

Send a request to your endpoint /.auth/me with the X-ZUMO-AUTH header set to the token. This will return a JSON blob that contains the provider token.

Related

Why is this "AccessDenied" while Communicating with Microsoft Graph API?

I cant access endpoints in Microsoft graph.
I will be uploading a file to a users one drive when I have the communication set up
but for now I am just trying to get a list of items in a drive.
This is the response I get from https://graph.microsoft.com/v1.0/drives/{{drive_id}}/root/children
{
"error": {
"code": "AccessDenied",
"message": "Either scp or roles claim need to be present in the token.",
"innerError": {
"request-id": "123",
"date": "2020-01-09T11:43:20"
}
}
}
I retrieved the drive_id by using graph explorer on endpoint https://graph.microsoft.com/v1.0/me/
on the signed in user.
It should be noted that I can use this endpoint https://graph.microsoft.com/v1.0/subscriptions
So I must be doing something right with the access token.
I followed this tutorial to get the access token using the client credential flow.
and this is the code I use to get the access token
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-
form-urlencoded"));
var req = new HttpRequestMessage(HttpMethod.Post, $"https://login.microsoftonline.com/<tenant>/oauth2/token");
req.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{"grant_type", "client_credentials"},
{"client_id", "123"},
{"client_secret", "123"},
{"resource", "https://graph.microsoft.com"}
});
When I decode the JWT I do not see any scopes in the token but if I understand correctly
header should get the scopes that have been permitted by admin.
An admin has already granted my app these permissions for graph explorer:
(Although I do not have the delegate permissions, does that matter?)
Filse.Read,
Files.ReadWriteAll,
Sites.ReadWtiteAll,
User.Read
I am using this collection in postman to test.
Thanks in advance any advice is appreciated.
From Marc LaFleurs' answer :
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.

Why doesn't AcquireTokenByAuthorizationCode return RefreshToken

In this documentation it gives a complete flow for a web application that calls a web API:
The web application executes a policy and the user completes the user experience.
Azure AD B2C returns an (OpenID Connect) id_token and an authorization code to the browser.
The browser posts the id_token and authorization code to the redirect URI.
The web server validates the id_token and sets a session cookie.
The web server asks Azure AD B2C for an access_token by providing it with the authorization code, application client ID, and
client credentials.
The access_token and refresh_token are returned to the web server.
The web API is called with the access_token in an authorization header.
The web API validates the token.
Secure data is returned to the web application.
Looking at 6. and using the code in the Azure-Samples repository active-directory-b2c-dotnet-webapp-and-webapi
, I cannot get the line
AuthenticationResult result = await confidentialClient.AcquireTokenByAuthorizationCode(Globals.Scopes, notification.Code).ExecuteAsync();
to return a refresh_token. It returns an IdToken and AccessToken but no RefreshToken.
By using my browser and Postman and following the steps in this document with the same B2C tenant and application I do get the refresh token as expected.
This question is similar to mine and the blog post mentioned in one of the answers provides a work around to the symptom of not having a refresh token but my question remains:
How can I get AcquireTokenByAuthorizationCode to return a refresh_token?
To get refresh token, your application should append offline_access as scope.
You mentioned like this msdn able to return you refresh token. It is because request already contain offline_access scope
&scope=openid%20offline_access
To get refresh token from active-directory-b2c-dotnet-webapp-and-webapi. You need to update Global.cs Scopes filed to include offline_access
public static string[] Scopes = new string[] { ReadTasksScope, WriteTasksScope, "offline_access" };
The offline_access scope is optional for web apps. It indicates that your app needs a refresh token for long-lived access to resources.
Go to web.config add below:
<add key ="api:OfflineAccessScope" value="offline_access "/>
And in Global.cs :
public static string OfflineAccessScope = ApiIdentifier + ConfigurationManager.AppSettings["api:OfflineAccessScope"];
public static string[] Scopes = new string[] { ReadTasksScope, WriteTasksScope, OfflineAccessScope};
Then the Globals.Scopes in AcquireTokenByAuthorizationCode will return refresh token.

Is it possible to purge azure cdn endpoint using storage key?

I want to create a function which will purge a file on Azure CDN.
Here in the documentation It says How can I purge the content specifying the path.
POST https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/purge?api-version=2017-10-12
But the security is provided by Azure Active Directory OAuth2 Flow.
Hence I need to use clientId, secretId (from here https://blogs.msdn.microsoft.com/maheshk/2017/04/01/azure-cdn-how-to-purge-cdn-content-from-c-code/)
var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/microsoft.onmicrosoft.com");
ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);
Task<AuthenticationResult> resultstr = authenticationContext.AcquireTokenAsync("https://management.core.windows.net/", clientCredential);
WebClient client = new WebClient();
//authentication using the Azure AD application
var token = resultstr.Result.AccessToken;
I wander Is there a way to make purge request using storage key and not clientId, secretId?
No, it is not possible. The Azure Rest API Endpoints - Purge Content is integrated with Azure AD authentication, it needs your valid credentials to get the access token.
See this link : Getting Started with REST - Register your client application with Azure AD.
Most Azure services (such as Azure Resource Manager providers and the classic deployment model) require your client code to authenticate with valid credentials before you can call the service's API. Authentication is coordinated between the various actors by Azure AD, and provides your client with an access token as proof of the authentication. The token is then sent to the Azure service in the HTTP Authorization header of subsequent REST API requests. The token's claims also provide information to the service, allowing it to validate the client and perform any required authorization.

OpenIDConnect to Connect to Azure AD

I am using OWIN OpenID Connect Middleware to connect to Azure AD. I am able to authenticate the user successfully and redirect back to callback endpoint. I am a bit confused here as i am receiving only id_token & code in the response.
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "Azure AD - TEST",
Caption = "azure AD",
SignInAsAuthenticationType = signInAsType,
ClientId = "some guid",
Authority = "https://sts.windows.net/idp",
ResponseType = OpenIdConnectResponseTypes.CodeIdToken,
RedirectUri = "https://localhost:44392/ExternalLogins/Callback/",
AuthenticationMode = AuthenticationMode.Active,
});
Callback Method :
[HttpPost]
[Route("ExternalLogins/Callback")]
[AllowAnonymous]
public async Task<IHttpActionResult> ExternalLoginCallback()
{
var content = await Request.Content.ReadAsStringAsync();
// I could see the content is a string with id_token, code , state etc.
//id_token is a JWT, so i can decode it and see the user claims and use them later
}
My Questions are :
Is Azure AD used for only authenticating the user ? What about authorizatoin ?
If i want to make calls to other APIs after authentication, how do i do that as i don't have access_token ?
I think i can exchange code with access_token but not sure which Azure endpoint i need to call to get access_token ?
What is the difference between AuthenticationMode.Active and AuthenticationMode.Passive ?
Azure AD can absolutely authorize a user and get your Access/Refresh tokens. It supports all oAuth 2.0 and OIDC flows.
You'll need to get an access token to make calls to an api. Let's say you want to call a /get endpoint on the MS Graph, you will stuff the access token into the body of the http request with the keyword Bearer ey... in front of it.
Additionally, you'll need to go into the Azure Portal and configure the delegated permissions you want to access.
The auth code is used to exchange for the access_token. I suggest checking out this protocol doc that shows you how to use all the endpoints. The short answer is you POST to the /token endpoint.
The difference between active and passive is a bit complex for a SO answer, I recommend reading this blog post about the differences.
I'll just add that if you want to see some sample code using Azure AD you can go to Azure AD Dev Guide or Azure AD code samples on Github.

Access token from WP8 not working on WebApi 2 endpoint

I have a basic SPA template with WebApi 2 backend that uses Microsoft account as external login provider. I also have a WP8 client in which users can login with their Microsoft account, both the SPA and WP8 client use ClientId so a users with same email address get the same identifiers in both clients (the ProviderKeys stored at the db match the id's for the same users when they log in on the phone).
When a user has logged in through the browser I can get their access_token and authenticate further requests they make against the api through the bearer token, this works well, returning 200 every time. On the WP8 client it doesnt work however, this is how I get the token:
LiveAuthClient Auth = new LiveAuthClient("0000000041422E16");
//some code removed
LiveConnectClient connect = new LiveConnectClient(Auth.Session);
string access_token = connect.Session.AccessToken;
//use token to send a http request to an authorized endpoint
I've used Fiddler to test the access token and the WebApi always return 401, what am I doing wrong here? Aren't the tokens sent back by the Live SDK client valid for authentication on the WebApi endpoints?

Categories

Resources