コード例 #1
0
 public GitHubAuthenticatedContext(HttpContext context, OAuthAuthenticationOptions options, JObject user, TokenResponse tokens)
     : base(context, options, user, tokens)
 {
     Login             = TryGetValue(user, "login");
     Id                = TryGetValue(user, "id");
     AvatarUrl         = TryGetValue(user, "avatar_url");
     GravatarId        = TryGetValue(user, "gravatar_id");
     Url               = TryGetValue(user, "url");
     HTMLUrl           = TryGetValue(user, "html_url");
     FollowersUrl      = TryGetValue(user, "followers_url");
     FollowingUrl      = TryGetValue(user, "following_url");
     GistsUrl          = TryGetValue(user, "gists_url");
     StarredUrl        = TryGetValue(user, "starred_url");
     SubscriptionUrl   = TryGetValue(user, "subscriptions_url");
     OrganizationsUrl  = TryGetValue(user, "organizations_url");
     ReposUrl          = TryGetValue(user, "repos_url");
     EventsUrl         = TryGetValue(user, "events_url");
     ReceivedEventsUrl = TryGetValue(user, "received_events_url");
     Type              = TryGetValue(user, "type");
     SiteAdmin         = bool.Parse(TryGetValue(user, "site_admin"));
     Name              = TryGetValue(user, "name");
     Company           = TryGetValue(user, "company");
     Blog              = TryGetValue(user, "blog");
     Location          = TryGetValue(user, "location");
     Email             = TryGetValue(user, "email");
     Hireable          = bool.Parse(TryGetValue(user, "hireable"));
     Bio               = TryGetValue(user, "bio");
     PublicRepos       = int.Parse(TryGetValue(user, "public_repos"));
     PublicGists       = int.Parse(TryGetValue(user, "public_gists"));
     Followers         = int.Parse(TryGetValue(user, "followers"));
     Following         = int.Parse(TryGetValue(user, "following"));
     CreatedAt         = DateTime.Parse(TryGetValue(user, "created_at"));
     UpdatedAt         = DateTime.Parse(TryGetValue(user, "updated_at"));
 }
コード例 #2
0
        /// <summary>
        /// Initializes a new <see cref="MicrosoftAccountAuthenticatedContext"/>.
        /// </summary>
        /// <param name="context">The HTTP environment.</param>
        /// <param name="user">The JSON-serialized user.</param>
        /// <param name="tokens">The access token provided by the Microsoft authentication service.</param>
        public MicrosoftAccountAuthenticatedContext(HttpContext context, OAuthAuthenticationOptions options, [NotNull] JObject user, TokenResponse tokens)
            : base(context, options, user, tokens)
        {
            IDictionary <string, JToken> userAsDictionary = user;

            JToken userId = User["id"];

            if (userId == null)
            {
                throw new ArgumentException(Resources.Exception_MissingId, "user");
            }

            Id        = userId.ToString();
            Name      = PropertyValueIfExists("name", userAsDictionary);
            FirstName = PropertyValueIfExists("first_name", userAsDictionary);
            LastName  = PropertyValueIfExists("last_name", userAsDictionary);

            if (userAsDictionary.ContainsKey("emails"))
            {
                JToken emailsNode = user["emails"];
                foreach (var childAsProperty in emailsNode.OfType <JProperty>().Where(childAsProperty => childAsProperty.Name == "preferred"))
                {
                    Email = childAsProperty.Value.ToString();
                }
            }
        }
コード例 #3
0
        public ConfigureSwaggerOptions(IOptions <OAuthAuthenticationOptions> oAuthAuthenticationOptionsAccessor)
        {
            if (oAuthAuthenticationOptionsAccessor.Value?.Authority == null)
            {
                throw new ApplicationException("The following service is missing; Add services.ConfigureOAuthAuthentication(...)");
            }

            _oAuthAuthenticationOptions = oAuthAuthenticationOptionsAccessor.Value;
        }
コード例 #4
0
 /// <summary>
 /// Initializes a new <see cref="FacebookAuthenticatedContext"/>.
 /// </summary>
 /// <param name="context">The HTTP environment.</param>
 /// <param name="user">The JSON-serialized user.</param>
 /// <param name="tokens">The Facebook Access token.</param>
 public FacebookAuthenticatedContext(HttpContext context, OAuthAuthenticationOptions options, JObject user, TokenResponse tokens)
     : base(context, options, user, tokens)
 {
     Id       = TryGetValue(user, "id");
     Name     = TryGetValue(user, "name");
     Link     = TryGetValue(user, "link");
     UserName = TryGetValue(user, "username");
     Email    = TryGetValue(user, "email");
 }
コード例 #5
0
 /// <summary>
 /// Initializes a new <see cref="GoogleAuthenticatedContext"/>.
 /// </summary>
 /// <param name="context">The HTTP environment.</param>
 /// <param name="user">The JSON-serialized Google user info.</param>
 /// <param name="tokens">Google OAuth 2.0 access token, refresh token, etc.</param>
 public GoogleAuthenticatedContext(HttpContext context, OAuthAuthenticationOptions options, JObject user, TokenResponse tokens)
     : base(context, options, user, tokens)
 {
     Id         = TryGetValue(user, "id");
     Name       = TryGetValue(user, "displayName");
     GivenName  = TryGetValue(user, "name", "givenName");
     FamilyName = TryGetValue(user, "name", "familyName");
     Profile    = TryGetValue(user, "url");
     Email      = TryGetFirstValue(user, "emails", "value");
 }
コード例 #6
0
        private static void AddOAuth2SecurityDefinition(this SwaggerGenOptions options,
                                                        OAuthAuthenticationOptions oauthAuthenticationOptions)
        {
            var scopes = new Dictionary <string, string>();

            if (!string.IsNullOrEmpty(oauthAuthenticationOptions.ApiName))
            {
                scopes.Add(oauthAuthenticationOptions.ApiName, "This is the main scope needed to access API");
            }

            if (oauthAuthenticationOptions.Scopes?.Any() == true)
            {
                foreach (var scope in oauthAuthenticationOptions.Scopes.Split(new[] { " " },
                                                                              StringSplitOptions.RemoveEmptyEntries))
                {
                    if (!scopes.ContainsKey(scope))
                    {
                        scopes.Add(scope, "This is a dependency scope needed to access API");
                    }
                }
            }

            options.AddSecurityDefinition(Constants.SecurityScheme, new OpenApiSecurityScheme
            {
                Type  = SecuritySchemeType.OAuth2,
                Flows = new OpenApiOAuthFlows
                {
                    AuthorizationCode = new OpenApiOAuthFlow
                    {
                        AuthorizationUrl =
                            new Uri(string.Concat(oauthAuthenticationOptions.Authority, "/connect/authorize"),
                                    UriKind.Absolute),
                        Scopes   = scopes,
                        TokenUrl = new Uri(string.Concat(oauthAuthenticationOptions.Authority, "/connect/token"),
                                           UriKind.Absolute)
                    }
                }
            });

            options.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id   = Constants.SecurityScheme
                        }
                    },
                    scopes.Select(x => x.Key).ToList()
                }
            });
        }
コード例 #7
0
        private static HttpMessageHandler ResolveHttpMessageHandler(OAuthAuthenticationOptions options)
        {
            HttpMessageHandler handler = options.BackchannelHttpHandler ??
#if DNX451
                                         new WebRequestHandler();

            // If they provided a validator, apply it or fail.
            if (options.BackchannelCertificateValidator != null)
            {
                // Set the cert validate callback
                var webRequestHandler = handler as WebRequestHandler;
                if (webRequestHandler == null)
                {
                    //throw new InvalidOperationException(Resources.Exception_ValidatorHandlerMismatch);
                    throw new InvalidOperationException("Resources.Exception_ValidatorHandlerMismatch");
                }
                webRequestHandler.ServerCertificateValidationCallback = options.BackchannelCertificateValidator.Validate;
            }
#else
                                         new WinHttpHandler();
#endif
            return(handler);
        }
コード例 #8
0
        /// <summary>
        /// Configures Identity Server Authentication using <see cref="OAuthAuthenticationOptions" />.
        /// </summary>
        /// <param name="builder">The <see cref="AuthenticationBuilder" />.</param>
        /// <param name="options">The <see cref="OAuthAuthenticationOptions" />.</param>
        /// <param name="schemeName">The scheme name.</param>
        /// <returns>The <see cref="AuthenticationBuilder" />.</returns>
        public static AuthenticationBuilder AddOAuthAuthentication([NotNull] this AuthenticationBuilder builder, [NotNull] OAuthAuthenticationOptions options, string schemeName)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (string.IsNullOrWhiteSpace(schemeName))
            {
                throw new ArgumentException($"'{nameof(schemeName)}' must not be null, empty or whitespace.", nameof(schemeName));
            }

            return(builder.AddIdentityServerAuthentication(schemeName, x =>
            {
                x.Authority = options.Authority;
                x.ApiName = options.ApiName;
                x.ApiSecret = options.ApiSecret;
                x.SupportedTokens =
                    Enum.TryParse(options.SupportedTokens, out SupportedTokens supportedToken)
                        ? supportedToken
                        : SupportedTokens.Both;
                x.RequireHttpsMetadata = options.RequireHttpsMetadata;
                x.LegacyAudienceValidation = options.LegacyAudienceValidation;
                x.JwtValidationClockSkew = TimeSpan.Zero;
            }));
        }
コード例 #9
0
 public RunkeeperAuthenticatedContext(HttpContext context, OAuthAuthenticationOptions options, JObject user, TokenResponse tokens)
     : base(context, options, user, tokens)
 {
 }
コード例 #10
0
 internal static void IncludeOAuthAuthentication(this SwaggerGenOptions options,
                                                 OAuthAuthenticationOptions oAuthAuthenticationOptions)
 {
     options.AddOAuth2SecurityDefinition(oAuthAuthenticationOptions);
 }
コード例 #11
0
        /// <summary>
        /// Adds OAuth Authentication.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection" />.</param>
        /// <param name="options">The <see cref="OAuthAuthenticationOptions" />.</param>
        /// <param name="schemeName">The scheme name.</param>
        /// <returns>The <see cref="IServiceCollection" />.</returns>
        public static IServiceCollection AddOAuthAuthentication([NotNull] this IServiceCollection services, [NotNull] OAuthAuthenticationOptions options, string schemeName)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (string.IsNullOrWhiteSpace(schemeName))
            {
                throw new ArgumentException($"'{nameof(schemeName)}' must not be null, empty or whitespace.", nameof(schemeName));
            }

            services
            .AddAuthentication(x =>
            {
                x.DefaultScheme          = schemeName;
                x.DefaultChallengeScheme = schemeName;
            })
            .AddOAuthAuthentication(options, schemeName);

            return(services);
        }