c# - How can I set up both a RefreshAccess Token as HTTP-Only? - Stack Overflow

Let me give you some context.I am trying to implement a RefreshAccess with JWT.But I am having issue

Let me give you some context.

I am trying to implement a Refresh/Access with JWT. But I am having issues with the implementation.

You see the problem is that whenever I use the [Authorize] attribute. It seems to default to the Refresh Token which doesn't hold relevant data. At least for the endpoints that require more data than just lets say the ID and username.

Before what I would do is just have the Access token be send through as a Bearer token. But now since both are HTTP-Only I have to handle it another way.

In case necessary this is the setup for my authorization:

 public static void AddAuthenticationConfig(this IServiceCollection services, IConfiguration config)
    {
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateAudience = false,
                ValidateIssuer = true,
                ValidateLifetime = true,
                ValidIssuer = config["JWT:Issuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["JWT:Key"]!)),
            };
        });
    }

Fairly basic. But it did get the job done.

Also for this specific implementation what I would do before was just have a refresh-access-token endpoint and just refresh it based on the Refresh Token which would be fetch using the HttpContext class.

Now I am not sure if it will be the same given that I have two HttpOnly and also if I would need to implement some sort of validation in case the Refresh Token expires.

As you can see I've plenty of question when implementing this specific situation. So any guidance, resource or advice into how to implement Refresh/Access Tokens when both are setup as HTTP-Only would be highly appreciated.

Thank you for your time!

Let me give you some context.

I am trying to implement a Refresh/Access with JWT. But I am having issues with the implementation.

You see the problem is that whenever I use the [Authorize] attribute. It seems to default to the Refresh Token which doesn't hold relevant data. At least for the endpoints that require more data than just lets say the ID and username.

Before what I would do is just have the Access token be send through as a Bearer token. But now since both are HTTP-Only I have to handle it another way.

In case necessary this is the setup for my authorization:

 public static void AddAuthenticationConfig(this IServiceCollection services, IConfiguration config)
    {
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateAudience = false,
                ValidateIssuer = true,
                ValidateLifetime = true,
                ValidIssuer = config["JWT:Issuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["JWT:Key"]!)),
            };
        });
    }

Fairly basic. But it did get the job done.

Also for this specific implementation what I would do before was just have a refresh-access-token endpoint and just refresh it based on the Refresh Token which would be fetch using the HttpContext class.

Now I am not sure if it will be the same given that I have two HttpOnly and also if I would need to implement some sort of validation in case the Refresh Token expires.

As you can see I've plenty of question when implementing this specific situation. So any guidance, resource or advice into how to implement Refresh/Access Tokens when both are setup as HTTP-Only would be highly appreciated.

Thank you for your time!

Share Improve this question edited Mar 28 at 7:55 Lex Li 63.4k11 gold badges124 silver badges161 bronze badges asked Mar 27 at 8:43 yzkaelyzkael 3312 silver badges9 bronze badges 1
  • Is this NET or Framework? – GH DevOps Commented Mar 27 at 10:34
Add a comment  | 

1 Answer 1

Reset to default 1

You could store the accesstoken in Http-Only cookie and read the token from cookie when you receive request

set the cookie:

public void SetTokensInsideCookie(TokenDto tokenDto, HttpContext context)
{
    context.Response.Cookies.Append("accessToken", tokenDto.AccessToken,
        new CookieOptions
        {
            Expires = DateTimeOffset.UtcNow.AddMinutes(5),
            HttpOnly = true,
            IsEssential = true,
            Secure = true,
            SameSite = SameSiteMode.None
        });
    context.Response.Cookies.Append("refreshToken", tokenDto.RefreshToken,
        new CookieOptions
        {
            Expires = DateTimeOffset.UtcNow.AddDays(7),
            HttpOnly = true,
            IsEssential = true,
            Secure = true,
            SameSite = SameSiteMode.None
        });
}

Configure the callback to read the cookie:

services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
.AddJwtBearer(options =>
{
    .....
    options.Events = new JwtBearerEvents
    {
        OnMessageReceived = ctx =>
        {
            ctx.Request.Cookies.TryGetValue("accessToken", out var accessToken);
            if (!string.IsNullOrEmpty(accessToken))
                ctx.Token = accessToken;
            return Task.CompletedTask;
        }
    };
});

For more details,you may read this article

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744103088a4558617.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信