Cin
Cin

Reputation: 113

In Xamarin UWP apps, How to get currently Windows logged-in User details

I need to use Windows authentication in my Xamarin UWP app. How can i access currently logged-in user details in the app. Need to retrieve user Active Directory login ID who currently logged in Windows.

I already tried below solution and it gives empty results for me.

How can I get username or id of currently logged in user in UWP App

Appreciate your help....

Upvotes: 0

Views: 560

Answers (3)

Damien Doumer
Damien Doumer

Reputation: 2286

This is fairly simple. You should do it at the platform specific level, using Windows.System.User, To retrieve the current user's information. Here is a post which describes detaily how to accomplish this.

Upvotes: 0

Nico Zhu
Nico Zhu

Reputation: 32785

If you have not add User Account Information capability to your app in the Package.appxmanifest, you will not have permission to access user account info.

enter image description here

For other reasons, if you authinticated using hotmail, you need KnownUserProperties.FirstName and KnownUserProperties.LastName to get your account name.

private async void GetUser()
{
    IReadOnlyList<User> users = await User.FindAllAsync();

    var current = users.Where(p => p.AuthenticationStatus == UserAuthenticationStatus.LocallyAuthenticated &&
                                p.Type == UserType.LocalUser).FirstOrDefault();

    // user may have username
    var data = await current.GetPropertyAsync(KnownUserProperties.AccountName);
    string displayName = (string)data;

    // authinticated using hotmail 
    if (String.IsNullOrEmpty(displayName))
    {

        string a = (string)await current.GetPropertyAsync(KnownUserProperties.FirstName);
        string b = (string)await current.GetPropertyAsync(KnownUserProperties.LastName);
        displayName = string.Format("{0} {1}", a, b);
    }
}

Please note the above code only works in UWP native project, and it can't be used directly in the pcl, you need to create GetUser method via DependencyService.

Update

If you have authorized with ADAL, you could use AcquireTokenSilentAsync method get info from token cache silently, for more refer this.

Upvotes: 1

Jenny
Jenny

Reputation: 1229

Here's a UWP sample that uses ADAL. ADAL.NET does not expose directly the notion of user from an authentication context. It does provide a UserInfo, as a property of the AuthenticationResult. When you get back the auth result, you can use the UserInfo property to get the Displayable ID of the signed in user.

Here's more from the ADAL wiki.

Upvotes: 1

Related Questions