我正在努力用 OAuth 和 JWT 实现自定义身份验证流。基本上, 它应该如下所示:
我一直在遵循这个伟大的教程如何建立 oauth 身份验证, 唯一不同的部分是, jerrie 正在使用 Cookies
。
到目前为止, 我所做的:
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 工作和一切的流程。我不会在这里发帖, 因为我的问题是在那之前。
在杰瑞的帖子中, 你可以看到他设置 DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
。有了它, 当 /auth/loginCallback
达到我有用户声明中 HttpContext
。问题是我 DefaultAuthenticateScheme
设置为 JwtBearersDefault
, 当 loginCallback
调用时, 我看不到用户声称在 Request
任何地方。OnCreatingTicketEvent
在此方案中, 如何访问在回调中获得的信息?
更改 [AllowAnonymous]
到 [Authorize]
'loginCallback'
在端点上 ( AuthController.IamCallback
方法)