Security icon indicating copy to clipboard operation
Security copied to clipboard

Issue using Redis to Store Shared Cookie from ASP.NET 4.x & AspNet Core App

Open aagarwal10 opened this issue 9 years ago • 3 comments

Hi,

I have used this link https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/compatibility/cookie-sharing to share aspnet core cookie with my ASP.NET 4.x Katana (Web Forms) application successfully. However, I am not getting the single sign experience when I implement the Redis Ticket Store on aspnetcore side and Redis Session Store on ASP.NET 4.x side, to store the shared cookie. In this case, I am always getting redirected to the login page.

Please help me understand why cookie sharing works without Redis between two apps but cookie sharing does not work with Redis as the centralized Session Store.

Thanks a lot, Appreciate all the insight provided here.

Here is my startup code on ASP.NET 4.x side in Startup

public void ConfigureAuth(IAppBuilder app) { // Now we create a data protector, with a fixed purpose and sub-purpose used in key derivation. var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys")); var dataProtector = protectionProvider.CreateProtector( "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookie", "v2");

        // And finally create a new auth ticket formatter using the data protector.
        var ticketFormat = new AspNetTicketDataFormat(new DataProtectorShim(dataProtector));

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = CookieConstants.AuthenticationScheme,
            CookieName = "AspNet.SharedCookie",
            LoginPath = new PathString("/Account/Login"),
            TicketDataFormat = ticketFormat,
            CookieManager = new Microsoft.Owin.Infrastructure.ChunkingCookieManager(),
            SessionStore = new RedisCacheSessionStore()
        });
  
    }

Here is RedisSessionStore class;

public class RedisCacheSessionStore : IAuthenticationSessionStore { private readonly IDistributedCache _cache;

    private const string KeyPrefix = "AuthSessionStore-";
    //TODO : Need to Configure this
    public static int RedisPort = 6379; // override default so that do not interfere with anyone else's server

    public RedisCacheSessionStore()
    {
        _cache = new RedisCache(new RedisCacheOptions
        {
            //TODO : Need to Configure this
            Configuration = "localhost:" + RedisPort,
            InstanceName = "Redis.Master"
        });

    }
    public Task<string> StoreAsync(AuthenticationTicket ticket)
    {
        var guid = Guid.NewGuid();
        var key = KeyPrefix + guid;
        RenewAsync(key, ticket);
        return Task.FromResult(key);
    }

    public Task RenewAsync(string key, AuthenticationTicket ticket)
    {
        var options = new DistributedCacheEntryOptions();
        var expiresUtc = ticket.Properties.ExpiresUtc;
        if (expiresUtc.HasValue)
        {
            options.SetAbsoluteExpiration(expiresUtc.Value);
        }

        //TODO : Need to Configure this
        options.SetSlidingExpiration(TimeSpan.FromMinutes(2));

        _cache.Set(key, SerializeToBytes(ticket), options);

        return Task.FromResult(0);
    }

    public Task<AuthenticationTicket> RetrieveAsync(string key)
    {
        var ticket = DeserializeFromBytes(_cache.Get(key));
        return Task.FromResult(ticket);
    }

    public Task RemoveAsync(string key)
    {
        _cache.Remove(key);
        return Task.FromResult(0);
    }

    private static byte[] SerializeToBytes(AuthenticationTicket source)
    {
        return AspNetTicketSerializer.Default.Serialize(source);
    }

    private static AuthenticationTicket DeserializeFromBytes(byte[] source)
    {
        return source == null ? null : AspNetTicketSerializer.Default.Deserialize(source);
    }
}

Here is the startup code for AspNetCore App;

var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys")); var dataProtector = protectionProvider.CreateProtector( "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Cookie", "v2"); // And finally create a new auth ticket formatter using the data protector. var ticketFormat = new TicketDataFormat(dataProtector);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = CookieConstants.AuthenticationScheme,
            CookieName = "AspNet.SharedCookie", //This is used to build a common cookie name between two apps
            LoginPath = new PathString("/Auth/RedirectToLegacy/"), //RedirectToLegacy
            //AccessDeniedPath = new PathString("/Auth/Login/"),
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            //SessionStore = new RedisCacheTicketStore(),
            TicketDataFormat = ticketFormat
        });

Here is the RedisTicketStore class;

public class RedisCacheTicketStore : ITicketStore { private readonly IDistributedCache _cache;

    private const string KeyPrefix = "AuthSessionStore-";
    //TODO : Need to Configure this
    public static int RedisPort = 6379; // override default so that do not interfere with anyone else's server

    public RedisCacheTicketStore()
    {
        _cache = new RedisCache(new RedisCacheOptions
        {
            //TODO : Need to Configure this
            Configuration = "localhost:" + RedisPort,
            InstanceName = "Redis.Master"
        });

    }

    public Task<string> StoreAsync(AuthenticationTicket ticket)
    {
        var guid = Guid.NewGuid();
        var key = KeyPrefix + guid;
        RenewAsync(key, ticket);
        return Task.FromResult(key);
    }

    public Task RenewAsync(string key, AuthenticationTicket ticket)
    {
        var options = new DistributedCacheEntryOptions();
        var expiresUtc = ticket.Properties.ExpiresUtc;
        if (expiresUtc.HasValue)
        {
            options.SetAbsoluteExpiration(expiresUtc.Value);
        }

        //TODO : Need to Configure this
        options.SetSlidingExpiration(TimeSpan.FromMinutes(2));

        _cache.Set(key, SerializeToBytes(ticket), new DistributedCacheEntryOptions());

        return Task.FromResult(0);
    }

    public Task<AuthenticationTicket> RetrieveAsync(string key)
    {
        var ticket = DeserializeFromBytes(_cache.Get(key));
        return Task.FromResult(ticket);
    }

    public Task RemoveAsync(string key)
    {
        _cache.Remove(key);
        return Task.FromResult(0);
    }

    private static byte[] SerializeToBytes(AuthenticationTicket source)
    {
        return TicketSerializer.Default.Serialize(source);
    }

    private static AuthenticationTicket DeserializeFromBytes(byte[] source)
    {
        return source == null ? null : TicketSerializer.Default.Deserialize(source);
    }
}

aagarwal10 avatar Feb 15 '17 03:02 aagarwal10

Figured out that the SessionIdClaim is not same between two CookieAuthenticationHandlers (AspnetCore & Microsoft.Owin.Security) is not same, which causes the above issue.

aagarwal10 avatar Feb 16 '17 16:02 aagarwal10

How did you solve SessionIdClaim problem please?

marc3lsk avatar May 01 '17 17:05 marc3lsk

SessionIdClaim is hard coded in both AspNet Core & Owin Cookie Library. Since there is no parameter in Cookie Options to configure it, hence I left cookie to be serialized version of Authentication Ticket and not use Redis at all as TicketStore.

aagarwal10 avatar May 01 '17 17:05 aagarwal10