【发布时间】:2019-08-19 07:45:51
【问题描述】:
我正在努力使用 OAuth 和 JWT 实现自定义身份验证流程。 基本上应该是这样的:
- 用户点击登录
- 用户被重定向到第 3 方 OAuth 登录页面
- 用户登录页面
- 我得到 access_token 并请求用户信息
- 我获取了用户信息并创建了我自己的 JWT 令牌来来回发送
我一直在关注 this great tutorial 如何构建 OAuth 身份验证,唯一不同的是 Jerrie 使用的是 Cookies。
到目前为止我做了什么:
配置了AuthenticationService
services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = "3rdPartyOAuth";
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie() // Added only because of the DefaultSignInScheme
.AddJwtBearer(options =>
{
options.TokenValidationParameters = // Ommited for brevity
})
.AddOAuth("3rdPartyOAuth", options =>
{
options.ClientId = securityConfig.ClientId;
options.ClientSecret = securityConfig.ClientSecret;
options.CallbackPath = new PathString("/auth/oauthCallback");
options.AuthorizationEndpoint = securityConfig.AuthorizationEndpoint;
options.TokenEndpoint = securityConfig.TokenEndpoint;
options.UserInformationEndpoint = securityConfig.UserInfoEndpoint;
// Only this for testing for now
options.ClaimActions.MapJsonKey("sub", "sub");
options.Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
// Request for user information
var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
response.EnsureSuccessStatusCode();
var user = JObject.Parse(await response.Content.ReadAsStringAsync());
context.RunClaimActions(user);
}
};
});
授权控制器
[AllowAnonymous]
[HttpGet("login")]
public IActionResult LoginIam(string returnUrl = "/auth/loginCallback")
{
return Challenge(new AuthenticationProperties() {RedirectUri = returnUrl});
}
[AllowAnonymous]
[DisableRequestSizeLimit]
[HttpGet("loginCallback")]
public IActionResult IamCallback()
{
// Here is where I expect to get the user info, create my JWT and send it back to the client
return Ok();
}
免责声明:现在正在合并此 OAuth 流程。我有一个创建和使用我自己的 JWT 工作和一切的流程。我不会在这里发帖,因为我的问题在此之前。
我想要什么
在 Jerrie 的帖子中,您可以看到他设置了 DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;。这样,当达到/auth/loginCallback 时,我在HttpContext 中有用户声明。
问题是我的DefaultAuthenticateScheme 设置为JwtBearersDefault,当调用loginCallback 时,我看不到用户在Request 中无处声称。
在这种情况下,我如何才能访问在我的回调中通过OnCreatingTicketEvent 获得的信息?
额外问题:我对 OAuth 了解不多(现在肯定很清楚)。您可能已经注意到我的options.CallbackPath 与Challenge 在login 端点处传递的RedirectUri 不同。我预计 option.CallbackPath 会被第 3 部分 OAuth 提供程序调用,但这不是发生的事情(显然)。我确实必须将CallbackPath 设置为我在 OAuth 提供程序配置中设置的相同值(如使用 GitHub 的 Jerries 教程)才能正常工作。那正确吗?回调仅用于匹配配置?我什至可以评论 CallbackPath 指向的端点,它仍然以相同的方式工作......
谢谢!
【问题讨论】:
标签: c# authentication oauth oauth-2.0 .net-core