Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.4 kB
2
Indexable
Never
//builder.Services.AddAuthentication(options =>
//{
//    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
//    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
//}).AddJwtBearer(options =>
//{
//    options.TokenValidationParameters = new TokenValidationParameters
//    {
//        ValidateIssuerSigningKey = true,
//        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Secret"])),
//        ValidateIssuer = true,
//        ValidateAudience = true,
//        ValidIssuer = jwtSettings["Issuer"],
//        ValidAudience = jwtSettings["Audience"],
//        ValidateLifetime = true,
//        ClockSkew = TimeSpan.Zero
//    };

//    options.Events = new JwtBearerEvents
//    {
//        OnMessageReceived = context =>
//        {
//            // Check if the token is in the HttpOnly cookie
//            var token = context.Request.Cookies["token"];
//            if (!string.IsNullOrEmpty(token))
//            {
//                context.Token = token;
//            }
//            return Task.CompletedTask;
//        },
//        OnAuthenticationFailed = context =>
//        {
//            context.NoResult();
//            context.Response.StatusCode = 401;
//            context.Response.ContentType = "application/json";
//            return context.Response.WriteAsync(JsonSerializer.Serialize(new { status = 401, message = "Token is expired or invalid." }));
//        },
//        OnChallenge = context =>
//        {
//            context.HandleResponse();
//            if (!context.Response.HasStarted)
//            {
//                context.Response.StatusCode = 401;
//                context.Response.ContentType = "application/json";
//                var result = JsonSerializer.Serialize(new { status = 401, message = context.ErrorDescription ?? "You are not authorized." });
//                return context.Response.WriteAsync(result);
//            }
//            return Task.CompletedTask;
//        },
//        OnForbidden = context =>
//        {
//            context.Response.StatusCode = 403;
//            context.Response.ContentType = "application/json";
//            return context.Response.WriteAsync(JsonSerializer.Serialize(new { status = 403, message = "You are not authorized to access this resource." }));
//        }
//    };
//});
Leave a Comment