Automatic login using jwt in Cookie in ASP.net MVC Core

陌路散爱 提交于 2021-01-29 15:03:55

问题


My process flow is :

  1. User logs into a Issuer Application (Username/Password)
  2. Clicks a link of the Client Application that they want to goto
  3. Issuer Application creates a jwt and stores it in a Cookie
  4. Issuer Application does a Response.Redirect to Client Application
  5. Client Application authenticates user using the jwt in the Cookie and creates the Principal and automatically logs in user.

Below is my Client Application setting from the Startup ConfigureServices method:

var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("password"));

            SigningCredentials SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = false,
                ValidIssuer = "issuerapp",

                ValidateAudience = false,
                ValidAudience = "clientapp",

                ValidateIssuerSigningKey = true,
                IssuerSigningKey = SigningCredentials.Key,

                RequireExpirationTime = false,
                ValidateLifetime = true,

                ClockSkew = TimeSpan.Zero
            };


            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.ClaimsIssuer = "issuerapp";
                options.TokenValidationParameters = tokenValidationParameters;
                options.SaveToken = true;
            })
            .AddCookie(JwtBearerDefaults.AuthenticationScheme,
            options =>
            {
                options.Cookie.HttpOnly = true;
                options.Cookie.Name = Configuration.GetValue<string>("AppSettings:CookieName");
                options.AccessDeniedPath = authenticationSettings.AccessDeniedPath;
                options.Events = new CookieAuthenticationEvents
                {
                    // Check if JWT needs refreshed 
                    OnValidatePrincipal = RefreshTokenMonitor.ValidateAsync,
                    OnSigningOut = (context) =>
                    {
                        context.HttpContext.Response.Redirect(Configuration.GetValue<string>("AppSettings:LogoutPath"));
                        return Task.CompletedTask;
                    },
                };
            });

In my Client Application I have all controllers decorated with [Authorize] attribute.

I need the Client Application automatically authenticating the user using the jwt. Which is not happening using the above mentioned configurations. My AccessDeniedPath (Action Method) is not getting hit either.

The workaround that I have been using is to redirect user from the Issuer Applicaiton to a Login action in the Client Application where :

  1. I read the jwt from the Cookie
  2. Validate the jwt to get the Principal
  3. Call httpContext.SignInAsync

How can I get the user logged in automatically using the jwt.

Any help / pointer are appreciated.

Thanks.


回答1:


By default , the AddJwtBearer extension will get the token from request's Authorization header :

Authorization: Bearer <token>

But you are pass the token in cookie , so you can find the token in cookie and set token in OnMessageReceived event in AddJwtBearer :

options.Events = new JwtBearerEvents  {
    OnMessageReceived = ctx =>
    {
        ctx.Token = ctx.HttpContext.Request.Cookies["jwt"];

        return Task.CompletedTask;
    }
};


来源:https://stackoverflow.com/questions/60603719/automatic-login-using-jwt-in-cookie-in-asp-net-mvc-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!