【问题标题】:Access User.Identity and Claims from Outside从外部访问 User.Identity 和声明
【发布时间】:2018-11-17 21:06:00
【问题描述】:

我正在尝试使用 OpenID Connect 构建 SSO(.net core) 服务,该服务将成为 Webforms 应用程序和服务提供者之间的一层。我创建了一些端点来检查用户是否经过身份验证并从服务中获取用户声明。当我从浏览器调用这些端点时,我能够得到正确的结果。但是,当我从网站(使用 HttpWebRequest)调用它们时。 User.Identity 始终为空。我的端点检查用户是否通过身份验证,如下所示:

[HttpGet]
[Route("IsAuthenticated")]
public IActionResult IsAuthenticated()
{
    return Json(User.Identity.IsAuthenticated);
}

或者获取访问令牌:

[HttpGet]
[Route("access_token")]
public async Task<IActionResult> AccessToken()
{
    var tokenResult = await HttpContext.GetTokenAsync("access_token");
    return Json(tokenResult);
}

我的启动配置服务如下所示:

var OIDCConfiguration = new OIDCSettings()
{
    Authority = Configuration["OIDCSettings:Authority"],
    ClientId = Configuration["OIDCSettings:ClientId"],
    ClientSecret = Configuration["OIDCSettings:ClientSecret"],
    CallbackPath = Configuration["OIDCSettings:CallbackPath"],
    UserInfoEndpoint = Configuration["OIDCSettings:UserInfoEndpoint"]
};

services.AddAuthentication(options => {
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect("oidc", options => {
    options.Authority = OIDCConfiguration.Authority;
    options.ClientId = OIDCConfiguration.ClientId;
    options.ClientSecret = OIDCConfiguration.ClientSecret;
    options.CallbackPath = new PathString(OIDCConfiguration.CallbackPath);
    options.ResponseType = OpenIdConnectResponseType.Code;
    options.GetClaimsFromUserInfoEndpoint = true;
    options.Scope.Add("openid emailAddress");
    options.AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet;
    options.SaveTokens = true;
});

为了启动中间件,我正在使用 ChallengeResult 对象。

我是 OpenID Connect 和中间件架构的初学者,所以我不确定我缺少什么,或者我的架构是否正确。

【问题讨论】:

    标签: c# .net-core asp.net-identity access-token openid-connect


    【解决方案1】:

    因此,通常当您通过浏览器登录时,ASP.NET Core 会管理一个包含有关您的 ClaimsPrincipal 的所有相关信息的 cookie,以便服务器可以在对网站的后续请求中识别您。可能发生的情况是您的服务器未使用身份验证后管理的 cookie 发送请求,因此您的请求无法通过身份验证。

    【讨论】:

    • 是的,这就是问题所在。我更改了我的应用程序以遵循“授权代码流程”。这个流程看起来最适合 API 解决方案。
    猜你喜欢
    • 1970-01-01
    • 2019-01-06
    • 2016-02-19
    • 1970-01-01
    • 2021-10-06
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多