Home > Software design >  How can I receive cookie in layout page in asp.net core razorpage?
How can I receive cookie in layout page in asp.net core razorpage?

Time:06-24

I create login page in the asp.net core RazorPage and the code below is: Login page:

 List<Claim> claims = new List<Claim>()
            {
                new Claim("Test","Test"),
                new Claim(ClaimTypes.NameIdentifier as string,user.UserID.ToString()  as string),
                new Claim(ClaimTypes.Name,user.UserName),
                new Claim(ClaimTypes.Role as string,user.UserRole.ToString() as string)
            };

            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var claimPrincipal = new ClaimsPrincipal(identity);
            HttpContext.SignInAsync(claimPrincipal);
            return RedirectToPage("../Index");

and my _layout page is like this _Layout:

                if (???????????)
                    {
                        <div>@User.Identity.Name</div>
                        <ul >
                            <li >
                                <a  asp-page="/Auth/Logout">Logout</a>
                            </li>
                        </ul>
                    }
                    else
                    {
                        <ul >
                            <li >
                                <a  asp-page="/Auth/login">Login</a>
                            </li>
                            <li >
                                <a  asp-page="/Auth/Register">Register</a>
                            </li>
                        </ul>
                    }

the question is: What should I put instead of question marks?

CodePudding user response:

Determine whether the user has successfully logged in,

Try below code in _layout:

@if (User.Identity.IsAuthenticated)

In my startup.cs

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie();

result:

enter image description here

CodePudding user response:

this is my program.cs (i using .net core 6) and i am new to .net core

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using PageNamaProj.Context;
using PageNamaProj.Services.Users;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddHttpContextAccessor();

builder.Services.AddAuthorization(option =>
{
    option.AddPolicy("Account", builder =>
    {
        builder.RequireAuthenticatedUser();
    });
});

builder.Services.AddRazorPages()
    //.AddRazorRuntimeCompilation()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AuthorizeFolder("/Profile", "Account");
    });

builder.Services.AddScoped<IUserService, UserService>();


builder.Services.AddDbContext<TablesContext>(options =>
   options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));


builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(option =>
{
    option.LoginPath = "/Auth/Login";
    option.LogoutPath = "/Auth/Logout";
    option.ExpireTimeSpan = TimeSpan.FromDays(30);
});


builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<TablesContext>();


var app = builder.Build();

//Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.Use(async (context, next) =>
{
    var token = context.Request.Cookies["Token"]?.ToString();
    if (string.IsNullOrWhiteSpace(token) == false)
    {
        context.Request.Headers.Append("Authorization", $"Bearer {token}");
    }
    await next();
});


app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.Use(async (context, next) =>
{
    await next();
    var status = context.Response.StatusCode;
    if (status == 401)
    {
        var path = context.Request.Path;
        context.Response.Redirect($"/login?redirectTo={path}");
    }
});
app.UseAuthentication();

app.UseAuthorization();
app.MapRazorPages();
app.Run();
  • Related