Esempio n. 1
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            var code  = Request.Query.Get("code");
            var state = Request.Query.Get("state");

            if (code == null || state == null)
            {
                return(null);
            }

            var properties = Options.StateDataFormat.Unprotect(state);

            if (properties == null)
            {
                return(null);
            }

            var nonce = await _nonceCache.GetNonceAsync(Context.Authentication);

            if (nonce == null)
            {
                return(null);
            }

            var tokenResponse = await _tokenClient.RequestAuthorizationCodeAsync(Options.TokenEndpoint, Options.ClientId, Options.ClientSecret, code, Request.Uri);

            if (tokenResponse.IsError)
            {
                throw new OidcAuthenticationException(tokenResponse.Error);
            }

            _tokenValidator.ValidateToken(Options, tokenResponse.IdentityToken, nonce);

            var identity = new ClaimsIdentity("Cookies");

            identity.AddClaim(new Claim("id_token", tokenResponse.IdentityToken));

            if (!string.IsNullOrWhiteSpace(tokenResponse.AccessToken))
            {
                identity.AddClaims(await _userInfoClient.GetUserClaims(Options, tokenResponse.AccessToken));
                identity.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
                identity.AddClaim(new Claim("expires_at", (DateTime.UtcNow.ToEpochTime() + tokenResponse.ExpiresIn).ToDateTimeFromEpoch().ToString()));
            }

            if (!string.IsNullOrWhiteSpace(tokenResponse.RefreshToken))
            {
                identity.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
            }

            Options.AuthenticatedCallback?.Invoke(identity);

            return(new AuthenticationTicket(identity, properties));
        }