Search code examples
asp.netasp.net-mvcfacebookasp.net-mvc-4asp.net-identity-2

How to authorize user who logged in using external login in Asp.Net MVC


Introduction I am working with authorization in application, registered users are authorized on role based for some actions/controllers i.e

[Authorize(Roles = "Developer,Admin,User")]

My question is, What if a user is logged in using external login method like facebook or google, how to authorize him.

What should be or can be done to achieve this, if someone know about that then please do help. Thanks for your time.


Solution

  • Do it like this

    public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
              var user = new ApplicationUser { UserName = model.Email, Email = model.Email, DisplayName=model.Displayname };
                var result = await UserManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        UserManager.AddToRole(user.Id, "ExternalUser");// This is the important line
    
                        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
    
                        return RedirectToLocal(returnUrl);
                    }
                }
    
        }
    

    Whenever the user logs in via an external service, he is automatically mapped to the role "External user". Now you can authorize it like this

    [Authorize(Roles = "Externaluser")]