public async Task GetResourceCallback()

in Source/WebApp-Service-Provider-DotNet/Controllers/DataController.cs [87:154]


        public async Task<IActionResult> GetResourceCallback(string code, string state)
        {
            ConsentCookie consentCookie = null;
            string json;
            try
            {
                json = Base64Decode(Request.Cookies["consent"]);
                consentCookie = JsonSerializer.Deserialize<ConsentCookie>(json);
                Response.Cookies.Delete("consent");
            }
            catch (Exception)
            {
                throw new Exception("Unable to retrieve cookie");
            }

            if (string.IsNullOrEmpty(code))
            {
                throw new ArgumentNullException(code,"Authorization code cannot be null");
            }
            if (string.IsNullOrEmpty(state))
            {
                throw new ArgumentNullException(state,"State cannot be null");
            }
            if (state != consentCookie.State)
            {
                throw new ArgumentException("Invalid state", state);
            }

            var tokenClient = new HttpClient();
            var tokenResponse = await tokenClient.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest
            {
                Address = _config.TokenEndpoint,
                ClientId = _config.ClientId,
                ClientSecret = _config.ClientSecret,
                Method = HttpMethod.Post,
                Code = code,
                RedirectUri = GetConsentRedirectUri()
            });
            if (tokenResponse.IsError || string.IsNullOrEmpty(tokenResponse.AccessToken) || string.IsNullOrEmpty(tokenResponse.IdentityToken))
            {
                throw new Exception("Unable to retrieve access token");
            }

            JwtSecurityToken IdToken = Validation.ReadAndValidateToken(tokenResponse.IdentityToken, new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.ClientSecret)));

            if (IdToken == null)
            {
                throw new Exception("Invalid IdToken");
            }

            if (!Validation.IsEIdasLevelMet(IdToken.Payload.Acr, _config.EIdasLevel))
            {
                throw new Exception("EIdasLevel not met");
            }

            UserLoginInfo FCUserAccount = await GetUserFCAccount();
            if (FCUserAccount != null & FCUserAccount.ProviderKey != Hashing.HashString(IdToken.Payload.Sub))
            {
                throw new Exception("Unexpected sub");
            }

            consentCookie.State = null;
            consentCookie.Token = tokenResponse.AccessToken;
            json = JsonSerializer.Serialize(consentCookie);
            Response.Cookies.Append("consent", Base64Encode(json), new CookieOptions { Expires = DateTimeOffset.Now.AddMinutes(15) });

            return RedirectToAction(nameof(Resource));
        }