xamarin android oauth 403 error - disallowed_useragent - c#

I am new to xamarin android. I am trying to implement OAuth in xamarin android with Google as Identity provider. I have registered my app with google and got the client id and Client secret which I am using when user click on login button as below.
void OnLoginClicked(object sender, EventArgs e)
{
var authenticator = new OAuth2Authenticator(
Constants.ClientId,
Constants.ClientSecret,
Constants.Scope,
new Uri(Constants.AuthorizeUrl),
new Uri(Constants.RedirectUrl),
new Uri(Constants.AccessTokenUrl));
authenticator.Completed += OnAuthCompleted;
authenticator.Error += OnAuthError;
var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
presenter.Login(authenticator);
}
It redirects to google but gives 403 error as 'disallowed_useragent'.
According to this, google "no longer allow OAuth requests to Google in embedded browsers known as web-views"
After going through some forums and stackoverflow questions, I come to know that
chromecustomtabs need to be use.
So here I have two questions
Is there alternate solution to chromecustomtabs?
If above answer is no, then if I understand correctly then I need to add below code in my project. My question is what modification needs to be done in OnLoginClicked function? Does the OAuth2Authenticator required in that case?
My code:
var mgr = new CustomTabsActivityManager (this);
mgr.CustomTabsServiceConnected += delegate {
mgr.LaunchUrl ("http://xamarin.com");
};
mgr.BindService ();
Any suggestions/links would be appreciated. Thanks.

Please read this topic. Xamarin Auth 1.5.0 supported CustomTabsIntent.

This is an answer to your section question:
There is a parameter on OAuth2Authenticator called isUsingNativeUI. You must set it to true. This will cause Xamarin.Auth to use the CustomTabs service inside Android rather than the webview.
Your code becomes:
var authenticator = new OAuth2Authenticator(
Constants.ClientId,
Constants.ClientSecret,
Constants.Scope,
new Uri(Constants.AuthorizeUrl),
new Uri(Constants.RedirectUrl),
new Uri(Constants.AccessTokenUrl),
null,
true); // <-- This is it isUsingNativeUI
I wish it were the default.

Related

Implementing refresh tokens in Xamarin (Authorization code flow - OAuth2)

Can anyone maybe share some tutorial, resources, link, anything related to implementing refresh tokens when using Xamarin.
What I am trying to accomplish is authentication code flow(where user firstly provides credentials to identity server, gets temporary code, which later gets exchanged for real access token, for accessing APIs).
I was looking all around, but nothing helped me. I have realized that implementing refresh tokens is not so easy in Xamarin, but still there must be a way.
I was trying something with TokenClient() class.
var client = new TokenClient("https://localhost:44305/connect/token", "mylegislature");
var request = await client.RequestResourceOwnerPasswordAsync(username, password);
if (!request.IsError)
{
_secureService.StoreAuthToken(request);
}
And with AuthorizeRequest() class:
var authorizeRequest =
new AuthorizeRequest("https://localhost:44305/connect/token");
var parameters = new Dictionary<string, string>();
parameters.Add("response_type", "token");
parameters.Add("client_id", "mylegislature");
parameters.Add("scope", "MyLegislatureAPI");
parameters.Add("redirect_uri", "https://localhost:44301/account/oAuth2");
var authorizeUri = authorizeRequest.Create(parameters);
But with non of them I have succeed in sending request to IdentityServer, which is ok since it is expecting respecting of authorization code flow of OAuth2, but I am unable to implement code in right way since I couldn't find any useful resources about this. If someone has something for sharing please help.

OneDrive API with C#, get authentication code programmatic

I have to write an application, no matter what language (c#, Java, shell, python ...) that can connect to OneDrive and then uploads file.
Following the OneDrive API I found that i need in one step to go to the browser (manually and to post a url that combines client_id and client_security to get an authentication code so i can connect my client with it to get the access token. (oAuth2 protocol)
I need to get the access_token pragmatically, i don't need any manual step to be involved.
I tried in c# to use the WebBrowser component to navigate to the url and to get the access token, I found that the browser stays in the same url and not getting the final url that includes the auth_code!
My code looks like:
// Initialize a new Client (without an Access/Refresh tokens
var client = new Client(options);
// Get the OAuth Request Url
var authRequestUrl = client.GetAuthorizationRequestUrl(new[] { Scope.Basic, Scope.Signin, Scope.SkyDrive, Scope.SkyDriveUpdate });
// TODO: Navigate to authRequestUrl using the browser, and retrieve the Authorization Code from the response
WebBrowser wb = new WebBrowser();
wb.AllowNavigation = true;
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
wb.Navigate(authRequestUrl);
Console.WriteLine(wb.Version);
while (wb.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
wb.Document.InvokeScript("evt_Login_onload(event)");
Uri myUrl = wb.Url;
Anyone can help with fixing this, or maybe suggest other ideas please?
Thanks in Advance!
It looks like you're creating a Windows desktop app using C#. There's actually an example at https://msdn.microsoft.com/en-us/library/hh826529.aspx for using the WebBrowser class to get the authorization code, then the token, then make an API. In short, you'll first need to send a request to the following URL with your client_id and scopes.
https://login.live.com/oauth20_authorize.srf?client_id=YOUR_CLIENT_ID&scope=YOUR_SCOPE_STRING&response_type=code&redirect_uri=https://login.live.com/oauth20_desktop.srf
In the response, you'll get the authorization code which you'll need to use to send another request to with your client_id, client_secret, authorization code like the following.
https://login.live.com/oauth20_token.srf?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&redirect_uri=https://login.live.com/oauth20_desktop.srf&code=AUTHORIZATION_CODE&grant_type=authorization_code
When you finally receive the access token, you can make requests to the API using your access token similar to the following.
"https://apis.live.net/v5.0/me?access_token=ACCESS_TOKEN". The "me" can be changed to any other folder or directory.
I hope that helps.
dont u think the scope u provided are wrong, they should be wl.basic, wl.signin, and if ur using new onedrive api then it should be onedrive.readonly or onedrive.readwrite
if ur using liveconnect api for the purpose of using onedrive then scope should be wl.skydrive or wl.contacts_skydrive or wl.skydrive_update
depending upon ur uses (refer https://msdn.microsoft.com/en-us/library/hh243646.aspx)
and can u more elaborate how ur trying to get the access_token, from above it is quite confusing to me
Have you solved you issue?
Have you tried to use the LiveSDK to authenticate?
Have a look at my question there, it might help you :
Onedrive API vs LiveSDK
I have used the following code, after installing both the LiveSDK and the OneDrive SDK, and this does not require any login after the first authorization. However it "may" have to be a RT app (windows store or windows phone store)
var authClient = new LiveAuthClient();
var authResult = await authClient.LoginAsync(new string[] {
"wl.signin", "onedrive.readwrite", "onedrive.appfolder"});
if (authResult.Session == null)
throw new InvalidOperationException("You need to sign in and give consent to the app.");
var Connection = new ODConnection("https://api.onedrive.com/v1.0",
new MicrosoftAccountAuthenticationInfo() { TokenType = "Bearer",
AccessToken = odArgs.Session.AccessToken });
Toan-Nguyen's answer almost helps me. On the step 2 (when I should send a request with authorization code) I get the response with error "Public clients can't send client secret". This answer said it's neccessary to remove the attribute client_secret from url.

Linq-to-Twitter always error 401 Unauthorized

I am using LinqToTwitter in my C# desktop application. Trying to send tweets and tweets with image to Twitter using OAuth credentials. Initially I am using these required attributes of my own Twitter application:
var auth = new SingleUserAuthorizer
{
Credentials = new SingleUserInMemoryCredentials
{
ConsumerKey = "key",
ConsumerSecret = "secret",
TwitterAccessToken = "token",
TwitterAccessTokenSecret = "tokensecret"
}
};
var context = new TwitterContext(auth);
context.UpdateStatus("Hello World");
NOTE: I have double checked that I am using correct values for above keys and tokens, but its always erroring 401 Unauthorized.
NOTE: Also I have checked this link for any mistake: http://linqtotwitter.codeplex.com/wikipage?title=LINQ%20to%20Twitter%20FAQ&referringTitle=Documentation
Any help to resolve this ?
Your code seems to be fine.
The FAQ, which you reference, is the best resource right now.
What type of application are you building, e.g. ASP.NET, Windows Phone, etc.?
You might also try downloading the source code and checking to see if the LinqToTwitterDemos project will work for you.

Hammock Package , Tweetsharp and C# Windows Phone 8

I followed this link
http://samjarawan.blogspot.co.uk/2010/09/building-real-windows-phone-7-twitter_18.html
step by step and when I am running my app, I am getting an error i.e. "Error Calling Twitter".
When I searched about it, I found that in this part of code
var client = new RestClient
{
Authority = "https://api.twitter.com/oauth",
Credentials = credentials,
HasElevatedPermissions = true,
SilverlightAcceptEncodingHeader = "gzip",
DecompressionMethods = DecompressionMethods.GZip
};
I need to do some changes, but what changes didn't find any where. Another answer I got that I need to update Hammock and Tweetsharp, but its already updated. Please suggest me and help me out.
Try changing DecompressionMethods or SilverlightAcceptEncodingHeader.

Execution of request failed: https://www.google.com/calendar/feeds/default/private/full

I'm trying to add an event to a Google calendar by accepting the event details from a winform
while trying to add the event i'm getting the following error
"Execution of request failed: https://www.google.com/calendar/feeds/default/private/full"
the code is as follows :
CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("username#gmail.com", "password");
EventEntry entry = new EventEntry();
entry.Title.Text = textBox1.Text;
entry.Content.Content = textBox2.Text;
Where eventLocation = new Where();
eventLocation.ValueString = textBox3.Text;
entry.Locations.Add(eventLocation);
When eventTime = new When();
eventTime.StartTime =Convert.ToDateTime(textBox4.Text);
entry.Times.Add(eventTime);
Uri postUri = new Uri("http://www.google.com/calendar/feeds/default/private/full");
AtomEntry insertedEntry = myService.Insert(postUri, entry);
can anyone help me out with this? I've tried for basic and full both and removing private as well, is there something that I'm missing out on?
The calendar credentials that i m passing has access to the calendar and does have more than one calendar.
I know all of the Google API's require OAuth 2 authentication. I'm not sure if your CalendarService class is using the Google API libraries or not. It looks like your doing the authentication piece yourself?
I would highly recommend using the Google API .Net client to simplify all of this. This library includes the Calendar API methods to make it really simple.
https://code.google.com/p/google-api-dotnet-client/
https://code.google.com/p/google-api-dotnet-client/wiki/OAuth2

Categories