コード例 #1
0
ファイル: Startup.Auth.cs プロジェクト: alex-kukhtin/A2v10
        private static void ConfigureApi(IAppBuilder app)
        {
            var apiAuth = ConfigurationManager.AppSettings["apiAuthentication"];

            if (apiAuth == null)
            {
                return;
            }
            var apiAuthKeys = apiAuth.Split(',');

            if (apiAuthKeys.Any(x => x.Equals("APIKEY", StringComparison.InvariantCultureIgnoreCase)))
            {
                var opts = new ApiKeyAuthenticationOptions()
                {
                    UnauthorizedCode = 403
                };
                app.UseApiKeyAuthentication(opts);
            }
            if (apiAuthKeys.Any(x => x.Equals("BASIC", StringComparison.InvariantCultureIgnoreCase)))
            {
                var opts = new ApiBasicAuthenticationOptions()
                {
                    UnauthorizedCode = 403
                };
                app.UseApiBasicAuthentication(opts);
            }
        }
コード例 #2
0
        public static IAppBuilder UseApiKeyAuthentication(this IAppBuilder self, ApiKeyAuthenticationOptions options)
        {
            if (self == null)
            {
                throw new ArgumentNullException(nameof(self));
            }

            self.Use(typeof(ApiKeyAuthenticationMiddleware), self, options);
            self.UseStageMarker(PipelineStage.Authenticate);
            return self;
        }
コード例 #3
0
        public static IAppBuilder UseApiKeyAuthentication(this IAppBuilder self, ApiKeyAuthenticationOptions options)
        {
            if (self == null)
            {
                throw new ArgumentNullException("self");
            }

            self.Use(typeof(ApiKeyAuthenticationMiddleware), self, options);
            self.UseStageMarker(PipelineStage.Authenticate);
            return(self);
        }
コード例 #4
0
        public void AuthenticationTypeProperty_VersionPropertyIsPresent_ReturnPass()
        {
            // Arrange
            var apiKeyAuthenticationOptions = new ApiKeyAuthenticationOptions();
            // Act
            var scheme = apiKeyAuthenticationOptions.AuthenticationType;

            // Assert
            Assert.NotEmpty(scheme);
            Assert.NotNull(scheme);
            Assert.IsType <string>(scheme);
            Assert.Equal("APIKey", scheme);
        }
コード例 #5
0
ファイル: Startup.Auth.cs プロジェクト: Ualikhandulat/A2v10
        public static void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext <AppUserManager>(AppUserManager.Create);
            app.CreatePerOwinContext <AppSignInManager>(AppSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider

            var authProvider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <AppUserManager, AppUser, Int64>
                                     (
                    validateInterval: TimeSpan.FromMinutes(30),
                    getUserIdCallback: (user) =>
                {
                    return(user.GetUserId <Int64>());
                },
                    regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager)
                                     ),
                OnResponseSignedIn = (context) =>
                {
                }
            };

            //var originalHandler = authProvider.OnApplyRedirect;

            authProvider.OnApplyRedirect = (context) =>
            {
                if (context.Request.SkipAuthRedirect())
                {
                    return;
                }
                var    refer     = context.Request.Query["ref"];
                var    loginPath = context.Options.LoginPath;
                String qs        = $"{context.Options.ReturnUrlParameter}={HttpUtility.UrlEncode(context.Request.Path.Value)}";
                if (refer != null)
                {
                    qs += $"&ref={HttpUtility.UrlEncode(refer)}";
                }
                String url = loginPath.Add(new QueryString(qs));
                context.Response.Redirect(url);
            };

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/account/login"),
                ReturnUrlParameter = "returnurl",
                Provider           = authProvider,
                CookieName         = GetApplicationCookieName(),
            });


            //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            //AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; //

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            //app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            app.UseCacheForStaticFiles();

            String GetApplicationCookieName()
            {
                var key = ConfigurationManager.AppSettings["AppKey"];

                return($"{key}.ASP.NET.ApplicationCookie");
            }

            if (ConfigurationManager.GetSection("oauth2") is Oauth2Section oauth2Config)
            {
                var expTimeSpan = oauth2Config.expireTimeSpan;
                if (expTimeSpan.TotalMilliseconds == 0)
                {
                    expTimeSpan = TimeSpan.FromMinutes(20);
                }

                app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions()
                {
                    Provider                  = new OAuth2Provider(),
                    TokenEndpointPath         = new PathString(oauth2Config.tokenEndpoint),
                    AllowInsecureHttp         = oauth2Config.allowInsecureHttp,
                    AccessTokenExpireTimeSpan = expTimeSpan
                });
            }

            var apiAuth = ConfigurationManager.AppSettings["apiAuthentication"];

            if (apiAuth != null)
            {
                var apiAuthKeys = apiAuth.Split(',');
                if (apiAuthKeys.Any(x => x.Equals("APIKEY", StringComparison.InvariantCultureIgnoreCase)))
                {
                    var opts = new ApiKeyAuthenticationOptions()
                    {
                        UnauthorizedCode = 403
                    };
                    app.UseApiKeyAuthentication(opts);
                }
                if (apiAuthKeys.Any(x => x.Equals("BASIC", StringComparison.InvariantCultureIgnoreCase)))
                {
                    var opts = new ApiBasicAuthenticationOptions()
                    {
                        UnauthorizedCode = 403
                    };
                    app.UseApiBasicAuthentication(opts);
                }
            }
        }
コード例 #6
0
 internal ApiKeyValidateIdentityContext(IOwinContext context, ApiKeyAuthenticationOptions options, string apiKey)
     : base(context, options, apiKey)
 {
 }
コード例 #7
0
 internal ApiKeyGenerateClaimsContext(IOwinContext context, ApiKeyAuthenticationOptions options, string apiKey)
     : base(context, options, apiKey)
 {
 }
コード例 #8
0
        public static IApplicationBuilder UseApiKeyAuthentication(this IApplicationBuilder app, ApiKeyAuthenticationOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return(app.UseMiddleware <ApiKeyAuthenticationMiddleware>(Options.Create(options)));
        }