Vindberg
Vindberg

Reputation: 1542

Manual set cookies using accesstoken/AuthenticationResult -like UseCookieAuthentication() owin middleware

In an Action in a Controller, we have the AuthenticationResult which contains AccessToken.

We would like to do a manual login with this token that is equal to the UserCookieAuthentication owin middleware. Is that possible?

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                TokenValidationParameters = new TokenValidationParameters
                {
                ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
            },
            });
    }
}

I have been looking at HttpContext.GetOwinContext().Authentication.SignIn() but that doesn't take any Tokens.

Upvotes: 1

Views: 997

Answers (1)

Vindberg
Vindberg

Reputation: 1542

Looking in the Katana/Owin Github project the following TokenHelper solved it along with using the AuthenticationResponseGrant method:

                result = await authContext.AcquireTokenAsync(resource, clientId, uc);

                var principal = await new TokenHelper().GetValidatedClaimsPrincipalAsync(result.AccessToken);

                var claimsIdentity = new ClaimsIdentity(principal.Claims, CookieAuthenticationDefaults.AuthenticationType);

                var properties = new AuthenticationProperties();

                HttpContext.GetOwinContext().Authentication.AuthenticationResponseGrant =
                    new AuthenticationResponseGrant(claimsIdentity, properties);

Upvotes: 2

Related Questions