ASP.net identity - external login - won't log

2019-02-27 09:31发布

In my application, all my authentication happens with Google - ie - all my users are Google Accounts.

I don't need users to need to register in my app, just sign in using a Google account. However, I do want to manage Roles for the users with ASP.net Identity (I think)

With that in mind, on successful external authentication, I create an ASP.net Identity user (if one doesn't exist)

So, I've got my ExternalLoginCallback as follows:

    [AllowAnonymous]
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
    {
        var authenticationManager = Request.GetOwinContext().Authentication;

        var loginInfo = await authenticationManager.GetExternalLoginInfoAsync();

        //successfully authenticated with google, so sign them in to our app
        var id = new ClaimsIdentity(loginInfo.ExternalIdentity.Claims, DefaultAuthenticationTypes.ApplicationCookie);
        authenticationManager.SignIn(id);

        //Now we need to see if the user exists in our database
        var user = UserManager.FindByName(loginInfo.Email);

        if (user == null)
        {
            //user doesn't exist, so the user needs to be created
            user = new ApplicationUser { UserName = loginInfo.Email, Email = loginInfo.Email };

            await UserManager.CreateAsync(user);

            //add the google login to the newly created user
            await UserManager.AddLoginAsync(user.Id, loginInfo.Login);
        }

        return RedirectToLocal(returnUrl);
    }

Idea being, I can now manage users, add roles, check if users are in roles, etc....

Firstly, is this a sensible approach? Or have I over complicated it?

One issue I'm having, however, is with logging out of my application

My Logout action looks like:

public ActionResult LogOut()
{
    HttpContext.GetOwinContext().Authentication.SignOut();

    return RedirectToAction("Index", "Home");
}

My Index action is decorated with the [Authorize] attribute - However, when I 'logout' - it redirects to Home.Index - but I still seem to be logged in?

2条回答
叼着烟拽天下
2楼-- · 2019-02-27 10:09

According to this ASPNet Identity Work Item, this is by design, and you need to call directly to Google's API in order to log the user out.

查看更多
一夜七次
3楼-- · 2019-02-27 10:24

completing the post Logout link with return URL (OAuth) Here is a solution that work for me :

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
        return Redirect("https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=https://[url-of-your-site]");
    }
查看更多
登录 后发表回答