Answer the question
In order to leave comments, you need to log in
How to return data and access token to the frontend after OAuth2 authentication from the backend?
I have an application that consists of SPA (Angular 10) and ASP.NET Core Web API 3.1. I'm trying to implement authentication using OAuth2 (GitHub for starters).
1. The user clicks on the button and gets a redirect to the backend:
login() {
const returnUrl = 'returnUrl=' + this.document.location.origin;
this.document.location.href = 'http://localhost:5050/auth/ExternalLogin?' + '&' + returnUrl;
}
[HttpGet]
public IActionResult ExternalLogin(string provider)
{
var callbackUrl = Url.Action("ExternalLoginCallback");
var authenticationProperties = new AuthenticationProperties { RedirectUri = callbackUrl };
return this.Challenge(authenticationProperties, provider);
}
[HttpGet]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return this.Ok(new
{
NameIdentifier = result.Principal.FindFirstValue(ClaimTypes.NameIdentifier),
Email = result.Principal.FindFirstValue(ClaimTypes.Email),
Login = result.Principal.FindFirstValue("urn:github:login")
});
}
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = "GitHub";
})
.AddOAuth("GitHub", options =>
{
options.ClientId = Configuration["GitHub:ClientId"];
options.ClientSecret = Configuration["GitHub:ClientSecret"];
options.CallbackPath = new PathString("/github-oauth");
options.AuthorizationEndpoint = "https://github.com/login/oauth/authorize";
options.TokenEndpoint = "https://github.com/login/oauth/access_token";
options.UserInformationEndpoint = "https://api.github.com/user";
options.SaveTokens = true;
options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
options.ClaimActions.MapJsonKey("urn:github:login", "login");
options.Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
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 json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
context.RunClaimActions(json.RootElement);
}
};
})
.AddCookie();
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question