【问题标题】:Protecting endpoints using Session cookie ASP.NET Core使用会话 cookie ASP.NET Core 保护端点
【发布时间】:2021-06-10 15:42:48
【问题描述】:

是否有通过会话 Cookie 保护端点的原生 ASP.NET Core 方法?我已通过关注the article on MSFT 成功地使用 Cosmos 后备存储实现了一个会话,但尚未弄清楚如何将其转化为保护我的端点。

Cookie authentication 似乎是要走的路,但我不知道如何完全正确。

我觉得通过使用:

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

我正在创建另一个 cookie,而不是重复使用 Session 中间件给我的那个。

最终,如果用户有会话并且它是有效的,我希望能够只允许调用特定的端点。谢谢!

【问题讨论】:

    标签: asp.net asp.net-core session


    【解决方案1】:

    我在最近的项目中通过ITicketStore(而不是AddSession)在 Cosmos DB 中实现了我自己的会话存储。您将CookieAuthenticationOptions 配置为通过您的自定义存储保留身份验证票证。这是要点,它允许使用 cookie 或 JWT,具体取决于请求来自浏览器还是 API 客户端。

    服务配置位:

    // Authenticate using shared cookie for browser clients, and JWT tokens for API clients
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, cookieOptions)
        .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtOptions);
    
    // Authorize with both cookies and JWT bearer tokens
    // Requires all controllers have attribute [Authorize(AuthenticationSchemes = "Bearer, Cookies")]
    services.AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder(
            CookieAuthenticationDefaults.AuthenticationScheme,
            JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser().Build();
    });
    
    // Persistent ticket/cookie store to provide durable user sessions
    services.AddSingleton<ITicketStore, MyCustomTicketStore>();
    services.AddOptions<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme)
        .Configure<ITicketStore>((options, store) => options.SessionStore = store);
    

    this presentation 中讨论了一些上下文。

    【讨论】:

      猜你喜欢
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      • 2021-12-09
      • 2019-02-04
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多