Exemple #1
0
        public async Task RefreshTokensAsync()
        {
            var refreshToken = await context.GetTokenAsync(OpenIdConnectParameterNames.RefreshToken);

            if (string.IsNullOrEmpty(refreshToken))
            {
                throw new ArgumentNullException(nameof(refreshToken));
            }

            // This is what [Authorize] calls
            var userResult = await context.AuthenticateAsync();

            var user  = userResult.Principal;
            var props = userResult.Properties;

            var options = optionsMonitor.Get(props.Items[".AuthScheme"]);

            var now = DateTimeOffset.Now;

            var scope     = string.Join(" ", options.Scope);
            var timestamp = now.ToString("yyyy.MM.dd HH:mm:ss") + " " + now.ToString("zzz").Replace(":", "");
            var clientId  = options.ClientId;
            var state     = Guid.NewGuid().ToString();

            var clientSecret = EsiaExtensions.SignData(esiaSigner, esiaOptions, scope, timestamp, clientId, state);

            var pairs = new Dictionary <string, string>()
            {
                { "client_id", options.ClientId },
                { "client_secret", clientSecret },
                { "scope", scope },
                { "timestamp", timestamp },
                { "state", state },
                { "grant_type", "refresh_token" },
                { "refresh_token", refreshToken }
            };
            var content       = new FormUrlEncodedContent(pairs);
            var tokenResponse = await options.Backchannel.PostAsync(options.Configuration.TokenEndpoint, content, context.RequestAborted);

            tokenResponse.EnsureSuccessStatusCode();

            var payload = JObject.Parse(await tokenResponse.Content.ReadAsStringAsync());

            var stateReceived = payload.Value <string>("state");

            if (state != stateReceived)
            {
                throw new ArgumentException(nameof(state));
            }

            props.UpdateTokenValue("access_token", payload.Value <string>("access_token"));
            props.UpdateTokenValue("refresh_token", payload.Value <string>("refresh_token"));
            if (int.TryParse(payload.Value <string>("expires_in"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var seconds))
            {
                var expiresAt = DateTimeOffset.UtcNow + TimeSpan.FromSeconds(seconds);
                props.UpdateTokenValue("expires_at", expiresAt.ToString("o", CultureInfo.InvariantCulture));
            }
            await context.SignInAsync(user, props);
        }
Exemple #2
0
        /// <summary>
        /// Событие перенаправления к поставщику данных.
        /// </summary>
        public override Task RedirectToIdentityProvider(RedirectContext context)
        {
            // prepare data
            var now = DateTimeOffset.Now;
            var pm  = context.ProtocolMessage;

            // add additional fields for redirect
            pm.ResponseType = OpenIdConnectResponseType.Code;
            pm.Parameters.Add("access_type", "offline");
            pm.Parameters.Add("timestamp", now.ToString("yyyy.MM.dd HH:mm:ss") + " " + now.ToString("zzz").Replace(":", ""));
            pm.State = Guid.NewGuid().ToString();

            // get data for sign
            var scope     = pm.Parameters["scope"];
            var timestamp = pm.Parameters["timestamp"];
            var clientId  = pm.ClientId;
            var state     = pm.State;

            // set clientSecret
            pm.ClientSecret = EsiaExtensions.SignData(EsiaSigner, EsiaOptions, scope, timestamp, clientId, state);

            return(AddAdditionalParametersForReceivingAccessCode(pm.Parameters));
        }
Exemple #3
0
        /// <summary>
        /// Событие получения маркера доступа и(или) маркера идентификации.
        /// </summary>
        public override Task AuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            // prepare data
            var now = DateTimeOffset.Now;
            var pm  = context.TokenEndpointRequest;

            // add additional fields for redirect
            pm.ClientId = context.Options.ClientId;
            pm.Parameters.Add("scope", string.Join(" ", (context.Properties as OpenIdConnectChallengeProperties)?.Scope ?? context.Options.Scope));
            pm.Parameters.Add("timestamp", now.ToString("yyyy.MM.dd HH:mm:ss") + " " + now.ToString("zzz").Replace(":", ""));
            pm.State = Guid.NewGuid().ToString();

            // get data for sign
            var scope     = pm.Parameters["scope"];
            var timestamp = pm.Parameters["timestamp"];
            var clientId  = pm.ClientId;
            var state     = pm.State;

            // set clientSecret
            pm.ClientSecret = EsiaExtensions.SignData(EsiaSigner, EsiaOptions, scope, timestamp, clientId, state);

            // ok
            return(Task.CompletedTask);
        }