Owin 托管了几种不同类型的端点,带有身份验证

时间:2021-06-24 19:09:17

标签: c# .net-core owin

这超出了我的舒适区,所以我可能忽略了一些明显的事情并犯了一个简单的错误,或者几个......希望有人能指出我正确的方向

我正在尝试使用 .NET Core 在同一个项目中托管 MVC 页面、Web API 和 SignalR,避免使用实体框架、第 3 方组件等。

我真正想要的只是以某种方式使用 MVC 部分中的 [Authorize] 标签,并让它在未经授权的情况下将用户转发到登录页面。

WebAPI 部分的 JWT 身份验证似乎有效,我只是不确定如何更改我必须重定向到网页登录页面的内容,并自己处理数据库端(可能会抛出一些声明)什么的)

我读过无数的例子,这些例子似乎朝着我不想进入的方向发展,或者过于复杂。如果我能做一些非常简单的事情,我觉得我可以从那里开始。

我也对 app.UsesAuthentication 之类的东西如何影响具有多个端点的项目感到困惑。它们可以以某种方式单独配置吗?

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();                 //Is it necessary? authentication change

        services.AddControllersWithViews(); //MVC
        services.AddControllers();          //Web API - seems to work without this?
        services.AddSignalR();              //Signal R

        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));   //authentication change

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = "Cookies";
        }).AddCookie("cookieAuth", config =>
        {
            config.Cookie.Name = "default";
            config.LoginPath = "/login/authenticate";
        });

/* 这给了我 InvalidOperationException: No authenticationScheme is specified,也没有找到 DefaultChallengeScheme。可以使用 AddAuthentication(string defaultScheme) 或 AddAuthentication(Action configureOptions) 设置默认方案。 */

        services.AddScoped<IUserService, UserService>();                            //authentication change
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseStaticFiles();               //Needed to serve scripts from wwwroot

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

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

        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()); //authentication change

        app.UseMiddleware<JwtMiddleware>();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();             //Web API 
            endpoints.MapHub<ChatHub>("/chathub");  //SignalR
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}",
                defaults: new { controller = "Home", action = "Index" }); //MVC
        });
    }

0 个答案:

没有答案