J
J
jyuart2020-08-08 13:30:43
Angular
jyuart, 2020-08-08 13:30:43

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;
}

2. Redirects him to GitHub (in this case), where he is authorized or not:
[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")
            });
        }

Code from Startup:
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();


Authentication works directly, but the question is the following. Now the user is redirected to the backend, where he receives some data about himself.
There is an implementation option when it returns to the main page of the frontend, but in this case, no data is transmitted.
I want to make sure that after the process is completed, the user is on the frontend, his access token is stored in localstorage, and he can edit the data before completing the registration (change the login or add something that github did not give away). How to implement it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question