加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – ASP.Net核心MVC6未经授权时重定向到登录

发布时间:2020-12-15 23:36:49 所属栏目:百科 来源:网络整理
导读:我正在使用ASP.Net核心MVC 6,我试图让用户重定向到登录页面,如果他们没有经过身份验证. 我似乎无法让它工作,目前用户只是得到一个空白页面. 下面是我在Startup.cs中的ConfigureServices方法 public void ConfigureServices(IServiceCollection services) { /
我正在使用ASP.Net核心MVC 6,我试图让用户重定向到登录页面,如果他们没有经过身份验证.

我似乎无法让它工作,目前用户只是得到一个空白页面.

下面是我在Startup.cs中的ConfigureServices方法

public void ConfigureServices(IServiceCollection services) {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
        );

        services.AddIdentity<ApplicationUser,IdentityRole>(options => {
            // configure identity options
            options.Password.RequireDigit = true;
            options.Password.RequireLowercase = true;
            options.Password.RequireUppercase = true;
            options.Password.RequireNonAlphanumeric = true;
            options.Password.RequiredLength = 7;

            options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
            options.Cookies.ApplicationCookie.AutomaticChallenge = true;
            options.Cookies.ApplicationCookie.LoginPath = "/Account/Login";

            // User settings
            options.User.RequireUniqueEmail = true;
        })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();

        // Add application services.
        services.AddTransient<IEmailSender,AuthMessageSender>();
        services.AddTransient<ISmsSender,AuthMessageSender>();
    }

解决方法

我本人正在努力解决这个问题,我得出的结论是,最新版本的“Microsoft.AspNetCore.Identity.EntityFrameworkCore”依赖关系似乎存在问题.

我最初使用的是1.1.0版本,但经过大量调试,中间件日志记录等,我得出的结论是我没有做错任何事.我检查了:

>授权属性工作并阻止请求
>添加了事件处理程序(OnRedirectToLogin),如下所示,以验证重定向URL(这仅用于调试)

options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
{ 
    OnRedirectToLogin = evt => {
        evt.Response.Redirect(evt.RedirectUri); // this url is correct,but the redirect never happens!??
        return Task.FromResult(0);
    }
};

决议:
我将我的软件包回滚到版本1.0.1,然后重定向按预期启动 – 到LoginPath设置中的Startup.cs中定义的URL

options.Cookies.ApplicationCookie.LoginPath = new PathString("/Auth/Login");

为了澄清,这个版本有效:
Microsoft.AspNetCore.Identity.EntityFrameworkCore“:”1.0.1“

我将向ASPNETCORE团队提出一个关于1.1.0版本的调查问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读