B
B
Boris the Animal2020-06-14 16:01:23
ASP.NET
Boris the Animal, 2020-06-14 16:01:23

Blazor how to send all cookies along with every client request?

Used previously on React JS + axios client. When the browser received a response from the server, it automatically saved cookies, and every request to the server was already with these cookies. Now I'm trying to make authorization by JWT and I need to send cookies, since there is a JWT.

On the server, I just get it from the cookies and add it to the headers so that authentication works fine:

using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace GoToEs.Identity.Jwt.Middleware
{
    public class SecureJwtMiddleware
    {
        private readonly RequestDelegate _next;

        public SecureJwtMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            string token = context.Request.Cookies[".AspNetCore.Application.Id"];

            if (!string.IsNullOrEmpty(token))
            {
                context.Request.Headers.Add("Authorization", "Bearer " + token);
            }

            // https://securityheaders.com
            // Заголовок X-Content-Type-Options используется для защиты от уязвимостей типа MIME sniffing.
            context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
            context.Response.Headers.Add("X-Xss-Protection", "1");

            // X-Frame-Options сообщает браузеру, что если ваш сайт помещен внутри HTML-фрейма, то ничего не отображать.
            // Это очень важно при попытке защитить себя от попыток clickjacking-взлома.
            context.Response.Headers.Add("X-Frame-Options", "DENY");

            await _next(context);
        }
    }
}


This is necessary so that the client does not have access to the JWT through JavaScript, since this is a readonly cookie. There is a whole article about security, all this is done for security purposes, it takes a long time to paint.

On the client, I want to implement authentication verification in ApiAuthenticationStateProvider : AuthenticationStateProvider .

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question