C# ASP.NET Azure Mobile Services InvalidOperationException - c#

try
{
JObject jO = new JObject();
// Change 'MobileService' to the name of your MobileServiceClient instance.
// Sign-in using Facebook authentication.
user = await client.LoginAsync(provider, jO);
Session["userId"] = user.UserId;
Session["authToken"] = user.MobileServiceAuthenticationToken;
}
catch (InvalidOperationException)
{
// error
}
I'm getting error saying I must specify the access token.
The POST Facebook login request must specify the access token in the body of the request.
Does it mean I need to add the Facebook SDK into my project and have to get the access token via the SDK and add it into the JObject?

Yes you need to use the Facebook SDK to get the access_token then add it to your JObject using the following:
jO.Add("access_token", JsonValue.CreateStringValue(accessToken));
I think this post has what you're looking for.
Authenticating with Facebook for Mobile Services in Azure

Related

Accessing Gmail using API key and .NET (C#)?

Trying to access my Gmail inbox using the NuGet package Google.Apis.Gmail.v1. I don't want to use OAuth. I do want to use an API key.
So I went and acquired an API key: https://developers.google.com/api-client-library/dotnet/guide/aaa_apikeys
And then I went here to find out how to authorize using an API key: https://developers.google.com/api-client-library/dotnet/get_started
And then I ended up with this:
var service = new GmailService(new BaseClientService.Initializer
{
ApplicationName = "NAME OF MY APP HERE",
ApiKey = "MY API KEY HERE"
});
var inboxlistRequest = service.Users.Messages.List("mygmail#gmail.com");
inboxlistRequest.LabelIds = "INBOX";
inboxlistRequest.IncludeSpamTrash = true;
var emailListResponse = inboxlistRequest.Execute();
When the last line executes, I get this:
Google.GoogleApiException : Google.Apis.Requests.RequestError
Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
at Google.Apis.Requests.ClientServiceRequest`1.ParseResponse(HttpResponseMessage response)
at Google.Apis.Requests.ClientServiceRequest`1.Execute()
...
Why isn't it working? Is there some limit as to what API keys can access? Where does it say?
An API key is there to identify your API. It does not grant you access to anything.
You still need credentials of the owner of the post box.

MSAL Error message AADSTS65005 when trying to get token for accessing custom api

I downloaded the example below to get an access token from MS Graph and it worked fine. Now I changed the code to get a token from a custom web API. On apps.dev.microsoft.com I registered a client application and an the API.
Client and server registration in AD
private static async Task<AuthenticationResult> GetToken()
{
const string clientId = "185adc28-7e72-4f07-a052-651755513825";
var clientApp = new PublicClientApplication(clientId);
AuthenticationResult result = null;
string[] scopes = new string[] { "api://f69953b0-2d7f-4523-a8df-01f216b55200/Test" };
try
{
result = await clientApp.AcquireTokenAsync(scopes, "", UIBehavior.SelectAccount, string.Empty);
}
catch (Exception x)
{
if (x.Message == "User canceled authentication")
{
}
return null;
}
return result;
}
When I run the code I login to AD via the dialog en get the following exception in the debugger:
Error: Invalid client Message = "AADSTS65005: The application
'CoreWebAPIAzureADClient' asked for scope 'offline_access' that
doesn't exist on the resource. Contact the app vendor.\r\nTrace ID:
56a4b5ad-8ca1-4c41-b961-c74d84911300\r\nCorrelation ID:
a4350378-b802-4364-8464-c6fdf105cbf1\r...
Error message
Help appreciated trying for days...
For anyone still striking this problem, please read this:
https://www.andrew-best.com/posts/please-sir-can-i-have-some-auth/
You'll feel better after this guy reflects all of your frustrations, except that he works it out...
If using adal.js, for your scope you need to use
const tokenRequest = {
scopes: ["https://management.azure.com/user_impersonation"]
};
I spent a week using
const tokenRequest = {
scopes: ["user_impersonation"]
};
.. since that is the format that the graph API scopes took
As of today, the V2 Endpoint does not support API access other than the Microsoft Graph. See the limitations of the V2 app model here.
Standalone Web APIs
You can use the v2.0 endpoint to build a Web API that is secured with
OAuth 2.0. However, that Web API can receive tokens only from an
application that has the same Application ID. You cannot access a Web
API from a client that has a different Application ID. The client
won't be able to request or obtain permissions to your Web API.
For the specific scenario that you are trying to accomplish, you need to use the V1 App Model (register apps on https://portal.azure.com).
In the very near future, V2 apps will be enabled to call other APIs other than Microsoft Graph, so your scenario will be supported, but that is just not the case today. You should keep an eye out on our documentation for this update.
In your (server) application registration in AAD, you need to specify your scopes in the oauth2Permissions element.
You may already have a user_impersonation scope set. Copy that as a baseline, give it a unique GUID and value, and then AAD will let your client request an access token with your new scope.

Using OAuth2 eBay authentication with .NET SDK

I have been searching throughout the internet for a solution to use OAuth2 user token with eBay's .NET SDK and could find ANY SINGLE solution. The code I have is like following:
var ctx = new ApiContext();
ctx.Version = "897";
ctx.ApiCredential.ApiAccount.Application = "//something here";
ctx.ApiCredential.ApiAccount.Developer = "//something here";
ctx.ApiCredential.ApiAccount.Certificate = "//something here";
ctx.ApiCredential.eBayToken = "v^1.1... // this is OAuth2 token";
var getUser = new GetUserCall();
getUser.OutputSelector = new string[] { "UserID","Site" };
getUser.GetUser();
What I find really irritating is the fact that there is a possibility to use the new OAuth2 token with trading API, and I know this for a fact, because if you add an HTTP header to any Trading API call like:
X-EBAY-API-IAF-TOKEN:q2eq2eq2eq2q2eq2e
It will work, but I haven't found anywhere in the documentation to pass the IAF-TOKEN (OAuth2) token via .NET SDK calls...
Has anyone else been trying this? Is there nay way to pass the OAuth2 token via .NET SDK and then fetch the results ?
Because if I try to pass the OAuth2 token like this:
ctx.ApiCredential.eBayToken = "v^1.1... // this is OAuth2 token";
In place where the traditional Auth'n'Auth token went, I'm getting the following error:
validation of the authentication token in api request failed.
Can someone help me out please ?!

Persistent authentication across UWP app and Azure Mobile Service

Building on the example here I'm attempting to authenticate an MSA login on the client, and have it authenticate service-side as well. The difference with mine is I'm using the new WebAccount-related API's in Windows 10 instead of the now deprecated Live SDK.
So far I've got:
var provider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", "consumers");
var request = new WebTokenRequest(provider, "service::wl.basic wl.emails::DELEGATION", "none");
var result = await WebAuthenticationCoreManager.RequestTokenAsync(request);
if (result.ResponseStatus == WebTokenRequestStatus.Success)
{
string token = result.ResponseData[0].Token;
//This calls my custom wrappers around the Live REST API v5 and runs successfully with this token
var acc = await LiveApi.GetLiveAccount(token);
var jtoken = new JObject
{
{"authenticationToken", token}
};
try
{
//Shouldn't this work? but raises a 401
await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount, jtoken);
//Alternate method? Also raises a 401
//await App.MobileService.LoginWithMicrosoftAccountAsync(token);
}
}
As I mentioned in the comments, all I get are 401s.
As far as I can tell the application is configured correctly in Microsoft Account dev center:
I'm using the client ID and secret from the same app in the Azure portal.
JWT issuing is not restricted.
Redirect URL is of the format https://{appname}.azurewebsites.net/.auth/login/microsoftaccount/callback
Authentication works fine when I switch to use purely server-side authentication. i.e.
await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
Any ideas? Am I missing something? Any help would be appreciated.
UPDATED:
The token I get back in the WebTokenRequestResult is 877 characters long and does not appear to be in the JWT format, with the dot (.) separators and I'm quite certain that this is the issue. The following error gets logged in service when the client calls the code above:
JWT validation failed: IDX10708: 'System.IdentityModel.Tokens.JwtSecurityTokenHandler' cannot read this string: 'EwCQAq1DBAAUGCCXc8wU/zFu9QnLdZXy+...Zz9TbuxCowNxsEPPOvXwE='.
Application: The string needs to be in compact JSON format, which is of the form: '<Base64UrlEncodedHeader>.<Base64UrlEndcodedPayload>.<OPTIONAL, Base64UrlEncodedSignature>'..
Application: 2015-12-07T17:47:09 PID[5740] Information Sending response: 401.71 Unauthorized
What format is the token currently in? Can it be transformed to a JWT?
Still no closer to a solution, so any help is appreciated.
Anyone feel free to correct me, but it looks like RequestTokenAsync gets you an access token which you can't use to login the backend. You need an authentication token for that, and as far as I can see RequestTokenAsync doesn't get you that.
There's some info here about the tokens.
If people end up here searching for a solution for App Service Mobile, the update to MobileService. Then there is now a solution
The code replicated here is:
async Task<string> GetDataAsync()
{
try
{
return await App.MobileService.InvokeApiAsync<string>("values");
}
catch (MobileServiceInvalidOperationException e)
{
if (e.Response.StatusCode != HttpStatusCode.Unauthorized)
{
throw;
}
}
// Calling /.auth/refresh will update the tokens in the token store
// and will also return a new mobile authentication token.
JObject refreshJson = (JObject)await App.MobileService.InvokeApiAsync(
"/.auth/refresh",
HttpMethod.Get,
null);
string newToken = refreshJson["authenticationToken"].Value<string>();
App.MobileService.CurrentUser.MobileServiceAuthenticationToken
= newToken;
return await App.MobileService.InvokeApiAsync<string>("values");
}
Hope it saves somebody time !

Get Facebook's Application Access Token

I have to use Facebook's notification for my web app.
Facebook Graph API requires the Application Access Token for this action.
Is there a way to get this token by code (C# SDK) or is this generated by Facebook a single time?
Is this token static (and secret) or with expire datetime?
For info: https://developers.facebook.com/tools/access_token/ - App Token, not User Token!
Thanks
The answer is the dynamic way by code:
var fb = new FacebookClient();
dynamic result = fb.Get( "oauth/access_token", new
{
client_id = <myAppID>,
client_secret = <mySecretID>,
grant_type = "client_credentials"
} );
var apptoken = result.access_token;
Or by the combination or appid|secretid
You can just use the concatenation of id and secret with a pipe symbol in the middle:
app_id|app_secret
This is actually how the PHP SDK creates the app access token internally, so there should be no question about the reliability of this method. (From other endpoints where you actively query for an app access token you might get another token that does not match this scheme though.)
you can investigate the getApplicationAccessToken method as in another c# sdk project from github
https://github.com/barans/FacebookCsharpSdk/blob/master/FacebookCSharpSDK/FacebookClient/FacebookClient.cs

Categories