示例#1
0
        public string GetTokenEndpoint(string tenantId)
        {
            if (!TokenEndpoint.Contains("/common/"))
            {
                throw new InvalidOperationException("Invalid token_endpoint: " + TokenEndpoint);
            }

            return(String.IsNullOrEmpty(tenantId) ? TokenEndpoint : TokenEndpoint.Replace("/common/", String.Format("/{0}/", tenantId)));
        }
        public async Task <AccessToken?> RequestTokenAsync(
            IConsoleOutput output,
            CancellationToken cancellationToken)
        {
            if (Token.HasValue())
            {
                return(new AccessToken(
                           Token.Value() !.Trim(),
                           Scheme.HasValue() ? Scheme.Value() !.Trim() : _defaultScheme));
            }

            if (TokenEndpoint.HasValue() || ClientId.HasValue() || ClientSecret.HasValue())
            {
                using IActivity activity = output.WriteActivity("Request token");
                ValidateOAuthArguments(activity);
                IEnumerable <string> scopes = Scopes.HasValue()
                    ? Enumerable.Empty <string>()
                    : Scopes.Values.Where(t => t is { }).OfType <string>();
示例#3
0
        public void Merge(OpenidEndpoints endpoints)
        {
            if (endpoints == null)
            {
                return;
            }

            if (Issuer.IsEmpty())
            {
                Issuer = endpoints.Issuer;
            }
            if (JwksUri.IsEmpty())
            {
                JwksUri = endpoints.JwksUri;
            }
            if (AuthorizationEndpoint.IsEmpty())
            {
                AuthorizationEndpoint = endpoints.AuthorizationEndpoint;
            }
            if (TokenEndpoint.IsEmpty())
            {
                TokenEndpoint = endpoints.TokenEndpoint;
            }
            if (UserinfoEndpoint.IsEmpty())
            {
                UserinfoEndpoint = endpoints.UserinfoEndpoint;
            }
            if (EndSessionEndpoint.IsEmpty())
            {
                EndSessionEndpoint = endpoints.EndSessionEndpoint;
            }
            if (CheckSessionIframe.IsEmpty())
            {
                CheckSessionIframe = endpoints.CheckSessionIframe;
            }
            if (RevocationEndpoint.IsEmpty())
            {
                RevocationEndpoint = endpoints.RevocationEndpoint;
            }
        }
 public string GetTokenEndpoint(string tenantId)
 {
     // ADFS URLs may not contain /common/. Replace /common/ with tenantID only if /common/ is present.
     return(String.IsNullOrEmpty(tenantId) ? TokenEndpoint : TokenEndpoint.Replace("/common/", String.Format("/{0}/", tenantId)));
 }
示例#5
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="principal">The principal</param>
        /// <param name="properties">The properties</param>
        /// <param name="context">The context</param>
        /// <param name="scheme">The authentication scheme, ie. OneId</param>
        /// <param name="options">The options</param>
        /// <param name="backchannel">The backchannel</param>
        /// <param name="tokens">The tokens</param>
        /// <param name="user">The user data from the id token</param>
        public OneIdAuthenticatedContext(ClaimsPrincipal principal, AuthenticationProperties properties, HttpContext context, AuthenticationScheme scheme, OAuthOptions options, HttpClient backchannel, OAuthTokenResponse tokens, JsonElement user) : base(principal, properties, context, scheme, options, backchannel, tokens, user)
        {
            if (options is null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (tokens is null)
            {
                throw new ArgumentNullException(nameof(tokens));
            }

            Context    = context;
            Principal  = principal;
            Properties = properties;

            _response = user.ToObject <TokenEndpoint>();

            if (options.SaveTokens)
            {
                var authTokens = new List <AuthenticationToken>();

                if ((((OneIdAuthenticationOptions)options).TokenSaveOptions & OneIdAuthenticationTokenSave.AccessToken) == OneIdAuthenticationTokenSave.AccessToken && !string.IsNullOrEmpty(tokens.AccessToken))
                {
                    authTokens.Add(new AuthenticationToken()
                    {
                        Name = "access_token", Value = tokens.AccessToken
                    });
                }
                ;

                if ((((OneIdAuthenticationOptions)options).TokenSaveOptions & OneIdAuthenticationTokenSave.RefreshToken) == OneIdAuthenticationTokenSave.RefreshToken && !string.IsNullOrEmpty(tokens.RefreshToken))
                {
                    authTokens.Add(new AuthenticationToken()
                    {
                        Name = "refresh_token", Value = tokens.RefreshToken
                    });
                }

                if (!string.IsNullOrEmpty(tokens.TokenType))
                {
                    authTokens.Add(new AuthenticationToken()
                    {
                        Name = "token_type", Value = tokens.TokenType
                    });
                }

                if (!string.IsNullOrEmpty(tokens.ExpiresIn))
                {
                    if (int.TryParse(tokens.ExpiresIn, NumberStyles.Integer, CultureInfo.InvariantCulture, out int value))
                    {
                        // https://www.w3.org/TR/xmlschema-2/#dateTime
                        // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
                        var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(value);

                        authTokens.Add(new AuthenticationToken()
                        {
                            Name  = "expires_at",
                            Value = expiresAt.ToString("o", CultureInfo.InvariantCulture),
                        });
                    }
                }

                Properties.StoreTokens(authTokens);
            }

            this.Email       = user.GetString("email");
            this.Id          = user.GetString("sub");
            this.GivenName   = user.GetString("given_name");
            this.FamilyName  = user.GetString("family_name");
            this.PhoneNumber = user.GetString("phoneNumber");
        }
        /// <summary>
        /// retrieve the access token
        /// </summary>
        /// <returns></returns>
        public string GetAccessToken(string code, string state)
        {
            int statusCode = 0;

            try
            {
                if (state != this.State)
                {
                    throw new SomeoneIdException(401, "Invalid state");
                }

                var accessTokenResult = new AccessTokenResult();
                var serializer        = new JavaScriptSerializer();

                string reqUri = (TokenEndpoint
                                 + "?client_id={client_id}"
                                 + "&redirect_uri={redirect_uri}"
                                 + "&cancel_url={cancel_url}"
                                 + "&client_secret={client_secret}"
                                 + "&code={code}")
                                .Replace("{client_id}", this.ClientId)
                                .Replace("{redirect_uri}", this.CallbackUri)
                                .Replace("{cancel_url}", this.CancelUrl)
                                .Replace("{client_secret}", this.ClientSecret)
                                .Replace("{code}", code);

                if (TokenEndpoint.StartsWith("https://"))
                {
                    //20171031 problems with https on someone site
                    //try https://stackoverflow.com/questions/28286086/default-securityprotocol-in-net-4-5
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                }

                HttpWebRequest wrLogon = (HttpWebRequest)WebRequest.Create(reqUri);
                wrLogon.AllowAutoRedirect = false;
                wrLogon.KeepAlive         = true;



                HttpWebResponse retreiveResponse = (HttpWebResponse)wrLogon.GetResponse();
                statusCode = (int)retreiveResponse.StatusCode;
                Stream       objStream = retreiveResponse.GetResponseStream();
                StreamReader objReader = new StreamReader(objStream);
                string       json      = objReader.ReadToEnd();
                retreiveResponse.Close();

                accessTokenResult = serializer.Deserialize <AccessTokenResult>(json);
                accessToken       = accessTokenResult.access_token;
                //SaveToken();
            }
            //catch (WebException wex)
            //{
            //    HttpWebResponse wrs = (HttpWebResponse)wex.Response;
            //    throw new SomeoneIdException((int)wrs.StatusCode, wex.ToString());
            //}
            catch (Exception ex)
            {
                throw new SomeoneIdException(statusCode, ex.ToString());
            }
            return(accessToken);
        }