2

I have implemented Facebook and Twitter logins on my MVC5 site and all is working well.

What I would like to do seems quote simple but I am not sure how to do it.

I can get the username of the logged in user with:

System.Web.HttpContext.Current.User.Identity.Name

However I would like to know if that user logged in using Facebook or Twitter and the ProviderKey from the relevant social network.

Hopefully this is easy to do

Thanks.

Always Learning
  • 365
  • 6
  • 20

2 Answers2

0

You can get all the external login information using below method.

private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
    get
    {
        return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
    }
    private set
    {
        _userManager = value;
    }
}

In your action:

var getExternalLoginInfor = UserManager.GetLogins(User.Identity.GetUserId());

Hope this helps.

DSR
  • 4,588
  • 29
  • 28
  • Hey - thanks for your feedback. This gives me a full list of all logins the user has registered. However, is there a way for me to tell which one they currently logged in with? – Always Learning Oct 28 '14 at 00:37
  • I am not sure about easy way to getting that details, someone will help you. But, if it is social login, you could add provider name into a claim and use it during the context and compare it with getExternalLoginInfor. http://stackoverflow.com/questions/20383955/how-to-add-claims-in-asp-net-identity – DSR Oct 28 '14 at 01:20
0

You can get it from extension method GetExternalLoginInfo of AuthenticationManager.

var loginInfo = AuthenticationManager.GetExternalLoginInfo();
if (loginInfo != null)
{
     var externalProvider = loginInfo.Login.LoginProvider;
}

Edit: In your ApplicationSignInManager : SignInManager class override method SignInAsync

There you can externalLoginInfo and add it as a claim

public override async Task SignInAsync(User user, bool isPersistent, bool rememberBrowser)
{
    var userIdentity = await CreateUserIdentityAsync(user); 

    //
    var logininfo = AuthenticationManager.GetExternalLoginInfo();
    userIdentity.AddClaim(new Claim("ExternalLoginProvider", logininfo.Login.LoginProvider));
    //

    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
    if (rememberBrowser)
    {
         var rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(ConvertIdToString(user.Id));
         AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity, rememberBrowserIdentity);
    }
    else
    {
         AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity);
    }
}

Then you can access it like this:

var identity = (ClaimsIdentity)User.Identity;
var loginProvide = identity.FindFirst("ExternalLoginProvider").Value;
tmg
  • 19,895
  • 5
  • 72
  • 76