0

.NET CORE 3.1

I got an answer how to logout all clients from Identity Server.

I work by this example (chapter) REVOCATION.

But now I have a new problem. On OnSignedIn event I want to add the user id to the Redis Cache, but I dont know how.

This is a bad practice:

var sp = services.BuildServiceProvider();
var cache = sp.GetService<IDistributedCache>();
cache.SetString("helloFromRedis", "world");
var valueFromRedis = cache.GetString("helloFromRedis");
Console.WriteLine(valueFromRedis);

My Startup.cs

public class Startup
{
   public Startup(IConfiguration configuration)
   {
       Configuration = configuration;
   }

   public IConfiguration Configuration { get; }

   public void ConfigureServices(IServiceCollection services)
   {
     services.AddStackExchangeRedisCache(options =>
     {
        options.Configuration = RedisString;
     });


     services.AddAuthentication(options =>
     {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";                              
     })
      .AddCookie("Cookies", options =>
      {
         options.Cookie.HttpOnly = true;                   
         options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
         options.SlidingExpiration = true;
         options.Events.OnSignedIn(a => {
               // there I want to resolve cache and put userId from claims.
         });
      })
      .AddOpenIdConnect("oidc", options =>
       {
        //...
      });
   }

How I can resolve Redis cache?

yacc
  • 2,915
  • 4
  • 19
  • 33
hdoitc
  • 386
  • 1
  • 10
  • 21
  • You must have an endpoint that is called when the user authenticates. You should not use services inside that event, it's meant for debugging. Use the endpoint and inject `IDistributedCache` there and then cache what ever you need. – alsami Jan 15 '20 at 12:02
  • @alsami How I can create endpoint? After success login Identity Server redirects to /signin-oidc, and after that app redirects to previous page. I can't handle /signin-oidc endpoint. – hdoitc Jan 15 '20 at 12:16
  • Don't you have a login callback registered? http://docs.identityserver.io/en/latest/topics/signin.html#login-workflow – alsami Jan 15 '20 at 12:23
  • @alsami I have registered in mvc client options.CallbackPath = "/callback-login"; In Nginx logs for login method: POST 302, but Console doesn't write word and client redirects to previous page. [HttpPost("callback-login")] public IActionResult Login() { Console.WriteLine("<<< Ok >>>"); return Ok(); } – hdoitc Jan 16 '20 at 14:24

1 Answers1

0

You can do it like this:

o.Events.OnSignedIn = ctx =>
{
    var cache = ctx.HttpContext.RequestServices.GetRequiredService<IDistributedCache>();
    return  Task.CompletedTask;
};

RequestServices property is an instance of IServiceProvider.

mtkachenko
  • 5,389
  • 9
  • 38
  • 68