user666
user666

Reputation: 332

The [Authorize] attribute can not work in asp.net core web?

I am using cookie authentication in the url:https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-5.0

I use HttpContext.SignInAsync for user successful and then I open other razor pages which has the [Authorize] attribute it redirected to the login path and tell me I have not loggin.

why?

the startup page:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

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

            app.UseRouting();

            app.UseAuthorization();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }

and the services:

services.AddRazorPages();

            services.AddDbContext<Models.DBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("dbContext")));

            services.AddScoped<Models.DBContext>();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.LoginPath = "/Manage/Login";
                    options.LogoutPath = "/Manage/Login";
                    options.ExpireTimeSpan = TimeSpan.FromMinutes(3600);
                });

Upvotes: 1

Views: 406

Answers (1)

Yinqiu
Yinqiu

Reputation: 7180

Change your code to:

 app.UseAuthentication();
 app.UseAuthorization();

Upvotes: 1

Related Questions