Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 External authentication with authentication mode=Forms

I'm following this tutorial to create a simple MVC 5 app with external authentication. It's working fine, but, if I change the authentication mode="None" to authentication mode="Forms" it stops working.

I'm getting null on:

await HttpContext.GetOwinContext().Authentication.GetExternalLoginInfoAsync()

I'm reading a lot about something to suppress FormsAuthentication on redirect. I don't know if it's the right path, but I tried to install this nuget packet and the problem is still there.

So, why I'm getting null everytime I change the authentication mode?

like image 890
Felipe Miosso Avatar asked Nov 10 '13 18:11

Felipe Miosso


2 Answers

I was able to get this working (OWIN and FormsAuthentication) by adding Response.SuppressFormsAuthenticationRedirect = true to the ChallengeResult Class.

If you are following the tutorial, here is the code:

public class ChallengeResult : HttpUnauthorizedResult
{
    public ChallengeResult(string provider, string redirectUri)
        : this(provider, redirectUri, null)
    {
    }

    public ChallengeResult(string provider, string redirectUri, string userId)
    {
        LoginProvider = provider;
        RedirectUri = redirectUri;
        UserId = userId;
    }

    public string LoginProvider { get; set; }
    public string RedirectUri { get; set; }
    public string UserId { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        // this line did the trick
        context.RequestContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;

        var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
        if (UserId != null)
        {
            properties.Dictionary[XsrfKey] = UserId;
        }

        context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
    }
}
like image 136
Felipe Miosso Avatar answered Oct 14 '22 16:10

Felipe Miosso


Usually, you would set authentication mode="None", when users are not authenticated at all or if you plan to develop custom authentication code. MVC 5 has been updated to use ASP.NET Identity for authentication.

ASP.NET Identity supports claims-based authentication, where the user’s identity is represented as a set of claims. Here, you set authentication mode="Forms" , Claims will not work, because ASP.NET Forms Authentication does not support claims. That's why you get a null value.

like image 43
Lin Avatar answered Oct 14 '22 15:10

Lin