【问题标题】:Oauth cookie authentication with cross domain in ASP.NET Core APIASP.NET Core API 中跨域的 Oauth cookie 身份验证
【发布时间】:2020-02-05 20:31:47
【问题描述】:

我在 ASP.NET Core API 项目中使用了 OAuth cookie 身份验证。本项目所有 API 均已授权。成功登录后,可从浏览器 URL 栏访问所有 API。当我尝试从其他域访问 AJAX 请求中的 API 时,总是会返回 Unauthorized

这里如何从AJAX请求中识别用户是否经过身份验证?

API domain = ".apidomain.com"
Client domain = ".clientdomain.com"

API 配置:

services.AddAuthentication("oAuthSecurityScheme")
                .AddOAuth("login.microsoftonline.com",
                options =>
                {
                   ....
                   ....
                }).AddCookie(
                "oAuthSecurityScheme",
                options =>
                {
                options.LogoutPath = new PathString("/logout");
                options.LoginPath = new PathString("/api/v1/account/authorize");
                options.ExpireTimeSpan = new TimeSpan(7, 0, 0, 0);
                options.SlidingExpiration = true;
                options.Cookie.Name = "CustomerOAuthCookie";
                options.Events.OnRedirectToLogin = UnAuthorizedResponseAsync;
                options.Cookie.SameSite = SameSiteMode.None;
                options.Cookie.HttpOnly = false;
            });

客户端应用程序:

$.ajax({
       url: "https://localhost:44332/api/gettickets/1",
       type: 'GET',
       success: function (result)
       {
          alert(result);
          console.log(result);
       }
});

注意:当我直接在浏览器中访问下面的 API 时,它会返回正确的响应 https://localhost:44332/api/gettickets/1

【问题讨论】:

标签: api authentication cookies .net-core cross-domain


【解决方案1】:

我通常更喜欢使用令牌来发送和保存授权数据并向您建议。 但如果您仍想使用 cookie,请按照以下链接方式:

jquery ajax call not sending cookie

【讨论】:

    猜你喜欢
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 2018-08-11
    • 2019-02-25
    • 2018-02-24
    • 1970-01-01
    • 2016-12-22
    相关资源
    最近更新 更多