Difference beetween authentication with cookies and JWT

sblb 1,171 Reputation points
2023-10-23T20:24:32.3166667+00:00

Hi, I would like to know if you can give me the difference between authentication with cookies and JWT.

Also, I would like to know if I can make an authorisation of my application Independently of the authentication method use : cookies or JWT.

Program.cs in server project : cookie method

builder.Services.ConfigureApplicationCookie(options =>
{
    options.Cookie.HttpOnly = false;
    options.Events.OnRedirectToLogin = context =>
    {
        context.Response.StatusCode = 401;
        return Task.CompletedTask;
    };
});

Program.cs in server project : cookie method

//builder.Services.AddAuthentication(opt =>
//{
//    opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
//    opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
//}).AddJwtBearer(options =>
//{
 //   options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
   // {
   //     ValidateIssuer = true,
   //     ValidateAudience = true,
   //     ValidateLifetime = true,
    //    ValidateIssuerSigningKey = true,

    //    ValidIssuer = jwtSettings["validIssuer"],
    //    ValidAudience = jwtSettings["validAudience"],
   //     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings))
  //  };
//});

Thanks in advance to your reply

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,500 questions
0 comments No comments
{count} votes

6 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,731 Reputation points
    2023-10-24T18:03:34.8433333+00:00

    with cookie authentication the user identification is stored in a cookie. it is typically used with browsers as they support setting and sending cookies with requests. if the request requires authentication, (or expired cookie) typically requests redirect to a login page.

    with jwt authentication the user identification is passed via the authentication header as a bearer token. browsers do not support using bearer tokens. this method is handy for api's called by application code, because the code can call to get a jwt token to use in subsequent api calls. if the request requires authentication (or expired token), typically a 401 response is returned.

    so in general cookie authentication is used with browser requests, and jwttokens is used for api requests.

    note: if a browser page has javascript that does an ajax call, because the browser will include any cookies, often cookie authentication is used. care must be taken if the cookie expires because the response is typically login page html. You can add code to detect an ajax request and return 401 instead of the default redirect.

    1 person found this answer helpful.
    0 comments No comments

  2. Bianca Malan 0 Reputation points
    2023-10-23T20:43:24.66+00:00

    hi sblb

    I asked the same question and a little googling led me to an article that helped me answer the question.

    https://jerrynsh.com/all-to-know-about-auth-and-cookies/#:~:text=Neither%20JWT%20nor%20Cookie%20are,within%20your%20browser's%20Cookies%20storage.

    0 comments No comments

  3. AgaveJoe 1,495 Reputation points
    2023-10-23T22:54:56.52+00:00

    I would like to know if you can give me the difference between authentication with cookies and JWT.

    Cookies are commonly used in browser (user-agent) based applications. JWTs are used when the client is code like JavaScript or C#.

    Also, I would like to know if I can make an authorisation of my application Independently of the authentication method use : cookies or JWT.

    An application can have multiple authorization schemas as illustrated in the official documentation.

    Authorize with a specific scheme in ASP.NET Core

    0 comments No comments

  4. Ruikai Feng - MSFT 2,556 Reputation points Microsoft Vendor
    2023-10-24T03:26:25.0733333+00:00

    Hi,@sblb

    I would like to know if you can give me the difference between authentication with cookies and JWT.

    As mentioned in the document

    An authentication scheme's authenticate action is responsible for constructing the user's identity based on request context. It returns an AuthenticateResult indicating whether authentication was successful and, if so, the user's identity in an authentication ticket. See AuthenticateAsync. Authenticate examples include:

    A cookie authentication scheme constructing the user's identity from cookies.

    A JWT bearer scheme deserializing and validating a JWT bearer token to construct the user's identity.

    Also, I would like to know if I can make an authorisation of my application Independently of the authentication method use : cookies or JWT.

    You could follow the document above ,create your custom AuthenticationHandler and AutheticationSchemeOptions,consider where to restore user claims and how to read them in your custom handler

    public class MyAuthHandler : AuthenticationHandler<MyAuthenOptions>
        {
            public MyAuthHandler(IOptionsMonitor<MyAuthenOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
            {
            }
    
            protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
            {
                ........
                 return AuthenticateResult.Fail/Success/NoResult .....
            }
        }
    
        public class MyAuthenOptions: AuthenticationSchemeOptions
        {
    
        }
    
    
    

    Regist it in your Program.cs:

    builder.Services.AddAuthentication().AddScheme<MyAuthenOptions, MyAuthHandler>("MyScheme", options =>
    {
        ........
    });
    
    0 comments No comments

  5. sblb 1,171 Reputation points
    2023-10-25T10:21:16.22+00:00

    thank you all for your replies.

    In my side I define my user identification with cookie authentication.

    builder.Services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = false;
        options.Events.OnRedirectToLogin = context =>
        {
            context.Response.StatusCode = 401;
            return Task.CompletedTask;
        };
    });
    
    
    

    In my first post ask the question :

    Also, I would like to know if I can make an authorisation of my application Independently of the authentication method use : cookies or JWT?

    I would like to be able to set up an admi account and define the roles.