Windows Universal App Get username from Microsoft Account Authentication - c#

So I wanted the users to login to my app using Microsoft Account
I did all the setup in my mobile service in Azure and this is how I implement the login in my App:
private async Task<bool> AuthenticateAsync()
{
string message;
bool success = false;
try
{
user = await App.MobileService
.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
message =
string.Format("You are now signed in - {0}", user.UserId);
success = true;
}
catch (InvalidOperationException)
{
message = "You must log in. Login Required";
}
var dialog = new MessageDialog(message);
dialog.Commands.Add(new UICommand("OK"));
await dialog.ShowAsync();
return success;
}
all is working fine but all I get from this is a User Id.
and I need the name of the user that logged in, can anyone help me how should I go about this?
Thanks

and I need the name of the user that logged in, can anyone help me how should I go about this
For UWP app, this is impossible using official managed API. See MobileServiceAuthentication class in here
internal async Task<MobileServiceUser> LoginAsync()
{
string response = await this.LoginAsyncOverride();
if (!string.IsNullOrEmpty(response))
{
JToken authToken = JToken.Parse(response);
// Get the Mobile Services auth token and user data
this.Client.CurrentUser = new MobileServiceUser((string)authToken["user"]["userId"]);
this.Client.CurrentUser.MobileServiceAuthenticationToken = (string)authToken[LoginAsyncAuthenticationTokenKey];
}
return this.Client.CurrentUser;
}
The official sdk just retrieves the userId and MobileServiceAuthenticationToken, for other platform, we need to use GetIdentitiesAsync() method to get identity, see How to get user name, email, etc. from MobileServiceUser? or LINK
The username info actually has been retrieved in the SSO process:
So you have to implement the auth process(Extend the method based on the open source code) and maintain the username information as you need.
If you can get the user's input, maybe you can also call Live API: https://msdn.microsoft.com/en-us/library/office/dn659736.aspx#Requesting_info

Related

Xamarin Forms Login Logout procedures with Web API

I want to log in and get cookies in xamarin forms. At the same time, the data will remain until I log out, but when I log out, the data I keep in the cookie will be reset. how can i do it?(Actually, I can login now, but I don't understand the logic of saving the information in the cookie and logging out.)
EDIT : I want to do it with using AppShell
if (Connectivity.NetworkAccess == NetworkAccess.Internet)
{
var userName = tbName.Text;
var password = tbPassword.Text;
var serviceUrl = "API";
var paramList = new List<ServiceParameterObject>();
paramList.Add(new ServiceParameterObject("_userCode", userName));
paramList.Add(new ServiceParameterObject("_userPassword", password));
var apiResult = ApiResult.SendPostRequestFromBody(serviceUrl, paramList);
if (apiResult.Status)
{
var user = JsonConvert.DeserializeObject<User>(apiResult.Message);
//Preferences.Set("userName", tbName.Text);
//Preferences.Set("Password", tbPassword.Text);
Preferences.Set("userId", user.Id.ToString());
var userIdCookie = Preferences.Get("userId", String.Empty);
await Shell.Current.GoToAsync($"//{nameof(HomePage)}");
}
else
{
await DisplayAlert("Uyarı", "Kullanıcı Adınız veya Şifreniz hatalıdır. Lütfen tekrar deneyiniz.", "Tamam");
}
}
else
{
await DisplayAlert("Uyarı", "İnternet bağlantınız yok. Lütfen Bağlantınızı kontrol edip tekrar deneyiniz", "Tamam");
}
Have your looked into Xamarin forms' Secure Storage ?
I think this could the easiest way for you to achieve your desired implementation.
Upon launch, look into storage to see if any information is stored (your cookie or any other auth information)
a) If Nothing is stored, run login and store information
b) If something is stored, grant access to app and fetch stored info
Upon logout, simply clear the stored cookie

"The user hasn't authorized the application to perform this action" in WinForms app

I am trying to post to my own status on Facebook using WinForms and the Facebook .NET SDK. I am using the code below to post an image. I get this error:
"The user hasn't authorized the application to perform this action"
I looked at similar questions but they deal with posting from a web app to other user's page which need a manual authorization on a confirmation page.
I am not finding where I grant myself this permission on Facebook. I might be missing a setting in the code too.
Any ideas?
private bool PostImage(string UserToken, string Status, string ImagePath)
{
try
{
FacebookClient fb = new FacebookClient(UserToken);
//for testing. id & name have values -----
dynamic me = fb.Get("me");
var id = me.id;
var name = me.name;
// ----------------------------------------
var imgstream = File.OpenRead(ImagePath);
dynamic response = fb.Post("/me/feed", new
{
message = Status,
file = new FacebookMediaStream
{
ContentType = "image/jpg",
FileName = Path.GetFileName(ImagePath)
}.SetValue(imgstream)
});
return true;
}
catch (Exception ex)
{
return false;
}
}
You are trying to post status on behalf of user means your application need to get permission from user using "publish_actions".
Refer : https://developers.facebook.com/docs/facebook-login/permissions/v2.5#reference-publish_actions

Authentication - Only HTTPS scheme is allowed

Currently working on an app that is connecting to Azure Mobile Services, and needs to require a Microsoft Account to authenticate.
I have been following this guide:
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-windows-universal-dotnet-get-started-users/ Unforunately I have run into this error: Only https scheme is allowed. and I am not entirely sure on how to fix it.
Screenshot of error: http://i.stack.imgur.com/hod9i.png
My code is as follows and comes from the guide listed above.
private async void executiveLoginBtn_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
await AuthenticateAsync();
}
// Define a member variable for storing the signed-in user.
private MobileServiceUser user;
// Define a method that performs the authentication process
// using a Facebook sign-in.
private async System.Threading.Tasks.Task AuthenticateAsync()
{
while (user == null)
{
string message;
try
{
// Change 'MobileService' to the name of your MobileServiceClient instance.
// Sign-in using Facebook authentication.
user = await App.MobileService
.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);
message =
string.Format("You are now signed in - {0}", user.UserId);
}
catch (InvalidOperationException)
{
message = "You must log in. Login Required";
}
var dialog = new MessageDialog(message);
dialog.Commands.Add(new UICommand("OK"));
await dialog.ShowAsync();
}
}
The error also says "WinRT Information: URI Scheme is not https" - so how could I go about making the URI scheme https or otherwise fixing this error when authenticating to Azure Mobile Services?
1) Select the local MobileService project in Solution Explorer.
2) In the Properties window, change SSL Enabled to True.
3) Take note of the SSL URL and use that address to initialize the MobileServiceClient object in your client application.
How I fix the error is as follows:
SSL Enabled to True.
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-how-to-register-microsoft-authentication/
Input to Redirect URL
App.xaml.cs
public static MobileServiceClient MobileService = new MobileServiceClient("http://service.azure-mobile.net/", "---------------------");
Change to
public static MobileServiceClient MobileService = new MobileServiceClient("https://service.azure-mobile.net/", "---------------------");

Post message with Facebook SDK .NET

I have created a facebook page and a facebook application for my website and now I need to post messages onto the facebook page with help of facebook SDK .NET.
This is what I got so far :
public static bool UploadPost(string message)
{
dynamic result;
//https://developers.facebook.com/tools/explorer/
//https://developers.facebook.com/tools/access_token/
FacebookClient client = new FacebookClient("secret access token");
result = client.Get("oauth/access_token", new
{
client_id = "[Client ID number]",
client_secret = "[Client sercret",
grant_type = "client_credentials",
});
result = client.Post("[facebook app Id]/feed", new { message = "Test Message from app" });
//result.id;
result = client.Get("[facebook app Id]");
return false;
}
When running this I get : Additional information: (OAuthException - #200) (#200) The user hasn't authorized the application to perform this action on client.Post. If I remove the client.Post row every thing works good, the correct data is fetched.
I have tried follow some helps on facebook SDK .NET website but it is still not working.
The main problem now is that I get permission exception. I was hoping that my facebook app hade enouth permissions to publish post from my website to the facebook page.
Here is a step wise tutorial to register your application with facebook and get an app Id for your application.
Then for permissions ::
private const string ExtendedPermissions = "user_about_me,read_stream,publish_stream";
This is a string of permissions. Pass it on further for getting correct permissions to post messages on page. Post using your standard code for posting no FB pages.
Cheers. Hope it helps.
Are you trying to post to [facebook app id]?
I would recomend to post to "me/feed" and test if that works.
Also, to post to Facebook you have to have the publish_stream permission
private async Task Authenticate()
{
string message = String.Empty;
try
{
session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream,publish_actions");
App.AccessToken = session.AccessToken;
App.FacebookId = session.FacebookId;
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Pages/LandingPage.xaml", UriKind.Relative)));
}
catch (InvalidOperationException e)
{
message = "Login failed! Exception details: " + e.Message;
MessageBox.Show(message);
}
}
Should work :)
The following should work.
var fb = new FacebookClient("access_token");
fb.PostCompleted += (o, e) => {
if(e.Error == null) {
var result = (IDictionary<string, object>)e.GetResultData();
var newPostId = (string)result.id;
}
};
var parameters = new Dictionary<string, object>();
parameters["message"] = "My first wall post using Facebook SDK for .NET";
fb.PostAsync("me/feed", parameters);
This was taken directly from the documentation.
By creating a extended page token and use it to make the post everything works just fine. See this : How to get Page Access Token by code?
Im surprised that this simple task was so hard to get running and that there was vary little help to get.

Linq2Twitter Single User Authorisation Null Value Exception

I've been developing an internal ASP.NET web forms application for our business and one of the requirements is to display our Twitter feed on our portal home page to all users.
For this I've decided that it is best to use LinqToTwitter Single User Authorisation to get the statuses for everyone without them having to authenticate their own accounts.
My main problem at the minute is that when we use the auth object to get the TwitterContext, it returns with an error on the TwitterContext saying
Value cannot be null
on every internal context object.
I've gone through our twitter application settings at http://dev.twitter.com and I have our correct consumer key/token and access key/token. The permission for the application is set to Read-Only. There is no callback URL specified on the http://dev.twitter.com website as it is currently on our internal system (so it wouldn't be able to get back anyway). Is this where it is going wrong? Do I need to forward some ports and allow the callback to get through to our development machines?
Here's the code for prudence. As far as I can see, there is nothing wrong with it. I know that it is set to .FirstOrDefault, this was just for seeing whether it is actually getting anything (which it isn't).
Thanks for any help you can give! :)
private async Task GetTweets()
{
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"],
AccessToken = ConfigurationManager.AppSettings["accessToken"],
AccessTokenSecret = ConfigurationManager.AppSettings["accessTokenSecret"],
}
};
try
{
using (TwitterContext twitterContext = new TwitterContext(auth))
{
var searchResponse = await (from c in twitterContext.Status
where c.Type == StatusType.User
&& c.ScreenName == "my_screenname"
select c).ToListAsync();
Tb_home_news.Text = searchResponse.FirstOrDefault().Text;
}
}
catch (Exception ex)
{
Tb_home_news.Text = ex.Message;
}
}
If you're creating a Web app, you do need to add a URL to your Twitter App page. It isn't used for the callback, but might help avoid 401's in the future if you're using AspNetAuthorizer.
It looks like you have a NullReferenceException somewhere. What does ex.ToString() say?
Double check CredentialStore after initialization to make sure that all 4 credentials are populated. AccessToken and AccessTokenSecret come from your Twitter app page.
Does searchResponse contain any values? Calling FirstOrDefault on an empty collection will return null.

Categories