0

Well, this was a mistake. I decided to migrate my MVC5 application to MVC6 and things were going fine until I needed to migrate my authentication. My MVC application was logging in using an external Web Api 2 application which returns a token. I built a filter to handle that very simply like this:

/// <summary>
/// Uses the session to authorize a user
/// </summary>
public class SimpleAuthorize : AuthorizeAttribute
{

    /// <summary>
    /// Authorizes the user
    /// </summary>
    /// <param name="httpContext">The HTTP Context</param>
    /// <returns></returns>
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var accessToken = httpContext.Session["AccessToken"];

        if (accessToken == null)
            return false;

        return true;
    }
}

which was applied to all controllers. Now, it appears that you can't do that anymore as mentioned here. So, how can I get my application to work with the API?

I have tried searching and found nothing that helps me with my situation. Does anyone know how I can solve this or could point me in the direction of some decent documentation?

Community
  • 1
  • 1
r3plica
  • 11,412
  • 17
  • 75
  • 203

1 Answers1

0

You'd approach it by writing Authorization middleware which creates an identity out of the access token. Having a valid identity is enough for authorization to succeed, and then you can delve into policy should you need something more detailed. Something like

public class SessionAuthenticationHandler : 
    AuthenticationHandler<SessionAuthenticationOptions>
{

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var sessionToken = Request.HttpContext.Session.GetString("Token");

        if (sessionToken == null)
        {
            return AuthenticateResult.Failed("No session token");
        }

        // Construct principal here
        var principal = 
            new ClaimsPrincipal(new ClaimsIdentity(new[] { 
                new Claim("SessionToken", sessionToken) }, Options.AuthenticationScheme));

        var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), 
            Options.AuthenticationScheme);
        return AuthenticateResult.Success(ticket);
    }
}

Having said that the reason ASP.NET has never used session to hold authentication details is due to session fixation attacks.

blowdart
  • 52,422
  • 11
  • 102
  • 145