Colin
Colin

Reputation: 4135

Authentication That Doesn't Require Javascript?

I have a Web API app, initialized thusly:

        app.UseCookieAuthentication();
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        app.UseOAuthBearerTokens(OAuthOptions);
        app.UseGoogleAuthentication();

For calls to most controllers, it works great. However, it also requires a bit of javascript before client-side service calls are made:

function getSecurityHeaders() {
    var accessToken = sessionStorage["accessToken"] || localStorage["accessToken"];
    if (accessToken) {
        return { "Authorization": "Bearer " + accessToken };
    }
    return {};
}

The problem is that we have a certain type of controller (one that accesses files) where no javascript can be run during the call. For example, the call might be to:

  http://mysite/mycontroller/file/filename.jpg

...where the value is assigned as the src attribute of an img tag. The call works, but Thread.CurrentPrincipal.Identity is unauthenticated with a null name, so there's currently not a way to enforce security.

I'm new to Web API, so it may be a dumb question, but what's the way around this? What switches do I need to flip to not require javascript to add security headers? I was considering trying to find a way to force an authorization header in an IAuthorizationFilter or something, but I'm not even sure that would work.

Upvotes: 1

Views: 80

Answers (1)

Colin
Colin

Reputation: 4135

So I figured out the solution to my problem.

First, I needed to configure the app to use an authentication type of external cookies thusly:

    //the line below is the one I needed to change
    app.UseCookieAuthentication(AuthenticationType = DefaultAuthenticationTypes.ExternalCookie);

    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    app.UseOAuthBearerTokens(OAuthOptions);
    app.UseGoogleAuthentication();

Second, it turned out there was a line of code in my WebApiConfig file that was disabling reading the external cookie:

    //this line needed to be removed
    //config.SuppressDefaultHostAuthentication();

After that, I could see the external cookie from Google, which passed along an email address I could identify the user with.

Upvotes: 1

Related Questions