Example #1
0
        public void Configuration(IAppBuilder app)
        {
            app.UseResourceAuthorization(new AuthorizationManager());

            var clientId  = (string)ConfigurationManager.AppSettings["oauth2.clientid"];
            var authority = (string)ConfigurationManager.AppSettings["oauth2.authority"];

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions {
                Authority      = authority,
                RequiredScopes = new[] { clientId },
            });

            app.UseResourceAuthorization(new AuthorizationManager());
        }
Example #2
0
        public void Configuration(IAppBuilder app)
        {
            app.UseResourceAuthorization(new AuthorizationManager());

            var clientId = (string)ConfigurationManager.AppSettings["oauth2.clientid"];
            var authority = (string)ConfigurationManager.AppSettings["oauth2.authority"];

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions {
                Authority = authority,
                RequiredScopes = new[] { clientId },
            });

            app.UseResourceAuthorization(new AuthorizationManager());
        }
Example #3
0
        public void Configuration(IAppBuilder app)
        {
            app.Map("/identity", idsrvApp => idsrvApp.UseIdentityServer(new IdentityServerOptions
            {
                SiteName = "Embedded IdentityServer",
                IssuerUri = "https://idsrv3/embedded",
                SigningCertificate = LoadCertificate(),

                Factory = InMemoryFactory.Create(
                    users: Users.Get(),
                    clients: Clients.Get(),
                    scopes: Scopes.Get())
            }));

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = "https://localhost:44304/identity",

                ClientId = "mvc",
                Scope = "openid profile roles",
                RedirectUri = "https://localhost:44304/",

                SignInAsAuthenticationType = "Cookies"
            });

            app.UseResourceAuthorization(new AuthorizationManager());
        }
Example #4
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = "https://localhost:44333/core",
                RequiredScopes = new[] { "api" },
                NameClaimType  = "name",
                RoleClaimType  = "role",

                // client credentials for the introspection endpoint
                ClientId     = "angularMaterial",
                ClientSecret = Guid.NewGuid().ToString()
            });

            var configuration = new HttpConfiguration();

            configuration.MapHttpAttributeRoutes();

            var jsonFormatter = configuration.Formatters.OfType <JsonMediaTypeFormatter>().FirstOrDefault();

            if (jsonFormatter != null)
            {
                jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            }

            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseWebApi(configuration);

            app.UseNancy();
            app.UseStageMarker(PipelineStage.MapHandler);
        }
        /// <summary>
        /// Configurations the application.
        /// </summary>
        /// <param name="app">The application.</param>
        public void Configuration(IAppBuilder app)
        {
            var logger = LogManager.GetCurrentClassLogger();

            logger.Debug("Started  Config.Configuration");

            IocConfig.UseIoc();

            app.UseIdentityClientConfig();
            app.UseResourceAuthorization();

            app.UseHttpConfig();

            // Generic Home Page
            app.UseWelcomePage("/");

            // Non-Generic Home Page
            //app.UseFileServer(new FileServerOptions
            //{
            //    FileSystem = new PhysicalFileSystem(_development ? "../../content" : "content"),
            //    RequestPath = new PathString("")
            //});

            //app.UseWelcomePage("/content");

            app.UseMetrics();

            // Uncomment after you create the database
            //app.UseOwinHangfire();
        }
Example #6
0
        public void Configuration(IAppBuilder app)
        {
            app.Map(
                "/identity",
                idsrvApp => idsrvApp.UseIdentityServer(
                    new IdentityServerOptions
            {
                SiteName           = "Embedded IdentityServer",
                SigningCertificate = this.LoadCertificate(),
                RequireSsl         = false,
                Factory            = InMemoryFactory.Create(
                    users: Users.Get(),
                    clients: Clients.Get(),
                    scopes: Scopes.Get().Union(StandardScopes.All))
            }));

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority    = "http://localhost:59087/identity",
                ClientId     = "mvc",
                RedirectUri  = "http://localhost:59087/",
                ResponseType = "id_token token",
                SignInAsAuthenticationType = "Cookies",
                Scope = "openid profile roles"
            });
            LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider());
            app.UseResourceAuthorization(new AppResourceAuthorizationManager(new AuthorizationPolicies(Policies.Get())));
        }
Example #7
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = "implicitclient-cardeal",
                Authority = Constants.BaseAddress,
                RedirectUri = "http://localhost:57870/",
                ResponseType = "id_token token",
                Scope = "openid email write",
                SignInAsAuthenticationType = "Cookies",

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = SecurityTokenValidated
                }
            });

            app.UseResourceAuthorization(new AuthorizationManager());

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
Example #8
0
        public void Configuration(IAppBuilder app)
        {
            app.Map("/identity", idsrvApp => idsrvApp.UseIdentityServer(new IdentityServerOptions
            {
                SiteName           = "Embedded IdentityServer",
                IssuerUri          = "https://idsrv3/embedded",
                SigningCertificate = LoadCertificate(),

                Factory = InMemoryFactory.Create(
                    users: Users.Get(),
                    clients: Clients.Get(),
                    scopes: Scopes.Get())
            }));

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = "https://localhost:44304/identity",

                ClientId    = "mvc",
                Scope       = "openid profile roles",
                RedirectUri = "https://localhost:44304/",

                SignInAsAuthenticationType = "Cookies"
            });

            app.UseResourceAuthorization(new AuthorizationManager());
        }
Example #9
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId     = "implicitclient-cardeal",
                Authority    = Constants.BaseAddress,
                RedirectUri  = "http://localhost:57870/",
                ResponseType = "id_token token",
                Scope        = "openid email write",
                SignInAsAuthenticationType = "Cookies",

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = SecurityTokenValidated
                }
            });

            app.UseResourceAuthorization(new AuthorizationManager());

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
Example #10
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44333/core",
                RequiredScopes = new[] { "api" },
                NameClaimType = "name",
                RoleClaimType = "role",

                // client credentials for the introspection endpoint
                ClientId = "angularMaterial",
                ClientSecret = Guid.NewGuid().ToString()
            });

            var configuration = new HttpConfiguration();
            configuration.MapHttpAttributeRoutes();

            var jsonFormatter = configuration.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();

            if (jsonFormatter != null)
            {
                jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            }

            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseWebApi(configuration);

            app.UseNancy();
            app.UseStageMarker(PipelineStage.MapHandler);
        }
        public void Configuration(IAppBuilder app)
        {
            //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies",
                //CookieDomain="",//for sso
                //CookieHttpOnly=true // for seceret to make js can not get cookie
            });
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                //Authority = "http://localhost:8003",//for user auth server
                Authority                  = "http://localhost:8008", //for ef auth server
                ClientId                   = "c-03",
                RequireHttpsMetadata       = false,                   //if not use https
                ClientSecret               = "B25F4BF7-8702-4593-BBAA-AD7005C8D4E9",
                RedirectUri                = "http://localhost:8004/",
                ResponseType               = "id_token token",
                SignInAsAuthenticationType = "Cookies",

                Scope = "openid profile api2",//get these authrize token
                //UseTokenLifetime = true,

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    //after Validated,setup cookie
                    SecurityTokenValidated = async n =>
                    {
                        //create userclaim at webclient side
                        //var cookieUser = new ClaimsIdentity(authenticationType: n.AuthenticationTicket.Identity.AuthenticationType,nameType: "role",roleType: "role");
                        var cookieUser = new ClaimsIdentity(authenticationType: n.AuthenticationTicket.Identity.AuthenticationType);
                        //get userinfo from auth server
                        var userInfoUri    = new Uri(n.Options.Authority + "/connect/userinfo");
                        var userInfoClient = new UserInfoClient(userInfoUri, n.ProtocolMessage.AccessToken);
                        var userInfo       = await userInfoClient.GetAsync();
                        //assign userinfo which from auth server to cookieuser
                        userInfo.Claims.ToList().ForEach(ui => cookieUser.AddClaim(new Claim(ui.Item1, ui.Item2)));
                        cookieUser.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        cookieUser.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));
                        //cookieUser.AddClaim(new Claim("refresh_token", n.ProtocolMessage.RefreshToken));
                        n.AuthenticationTicket = new Microsoft.Owin.Security.AuthenticationTicket(cookieUser, n.AuthenticationTicket.Properties);
                    },
                    //logout
                    RedirectToIdentityProvider = r =>
                    {
                        if (r.ProtocolMessage.RequestType == Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectRequestType.Logout)
                        {
                            var idTokenHint = r.OwinContext.Authentication.User.FindFirst("id_token");
                            if (idTokenHint != null)
                            {
                                r.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }
                        return(Task.FromResult(0));
                    }
                },
            });
            app.UseResourceAuthorization(new AuthorizationManager());
        }
Example #12
0
        public static IAppBuilder UseResourceAuthorization(this IAppBuilder app, IResourceAuthorizationManager authorizationManager)
        {
            var options = new ResourceAuthorizationMiddlewareOptions
            {
                Manager = authorizationManager
            };

            app.UseResourceAuthorization(options);
            return(app);
        }
Example #13
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            //ResponseType is "id_token" based on "ImplicitFlow" defined in "Clients"
            //IF ResponseType is "code id_token" than Flow in Clients is "HybridFlow"
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority    = "https://localhost:44386/identity",
                ClientId     = "mvc",
                Scope        = "openid profile roles",
                RedirectUri  = "http://localhost:50381/",
                ResponseType = "id_token",
                SignInAsAuthenticationType = "Cookies",
                UseTokenLifetime           = false
                                             //Notifications = new OpenIdConnectAuthenticationNotifications
                                             //{
                                             //    SecurityTokenValidated = n =>
                                             //    {
                                             //        var id = n.AuthenticationTicket.Identity;

                                             //        // we want to keep first name, last name, subject and roles
                                             //        var givenName = id.FindFirst(Constants.ClaimTypes.GivenName);
                                             //        var familyName = id.FindFirst(Constants.ClaimTypes.FamilyName);
                                             //        var sub = id.FindFirst(Constants.ClaimTypes.Subject);
                                             //        var roles = id.FindAll(Constants.ClaimTypes.Role);

                                             //        // create new identity and set name and role claim type
                                             //        var nid = new ClaimsIdentity(
                                             //            id.AuthenticationType,
                                             //            Constants.ClaimTypes.GivenName,
                                             //            Constants.ClaimTypes.Role);

                                             //        nid.AddClaim(givenName);
                                             //        nid.AddClaim(familyName);
                                             //        nid.AddClaim(sub);
                                             //        nid.AddClaims(roles);

                                             //        // add some other app specific claim
                                             //        nid.AddClaim(new Claim("app_specific", "some data"));

                                             //        n.AuthenticationTicket = new AuthenticationTicket(
                                             //            nid,
                                             //            n.AuthenticationTicket.Properties);

                                             //        return Task.FromResult(0);
                                             //    }
                                             //}
            });

            app.UseResourceAuthorization(new AuthorizationManager());
        }
Example #14
0
        public void ConfigureAuth(IAppBuilder app)
        {
            Logger _log = LogManager.GetCurrentClassLogger();

            _log.Info("ConfigureAuth");
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            });


            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority             = Properties.Settings.Default.Authority,
                ClientId              = Properties.Settings.Default.ClientId,
                Scope                 = "openid profile roles",
                RedirectUri           = Properties.Settings.Default.RedirectUri,
                ResponseType          = "id_token",
                PostLogoutRedirectUri = Properties.Settings.Default.PostLogoutRedirectUri,

                SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,


                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    //This is to attach the id_token as a claim so that the logout can access the claim once the IdentityServer has logged the user out of the user service.
                    SecurityTokenValidated = n =>
                    {
                        var id = n.AuthenticationTicket.Identity;

                        id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        n.AuthenticationTicket = new AuthenticationTicket(id, n.AuthenticationTicket.Properties);
                        return(Task.FromResult(0));
                    },

                    //This uses the id_token claim set above to access the redirect uri
                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");
                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }
                        return(Task.FromResult(0));
                    },
                }
            });

            //This tells the app what class will be looking after Authorization (access to resources, NOT Authentication which is validating the user)
            app.UseResourceAuthorization(new AuthorisationManager());
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
        }
        public void Configuration(IAppBuilder app)
        {
            var cookie = new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookie",
                ExpireTimeSpan = TimeSpan.FromMinutes(20),
                LoginPath = new PathString("/Login"),
            };
            app.UseCookieAuthentication(cookie);

            app.UseResourceAuthorization(new ChinookAuthorization());
        }
Example #16
0
        public void Configuration(IAppBuilder app)
        {
            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = ExpenseTrackerConstants.IdSrvBase,
                RequiredScopes = new[] { "expensetrackerapi" }

            });

            app.UseWebApi(WebApiConfig.Register());
        }
        public void Configuration(IAppBuilder app)
        {
            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseIdentityServerBearerTokenAuthentication(new
                                                           IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = ExpenseTrackerConstants.IdSrv,
                RequiredScopes = new[] { "expensetrackerapi" }
            });

            app.UseWebApi(WebApiConfig.Register());
        }
Example #18
0
        public void Configuration(IAppBuilder app)
        {
            var cookie = new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookie",
                ExpireTimeSpan     = TimeSpan.FromMinutes(20),
                LoginPath          = new PathString("/Login"),
            };

            app.UseCookieAuthentication(cookie);

            app.UseResourceAuthorization(new ChinookAuthorization());
        }
Example #19
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44333/core",
                RequiredScopes = new[] { "webapi" }
            });

            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseWebApi(WebApiConfig.Register());
        }
Example #20
0
    public void Configuration(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            // TODO : these login/logout path should be set only for ASP.Net MVC view
            //LoginPath = new PathString("/sph/sphaccount/login"),
            //LogoutPath = new PathString("/sph/sphaccount/logoff"),
            //ReturnUrlParameter = "returnUrl",
            AuthenticationType = ConfigurationManager.ApplicationName + "Cookie",
            CookieHttpOnly     = true,
            ExpireTimeSpan     = TimeSpan.FromMinutes(30),
            SlidingExpiration  = true,
            CookieName         = $".{ConfigurationManager.ApplicationName}.Cookie"
        });

        //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        //app.UseGoogleAuthentication("112970609059-m6aibunjgp870t2nfd4de64uk6rhid3j.apps.googleusercontent.com", "rp51TYacrgleJjKNbuRimyQ6");

        app.RegisterCustomEntityDependencies()
        .UseCoreResource(true)
        .MapSignalRConnection();


        var config = new HttpConfiguration();

        config.MessageHandlers.Add(new MethodOverrideHandler());

        config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
        var setting = new JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            TypeNameHandling      = TypeNameHandling.None
        };

        setting.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
        setting.Formatting = Formatting.Indented;

        config.Formatters.JsonFormatter.SerializerSettings = setting;
        config.MapHttpAttributeRoutes();

        config.Filters.Add(new ResourceAuthorizeAttribute());
        config.Services.Replace(typeof(IExceptionHandler), ObjectBuilder.GetObject <IExceptionHandler>());
        config.EnsureInitialized();

        app.UseResourceAuthorization(new CustomPolicyAuthorizationManager());

        app.UseJwt()
        .UseApiMetering()
        .UseWebApi(config);
    }
Example #21
0
        /// <summary>
        /// Configurations the specified application.
        /// </summary>
        /// <param name="app">The application.</param>
        public void Configuration(IAppBuilder app)
        {
            // Set up IOC Container
            IocConfig.UseIoc();

            // Set MVC to use the same Identity settings as Owin
            app.UseIdentityClientConfig();
            app.UseResourceAuthorization();

            // FUN Stuff
            app.UseMetrics();

            // Uncomment After Database is created
            //app.UseOwinHangfire();
        }
Example #22
0
        public void Configuration(IAppBuilder app)
        {
            app.UseResourceAuthorization(new AuthorizationManager());

            ResetClaimsMapPreveningDotNetClaimsUsage();

            app.UseIdentityServerBearerTokenAuthentication(
                new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = ConfigurationManager.AppSettings["identityServerUrl"],
                RequiredScopes = new[] { "securedapi" }
            });

            app.UseWebApi(WebApiConfig.Register());
        }
        public void Configuration(IAppBuilder app)
        {
            app.UseResourceAuthorization(new AuthorizationManager());

            //Ensure that id server only accepts access_token created on this server
            app.UseIdentityServerBearerTokenAuthentication(
                new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = ExpenseTrackerConstants.IdSrv, //Only trust access token created in this url
                RequiredScopes = new[] { "expensetrackerapi" } //This is the resource scope defined in the scopes.cs file
            });


            app.UseWebApi(WebApiConfig.Register());
        }
Example #24
0
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            WebApiConfig.Register(config);

            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseIdentityServerBearerTokenAuthentication(
                new IdentityServerBearerTokenAuthenticationOptions {
                Authority      = ChatterApiConstants.IdSrv,
                RequiredScopes = new [] { "chatterapi" }
            });


            app.UseWebApi(config);
        }
Example #25
0
        public void Configuration(IAppBuilder app)
        {
            app
            .UseResourceAuthorization(new ApiAuthorizationManager())
            .UseIdentityServerBearerTokenAuthentication(
                new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44375/identity",
                //AuthenticationType = "Bearer",
                //AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                //ValidationMode = ValidationMode.Local,
                RequiredScopes = new[] { "openid", "profile", "solution-template-api" }
            });

            app
            .UseNinjectMiddleware(CreateKernel)
            .UseNinjectWebApi(WebApiConfig.Register());
        }
Example #26
0
        public void Configuration(IAppBuilder app)
        {
            // authorization manager
            ClaimsAuthorization.CustomAuthorizationManager = new AuthorizationManager();

            // no mapping of incoming claims to Microsoft types
            JwtSecurityTokenHandler.InboundClaimTypeMap = ClaimMappings.None;

            // validate JWT tokens from AuthorizationServer
            app.UseJsonWebToken(
                issuer: "AS",
                audience: "todoApi",
                signingKey: "1fTiS2clmPTUlNcpwYzd5i4AEFJ2DEsd8TcUsllmaKQ=");

            app.UseResourceAuthorization(new TodoAuthorization());

            app.UseWebApi(WebApiConfig.Configure());
        }
Example #27
0
        public void Configuration(IAppBuilder app)
        {
            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseIdentityServerBearerTokenAuthentication(new
                                                           IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = Constants.Constants.BaseAddress,
                RequiredScopes = new[] { "medicoApi" }
            });

            var config = new HttpConfiguration();

            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
            WebApiConfig.Register(config);
            app.UseNinjectMiddleware(() => NinjectConfig.CreateKernel.Value);
            app.UseNinjectWebApi(config);
        }
Example #28
0
        private void ConfigureAuth(IAppBuilder app)
        {
            app.UseResourceAuthorization(new AuthorizationManager());


            JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

            // 忽略服务器证书错误
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((sender, certificate, chain, errors) => true);

            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = AppSetting.GetString("IdentityServerUrl"),
                RequiredScopes = new[] { "openid", "roles", "profile" },
                TokenProvider  = new OAuthBearerAuthenticationProvider
                {
                    OnValidateIdentity = OnValidateIdentityHandle
                },
            });
        }
Example #29
0
        internal static void ConfigureResourceServer(IAppBuilder app)
        {
            var issuer   = ConfigurationManager.AppSettings[Constants.AppSettings.AUTH_SERVER_TOKEN_ISSUER];
            var audience = "683DD6FEC91749DAA00B103BA026215C";

            var secret = Microsoft.Owin.Security.DataHandler.Encoder.TextEncodings.Base64Url.Decode("PKJHc8JIsdDICF+kzdfTui3BYaHyiFY10oxH1JVEsDQ=");

            var options = new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audience },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                },
                Provider = new OAuthBearerAuthenticationProvider()
            };

            app.UseJwtBearerAuthentication(options);
            app.UseResourceAuthorization(new Gestion.Security.Authorization.GestionResourceAuthorizationManager());
        }
Example #30
0
        public void Configuration(IAppBuilder appBuilder)
        {
            // Handle X-Forwarded-* headers.
            appBuilder.Use(typeof(ApplyProxyHeadersMiddleware));

            // Map static web site, which doesn't need any authorization.
            ConfigureStaticFiles(appBuilder);

            // Configure authorization.
            appBuilder.SetDataProtectionProvider(dataProtectionProvider);
            appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            ConfigureOAuth(appBuilder);
            appBuilder.UseResourceAuthorization(resourceAuth);

            // Map SignalR.
            GlobalHost.DependencyResolver.Register(typeof(Guncho.Api.Hubs.PlayHub), () => sigrResolver.GetService(typeof(Guncho.Api.Hubs.PlayHub)));
            appBuilder.MapSignalR();

            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();

            config.DependencyResolver = webResolver;
            config.Filters.Add(new System.Web.Http.AuthorizeAttribute());
            config.MessageHandlers.Add(new HeadHandler());

            // Configure JSON formatting.
            ConfigureJson(config);

            // Configure routing.
            config.MapHttpAttributeRoutes();

            // Configure tracing.
            //config.EnableSystemDiagnosticsTracing();
            //appBuilder.SetLoggerFactory(new DiagnosticsLoggerFactory());

            // Map Web API.
            config.EnsureInitialized();
            appBuilder.UseWebApi(config);
        }
Example #31
0
        public void ConfigureAuth(IAppBuilder app)
        {
            // anti CRFS
            AntiForgeryConfig.UniqueClaimTypeIdentifier = "sub";

            // if prop name is in red - it is just VS messing with you
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions()
            {
                ClientId    = "implicitclient",
                Authority   = "https://localhost:44333/identity",
                RedirectUri = "http://localhost:2671/",
                // id - OIDC token, token - for oauth to webapi
                ResponseType = "id_token token",
                // openid - auth token, email - claim, roles -all claim fo role assignement
                Scope = "openid email roles webApiBack",
                SignInAsAuthenticationType = "Cookies",

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    // to store only needed claims in cookie
                    SecurityTokenValidated = async data => await ExtractNameAndRoleFromValidatedTokenAsync(data),

                    // for logout purposes, when we are sending the logout req
                    // we need to pass our id token to prove we are not spammer
                    RedirectToIdentityProvider = async data => RedirectToIdentityProvider(data)
                }
            });

            app.UseResourceAuthorization(new CustomResourceAuthManager());
        }
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                LoginPath = new PathString("/Home/Login"),
                SlidingExpiration = true,
                CookieHttpOnly = true,  // already defaults to true
                CookieSecure = CookieSecureOption.SameAsRequest,
                Provider = new CookieAuthenticationProvider
                {
                    OnApplyRedirect = ctx =>
                    {
                        if (!ctx.Request.IsAjaxRequest())
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                    }
                }
            });

            app.UseResourceAuthorization(new CustomAuthorizationManager());
            ConfigureWebApi(app);
        }
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext <IBookStroreService>(() =>
                                                          new BookStroreService());

            //1,validate token: IdentityServer3.AccessTokenValidation
            //get validation from the auth server,and set User.Identity.IsAuthenticated = true or false
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServer3.AccessTokenValidation.IdentityServerBearerTokenAuthenticationOptions()
            {
                //Authority = "Http://localhost:8002",//for client auth server
                Authority      = "Http://localhost:8003",// for user auth server
                RequiredScopes = new System.Collections.Generic.List <string> {
                    "api1"
                },
                ValidationMode = IdentityServer3.AccessTokenValidation.ValidationMode.ValidationEndpoint
            });

            //2,validate resource/action: access Thinktecture.IdentityModel.Owin.ResourceAuthorization.WebApi
            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseCors(CorsOptions.AllowAll);
            app.UseWebApi(GetHttpConfig());
        }
Example #34
0
        public void Configuration(IAppBuilder app)
        {
            /*
             *  Project -> No Template / WebApi ref
             *  install-package Microsoft.Owin.Host.SystemWeb
             *  install-package Microsoft.AspNet.WebApi.Owin
             *  install-package IdentityServer3.AccessTokenValidation
             */
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = IdentityServerSetting.BASE_IDENTITY_SERVER_URL,
                RequiredScopes = new[] { "siteApi" }
            });

            app.UseResourceAuthorization(new AuthorizationManager());

            // web api configuration
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            app.UseWebApi(config);
        }
Example #35
0
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            app.SetupFilters(config);
            app.SetupRoutes(config);
            app.SetupDependencies(config);

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions()
            {
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
                AllowInsecureHttp         = true,
                Provider          = new SimpleAuthorizationServerProvider(),
                TokenEndpointPath = new PathString("/api/token")
            });

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
            {
            });

            app.UseResourceAuthorization(new AppAuthorization());

            app.UseWebApi(config);
        }
Example #36
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            app.UseCookieAuthentication(new CookieAuthenticationOptions {
                AuthenticationType = "Cookies"
            });

            app.UseResourceAuthorization(new AuthorizationManager());

            var clientId    = (string)ConfigurationManager.AppSettings["oauth2.clientid"];
            var authority   = (string)ConfigurationManager.AppSettings["oauth2.authority"];
            var redirectUri = (string)ConfigurationManager.AppSettings["oauth2.redirect"];

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {
                Authority    = authority,
                ClientId     = clientId,
                RedirectUri  = redirectUri,
                ResponseType = "id_token token",
                Scope        = "openid roles demo-website",

                SignInAsAuthenticationType = "Cookies",
            });
        }
Example #37
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.UseCookieAuthentication(new CookieAuthenticationOptions {
                AuthenticationType = "Cookies"
            });

            app.UseResourceAuthorization(new AuthorizationManager());

            var clientId = (string)ConfigurationManager.AppSettings["oauth2.clientid"];
            var authority = (string)ConfigurationManager.AppSettings["oauth2.authority"];
            var redirectUri = (string)ConfigurationManager.AppSettings["oauth2.redirect"];

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {
                Authority = authority,
                ClientId = clientId,
                RedirectUri = redirectUri,
                ResponseType = "id_token token",
                Scope = "openid roles demo-website",

                SignInAsAuthenticationType = "Cookies",
            });
        }
Example #38
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            //JWT

            AntiForgeryConfig.UniqueClaimTypeIdentifier = JwtRegisteredClaimNames.Sub;// Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            var issuer   = "http://authorization.onyximports.com.br";
            var audience = "ngAuthApp";
            var secret   = TextEncodings.Base64Url.Decode("IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw");

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
            {
                AuthenticationMode           = AuthenticationMode.Active,
                AllowedAudiences             = new[] { audience },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                }
            });


            //JWT



            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.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
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = 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 <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // 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));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);


            app.UseResourceAuthorization(new AuthorizationManager());

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Example #39
0
        public void Configuration(IAppBuilder app)
        {
            //This line prevent claim type to be mapped to dotnet's claim types, it resets the mapping dictionary,
            //ensure that no mapping occurs.
            //Second benefit is that the claim's names are much more readable.
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            //Use this claim instead of identifier or identity provider claim
            AntiForgeryConfig.UniqueClaimTypeIdentifier = "unique_user_key";

            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });


            //Open connect middleware with supports hybrid flow:
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = "mvc", //this name is defined in id srv: ExpenseTracker.IdSrv.Config.Clients class
                Authority = ExpenseTrackerConstants.IdSrv,
                RedirectUri = ExpenseTrackerConstants.ExpenseTrackerClient,
                SignInAsAuthenticationType = "Cookies",

                //Possibility to  define 3 types of responses:
                //code for authorization code
                //token for access token
                //id_token for an identity
                
                
                //There are 3 types of response types:
                // code: for authorization code
                // token: for an access token and to get userInfo
                // id_token: for identity token

                ResponseType = "code id_token token", // this depends on the flow you are using (implit vs authorization code flow)
                //the type above is configured for hybrid flow:
                //- we are working with identity so we require an id_token
                //- we also require the authorization code so that the flow can successfully complete

                //Example: authorization code flow requires authoriation code
                //If the client does not call the correct response type, the flow would not be able to successfully complete

                //Configure resource scopes:
                //Type of id scope are like a collections of claims
                //Profile matches to profile related claims such as given_name, family_name, picture, gender, etc...

                //Other scopes:
                // - address: country, postal code, etc... 
                // - ...
                //Check openid tech spec to get a full list of scope types

                Scope = "openid profile roles expensetrackerapi offline_access",
                //openid scope is a requirement for openid support
                //roles scope to request roles from id server
                //expensetrackerapi to allow access to the api

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    MessageReceived = async n =>
                    {
                        EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.IdToken);
                        
                        //When 'token' is set in reponse type, the access token will contain the profile and openid scope
                        EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.AccessToken);
                        //this allows us to access the user endpoint and retrieve the profile values
                        //given_name and family_name values will be available in userInfo
                        var userInfo = await EndpointAndTokenHelper
                            .CallUserInfoEndpoint(n.ProtocolMessage.AccessToken);

                        //Best practise:
                        //Put very basic information in the id_token,
                        //but return extended information through a seperate call to the userinfo endpoint.
                    },

                    //Using claims transformation
                    SecurityTokenValidated = async n =>
                    {
                        //Debug access token use: EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.AccessToken)

                        var userInfo = await EndpointAndTokenHelper.CallUserInfoEndpoint(n.ProtocolMessage.AccessToken);

                        var givenNameClaim = new Claim(
                            Thinktecture.IdentityModel.Client.JwtClaimTypes.GivenName,
                            userInfo.Value<string>("given_name"));

                        var familyNameClaim = new Claim(
                            Thinktecture.IdentityModel.Client.JwtClaimTypes.FamilyName,
                            userInfo.Value<string>("family_name"));

                        var roles = userInfo.Value<JArray>("role").ToList();

                        var newIdentity = new ClaimsIdentity(
                           n.AuthenticationTicket.Identity.AuthenticationType,
                           Thinktecture.IdentityModel.Client.JwtClaimTypes.GivenName,
                           Thinktecture.IdentityModel.Client.JwtClaimTypes.Role);

                        newIdentity.AddClaim(givenNameClaim);
                        newIdentity.AddClaim(familyNameClaim);

                        foreach (var role in roles) //Add the roles to the claims:
                        {
                            newIdentity.AddClaim(new Claim(
                                Thinktecture.IdentityModel.Client.JwtClaimTypes.Role,
                                role.ToString()));
                        }

                        var issuerClaim = n.AuthenticationTicket.Identity
                            .FindFirst(Thinktecture.IdentityModel.Client.JwtClaimTypes.Issuer);
                        var subjectClaim = n.AuthenticationTicket.Identity
                            .FindFirst(Thinktecture.IdentityModel.Client.JwtClaimTypes.Subject);

                        newIdentity.AddClaim(new Claim("unique_user_key", //this claim is used as AntiForgery token
                            issuerClaim.Value + "_" + subjectClaim.Value)); //userId is composed of issuer and subject



                        //This is used for client credentials flow (server to server):
                        //var oAuth2Client = new OAuth2Client(
                        // new Uri(ExpenseTrackerConstants.IdSrvToken),
                        // "mvc_api",
                        // "secret");

                        //var response = oAuth2Client.RequestClientCredentialsAsync("expensetrackerapi").Result;
                        //EndpointAndTokenHelper.DecodeAndWrite(response.AccessToken)



                        //Add access token to list of cliams, next pass this access token to api on each call
                        //so that resource scope can fulfill requests. To do this add it to the bearer token
                        //in the http client headers.
                        //newIdentity.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken)); // this token is replaced by the refresh tokens below:


                        // use the authorization code to get a refresh token 
                        var tokenEndpointClient = new OAuth2Client(
                            new Uri(ExpenseTrackerConstants.IdSrvToken),
                            "mvc", "secret");

                        var tokenResponse = await tokenEndpointClient.RequestAuthorizationCodeAsync(
                            n.ProtocolMessage.Code, ExpenseTrackerConstants.ExpenseTrackerClient);

                        newIdentity.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
                        newIdentity.AddClaim(new Claim("access_token", tokenResponse.AccessToken));
                        newIdentity.AddClaim(new Claim("expires_at",
                            DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString()));



                        n.AuthenticationTicket = new AuthenticationTicket(
                            newIdentity,
                            n.AuthenticationTicket.Properties);
                    },
                }
            });

        }
        public void Configuration(IAppBuilder app)
        {
            // todo: replace with serilog
            //LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider());

            AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.Map("/identity", idsrvApp =>
                {
                    idsrvApp.UseIdentityServer(new IdentityServerOptions
                    {
                        SiteName = "Embedded IdentityServer",
                        SigningCertificate = LoadCertificate(),

                        Factory = new IdentityServerServiceFactory()
                                    .UseInMemoryUsers(Users.Get())
                                    .UseInMemoryClients(Clients.Get())
                                    .UseInMemoryScopes(Scopes.Get()),

                        AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions
                        {
                            IdentityProviders = ConfigureIdentityProviders
                        }
                    });
                });

            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = "Cookies"
                });


            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
                {
                    Authority = "https://localhost:44319/identity",

                    ClientId = "mvc",
                    Scope = "openid profile roles sampleApi",
                    ResponseType = "id_token token",
                    RedirectUri = "https://localhost:44319/",

                    SignInAsAuthenticationType = "Cookies",
                    UseTokenLifetime = false,

                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        SecurityTokenValidated = async n =>
                            {
                                var nid = new ClaimsIdentity(
                                    n.AuthenticationTicket.Identity.AuthenticationType,
                                    Constants.ClaimTypes.GivenName,
                                    Constants.ClaimTypes.Role);

                                // get userinfo data
                                var userInfoClient = new UserInfoClient(
                                    new Uri(n.Options.Authority + "/connect/userinfo"),
                                    n.ProtocolMessage.AccessToken);

                                var userInfo = await userInfoClient.GetAsync();
                                userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2)));

                                // keep the id_token for logout
                                nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                                // add access token for sample API
                                nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));

                                // keep track of access token expiration
                                nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

                                // add some other app specific claim
                                nid.AddClaim(new Claim("app_specific", "some data"));

                                n.AuthenticationTicket = new AuthenticationTicket(
                                    nid,
                                    n.AuthenticationTicket.Properties);
                            },

                            RedirectToIdentityProvider = n =>
                                {
                                    if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                                    {
                                        var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                                        if (idTokenHint != null)
                                        {
                                            n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                                        }
                                    }

                                    return Task.FromResult(0);
                                }
                    }
                });
        }
Example #41
0
        public void Configuration(IAppBuilder app)
        {
            app.Map("/identity2", idsrvApp =>
            {
                idsrvApp.UseIdentityServer(new IdentityServerOptions
                {
                    SiteName = "Embedded IdentityServer",
                    SigningCertificate = LoadCertificate(),

                    //Factory = InMemoryFactory.Create(
                    //    users: Users.Get(),
                    //    clients: Clients.Get(),
                    //    scopes: StandardScopes.All)

                    Factory = InMemoryFactory.Create(
                             users: Users.Get(),
                             clients: Clients.Get(),
                            scopes: Scopes.Get())
                });
            });
           
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = "https://localhost:44301/identity2",
                ClientId = "mvc",
                Scope = "openid profile roles sampleApi",
                RedirectUri = "http://localhost:44300/home/about",
                ResponseType = "id_token token",
             
               SignInAsAuthenticationType = "Cookies",




                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var id = n.AuthenticationTicket.Identity;

                        // we want to keep first name, last name, subject and roles
                        var givenName = id.FindFirst(Constants.ClaimTypes.GivenName);
                        var familyName = id.FindFirst(Constants.ClaimTypes.FamilyName);
                        var sub = id.FindFirst(Constants.ClaimTypes.Subject);
                        var roles = id.FindAll(Constants.ClaimTypes.Role);

                        // create new identity and set name and role claim type
                        var nid = new ClaimsIdentity(
                            id.AuthenticationType,
                            Constants.ClaimTypes.GivenName,
                            Constants.ClaimTypes.Role);

                        // get userinfo data
                            var userInfoClient = new UserInfoClient(
                              new Uri(n.Options.Authority + "/connect/userinfo"),
                              n.ProtocolMessage.AccessToken);

                        var userInfo = await userInfoClient.GetAsync();
                        userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2)));

                        // keep the id_token for logout
                        nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                        // add access token for sample API
                        nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));

                        // keep track of access token expiration
                        nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));




                        //nid.AddClaim(givenName);
                        //nid.AddClaim(familyName);
                        //nid.AddClaim(sub);
                        //nid.AddClaims(roles);


                        // add some other app specific claim
                        nid.AddClaim(new Claim("app_specific", "some data"));

                        nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                        n.AuthenticationTicket = new AuthenticationTicket(
                            nid,
                            n.AuthenticationTicket.Properties);
                    },



                    RedirectToIdentityProvider = async n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value;
                            n.ProtocolMessage.IdTokenHint = idTokenHint;
                        }
                    }
                }
            });
            //The long claim names come from Microsoft's JWT handler trying to map some claim types to .NET's ClaimTypes class types. You can turn off this behavior with the following line of code (in Startup).
            AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();


            app.UseResourceAuthorization(new AuthorizationManager());

        }
Example #42
0
        public void Configuration(IAppBuilder app)
        {
            // turn off long claims names by preventing MS JWT handler of mapping to claims types
            AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            app.Map("/identity", idsrvApp =>
            {
                idsrvApp.UseIdentityServer(new IdentityServerOptions
                {
                    SiteName              = "Embedded IdentityServer",
                    SigningCertificate    = LoadCertificate(),
                    AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions
                    {
                        IdentityProviders             = ConfigureIdentityProviders,
                        EnablePostSignOutAutoRedirect = true
                    },

                    Factory = new IdentityServerServiceFactory()
                              .UseInMemoryUsers(Users.Get())
                              .UseInMemoryClients(Clients.Get())
                              .UseInMemoryScopes(Scopes.Get())
                });
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            // User OpenId connect Middleware
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority             = "https://localhost:44300/identity",
                ClientId              = "mvc",
                Scope                 = "openid profile roles",
                RedirectUri           = "https://localhost:44300/",
                PostLogoutRedirectUri = "https://localhost:44300/",

                ResponseType = "id_token",

                SignInAsAuthenticationType = "Cookies",
                UseTokenLifetime           = false,

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var id = n.AuthenticationTicket.Identity;

                        //if (id.FindFirst("idp").Value == "okta")
                        //    return;


                        // we want to keep first name, last name, subject and roles
                        var givenName  = id.FindFirst(Constants.ClaimTypes.GivenName);
                        var familyName = id.FindFirst(Constants.ClaimTypes.FamilyName);
                        var sub        = id.FindFirst(Constants.ClaimTypes.Subject);
                        var roles      = id.FindAll(Constants.ClaimTypes.Role);

                        // create new identity and set name and role claim type
                        var nid = new ClaimsIdentity(
                            id.AuthenticationType,
                            Constants.ClaimTypes.GivenName,
                            Constants.ClaimTypes.Role);

                        nid.AddClaim(givenName);
                        nid.AddClaim(familyName);
                        nid.AddClaim(sub);
                        nid.AddClaims(roles);

                        // add some other app specific claim
                        nid.AddClaim(new Claim("app_specific", "some data"));
                        // keep the id_token for logout
                        nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                        n.AuthenticationTicket = new AuthenticationTicket(nid, n.AuthenticationTicket.Properties);
                    },
                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }

                        return(Task.FromResult(0));
                    }
                }
            }
                                               );



            app.UseResourceAuthorization(new AuthorizationManager());
        }
        public void Configuration(IAppBuilder app)
        {
            // turn off long claims names by preventing MS JWT handler of mapping to claims types
            AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.Map("/identity", idsrvApp =>
            {
                idsrvApp.UseIdentityServer(new IdentityServerOptions
                {
                    SiteName = "Embedded IdentityServer",
                    SigningCertificate = LoadCertificate(),
                    AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions
                    {
                        IdentityProviders =  ConfigureIdentityProviders,
                      EnablePostSignOutAutoRedirect = true
                    },

                    Factory = new IdentityServerServiceFactory()
                                .UseInMemoryUsers(Users.Get())
                                .UseInMemoryClients(Clients.Get())
                                .UseInMemoryScopes(Scopes.Get())
                });
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            // User OpenId connect Middleware
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = "https://localhost:44300/identity",
                ClientId = "mvc",
                Scope = "openid profile roles",
                RedirectUri = "https://localhost:44300/",
                PostLogoutRedirectUri = "https://localhost:44300/",

                ResponseType = "id_token",

                SignInAsAuthenticationType = "Cookies",
                UseTokenLifetime = false,

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var id = n.AuthenticationTicket.Identity;

                        //if (id.FindFirst("idp").Value == "okta")
                        //    return;

                        // we want to keep first name, last name, subject and roles
                        var givenName = id.FindFirst(Constants.ClaimTypes.GivenName);
                        var familyName = id.FindFirst(Constants.ClaimTypes.FamilyName);
                        var sub = id.FindFirst(Constants.ClaimTypes.Subject);
                        var roles = id.FindAll(Constants.ClaimTypes.Role);

                        // create new identity and set name and role claim type
                        var nid = new ClaimsIdentity(
                            id.AuthenticationType,
                            Constants.ClaimTypes.GivenName,
                            Constants.ClaimTypes.Role);

                        nid.AddClaim(givenName);
                        nid.AddClaim(familyName);
                        nid.AddClaim(sub);
                        nid.AddClaims(roles);

                        // add some other app specific claim
                        nid.AddClaim(new Claim("app_specific", "some data"));
                        // keep the id_token for logout
                        nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                        n.AuthenticationTicket = new AuthenticationTicket(nid, n.AuthenticationTicket.Properties);

                    },
                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }

                        return Task.FromResult(0);
                    }
                }
            }
                );

            app.UseResourceAuthorization(new AuthorizationManager());
        }
 // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
 public void ConfigureAuth(IAppBuilder app)
 {
   app.UseResourceAuthorization(new MyWebAppAuthorization());
 }
        public void Configuration(IAppBuilder app)
        {
            AntiForgeryConfig.UniqueClaimTypeIdentifier = "sub";
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();


            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = Constants.IdentityServerUri,
                ClientId = Constants.ImplicitClient,
                Scope = "openid profile roles apiAccess",
                RedirectUri = Constants.ImplicitClientUri,
                ResponseType = "id_token token",
                UseTokenLifetime = false,
                SignInAsAuthenticationType = "Cookies",

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var nid = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            "givenname",
                            "role");

                        // get userinfo data
                        var userInfoClient = new UserInfoClient(new Uri(n.Options.Authority + "/connect/userinfo"), n.ProtocolMessage.AccessToken);

                        var userInfo = await userInfoClient.GetAsync();

                        if (userInfo.Claims != null)
                        {
                            userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2)));
                        }


                        // keep the id_token for logout
                        nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                        // add access token for sample API
                        nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));

                        // keep track of access token expiration
                        nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

                        n.AuthenticationTicket = new AuthenticationTicket(nid, n.AuthenticationTicket.Properties);
                    },

                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenHint != null)
                            {
                                n.ProtocolMessage.PostLogoutRedirectUri = Constants.ImplicitClientUri;
                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                            }
                        }

                        return Task.FromResult(0);
                    }
                }
            });

            app.UseResourceAuthorization(new AuthorizationManager());
        }
Example #46
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            AntiForgeryConfig.UniqueClaimTypeIdentifier = "unique_user_key";

            app.UseResourceAuthorization(new AuthorizationManager());

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = "mvc",
                Authority = ExpenseTrackerConstants.IdSrv,
                RedirectUri = ExpenseTrackerConstants.ExpenseTrackerClient,
                SignInAsAuthenticationType = "Cookies",
                
                ResponseType = "code id_token token",
                Scope = "openid profile roles",

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {

                    MessageReceived = async n =>
                    {
                        EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.IdToken);
                        EndpointAndTokenHelper.DecodeAndWrite(n.ProtocolMessage.AccessToken);

                        //var userInfo = await EndpointAndTokenHelper.CallUserInfoEndpoint(n.ProtocolMessage.AccessToken);    

                    },

                    SecurityTokenValidated = async n =>
                    {                         
                        var userInfo = await EndpointAndTokenHelper.CallUserInfoEndpoint(n.ProtocolMessage.AccessToken);


                        var givenNameClaim = new Claim(
                            Thinktecture.IdentityModel.Client.JwtClaimTypes.GivenName,
                            userInfo.Value<string>("given_name"));

                        var familyNameClaim = new Claim(
                            Thinktecture.IdentityModel.Client.JwtClaimTypes.FamilyName,
                            userInfo.Value<string>("family_name"));

                        var roles = userInfo.Value<JArray>("role").ToList();
 
                        var newIdentity = new ClaimsIdentity(
                           n.AuthenticationTicket.Identity.AuthenticationType,
                           Thinktecture.IdentityModel.Client.JwtClaimTypes.GivenName,
                           Thinktecture.IdentityModel.Client.JwtClaimTypes.Role);

                        newIdentity.AddClaim(givenNameClaim);
                        newIdentity.AddClaim(familyNameClaim);

                        foreach (var role in roles)
                        {
                            newIdentity.AddClaim(new Claim(
                            Thinktecture.IdentityModel.Client.JwtClaimTypes.Role,
                            role.ToString()));
                        }

                        var issuerClaim = n.AuthenticationTicket.Identity
                            .FindFirst(Thinktecture.IdentityModel.Client.JwtClaimTypes.Issuer);
                        var subjectClaim = n.AuthenticationTicket.Identity
                            .FindFirst(Thinktecture.IdentityModel.Client.JwtClaimTypes.Subject);

                        newIdentity.AddClaim(new Claim("unique_user_key",
                            issuerClaim.Value + "_" + subjectClaim.Value));


                        var oAuth2Client = new OAuth2Client(
                         new Uri(ExpenseTrackerConstants.IdSrvToken),
                         "mvc_api",
                         "secret");

                        var response = oAuth2Client.RequestClientCredentialsAsync("expensetrackerapi").Result;

                        // add the token                        
                        newIdentity.AddClaim(new Claim("access_token",
                      response.AccessToken));


                        n.AuthenticationTicket = new AuthenticationTicket(
                            newIdentity,
                            n.AuthenticationTicket.Properties);

                    },


                }

                                 
              
                });

            
        }
Example #47
0
            public void ConfigureAuth(IAppBuilder app)
            {

            //   LG.Owin.Security.Enviornment.Startup.ConfigAuth(app);

            AntiForgeryConfig.UniqueClaimTypeIdentifier = Thinktecture.IdentityServer.Core.Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.UseResourceAuthorization(
                new AuthorizationManager());

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies",
                AuthenticationMode = AuthenticationMode.Active
            });

            app.SetDefaultSignInAsAuthenticationType("External");
            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority = LG.Owin.Security.Config.ServerSettings.Url,
                ClientId = LG.Owin.Security.Config.ClientSettings.ClientID,
                ClientSecret = "51FC860D-07D3-4296-9147-2E40AC7FF6C8".Sha256(),
                Scope = "openid profile roles all_claims",
                ResponseType = "id_token token",
                RedirectUri = "https://www.1888md.com/Members/",
                SignInAsAuthenticationType = "Cookies",
                UseTokenLifetime = false,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        var nid = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                              Thinktecture.IdentityServer.Core.Constants.ClaimTypes.GivenName,

                        Thinktecture.IdentityServer.Core.Constants.ClaimTypes.Role);

                        var userInfoClient = new UserInfoClient(
                          new Uri(n.Options.Authority + "/connect/userinfo"),
                          n.ProtocolMessage.AccessToken);

                        var userInfo = await userInfoClient.GetAsync();
                        userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2)));

                        //userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(
                        //    new Claim(ui.Item1, ui.Item2)));

                        // keep the id_token for logout
                        nid.AddClaim(new Claim("id_token",
                            n.ProtocolMessage.IdToken));

                        // add access token for sample API
                        nid.AddClaim(new Claim("access_token",
                            n.ProtocolMessage.AccessToken));

                        // keep track of access token expiration
                        nid.AddClaim(new Claim("expires_at",
                            DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

                        // add some other app specific claim
                        //nid.AddClaim(new Claim("app_specific", "some data"));
                        n.AuthenticationTicket = new AuthenticationTicket(nid, n.AuthenticationTicket.Properties);

                    },
                    RedirectToIdentityProvider = async n =>
                    {
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest)
                        {
                            await GetWaiter();
                            var sb = new StringBuilder();
                            var custom = n.OwinContext.Get<Dictionary<string, string>>("OpenIdConnect.Parameters");
                            if (custom != null)
                            {
                                foreach (var c in custom)
                                {
                                    // ReSharper disable once UseStringInterpolation
                                    sb.Append(string.Format(" {0}={1}", c.Key, c.Value));
                                }
                            }
                            if (sb.Length > 0) { sb.Remove(0, 1); }
                            n.ProtocolMessage.AcrValues = sb.ToString();
                        }
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");
                            if (idTokenHint != null) { n.ProtocolMessage.IdTokenHint = idTokenHint.Value; }
                        }
                    }
                }
            });
        }
Example #48
0
        public void Configuration(IAppBuilder app)
        {
            AntiForgeryConfig.UniqueClaimTypeIdentifier = Constants.ClaimTypes.Subject;
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

            app.Map(
                "/identity",
                idsrvApp =>
                    {
                        idsrvApp.UseIdentityServer(
                            new IdentityServerOptions
                                {
                                    SiteName = "Embedded IdentityServer",
                                    SigningCertificate = LoadCertificate(),
                                    Factory =
                                        new IdentityServerServiceFactory().UseInMemoryUsers(
                                            Users.Get())
                                        .UseInMemoryClients(Clients.Get())
                                        .UseInMemoryScopes(Scopes.Get()),

                                    // Use this for Facebook login
                                    //AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions
                                    //{
                                    //    IdentityProviders = ConfigureIdentityProviders
                                    //}
                                });
                    });

            app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" });

            // Point the OpenID Connect middleware (also in Startup.cs) to our embedded version of IdentityServer and use the previously configured client configuration
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                    {
                        Authority = "https://localhost:44301/identity",
                        ClientId = "mvc",
                        Scope = "openid profile roles sampleApi",
                        RedirectUri = "https://localhost:44301/",
                        ResponseType = "id_token token",
                        SignInAsAuthenticationType = "Cookies",
                        UseTokenLifetime = false,

                        // Do the claims transformations
                        Notifications = new OpenIdConnectAuthenticationNotifications
                                            {

                            SecurityTokenValidated = async n =>
                                                    {
                                                        var nid = new ClaimsIdentity(
                                                            n.AuthenticationTicket.Identity.AuthenticationType,
                                                            Constants.ClaimTypes.GivenName,
                                                            Constants.ClaimTypes.Role);

                                                        // get userinfo data
                                                        var userInfoClient = new UserInfoClient(
                                                            new Uri(n.Options.Authority + "/connect/userinfo"),
                                                            n.ProtocolMessage.AccessToken);

                                                        var userInfo = await userInfoClient.GetAsync();
                                                        userInfo.Claims.ToList().ForEach(ui => nid.AddClaim(new Claim(ui.Item1, ui.Item2)));

                                                        // keep the id_token for Logout - the client has to prove its identity to the
                                                        // logout endpoint to make sure we redirect to the right URL (and not some spammer/phishing page).
                                                        nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

                                                        // add access token for sample API
                                                        nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));

                                                        // keep track of access token expiration
                                                        nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));

                                                        // add some other app specific claim
                                                        nid.AddClaim(new Claim("app_specific", "some data"));

                                                        n.AuthenticationTicket = new AuthenticationTicket(
                                                            nid,
                                                            n.AuthenticationTicket.Properties);
                                                    },

                            // attach the id_token when the user logs out and we make the roundtrip to IdentityServer.
                            RedirectToIdentityProvider = n =>
                                                    {
                                                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                                                        {
                                                            var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                                                            if (idTokenHint != null)
                                                            {
                                                                n.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                                                            }
                                                        }

                                                        return Task.FromResult(0);
                                                    }
                        }
                    });

            app.UseResourceAuthorization(new AuthorizationManager());
        }
Example #49
0
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            app.SetupFilters(config);
            app.SetupRoutes(config);
            app.SetupDependencies(config);

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions() {
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
                AllowInsecureHttp = true,
                Provider = new SimpleAuthorizationServerProvider(),
                TokenEndpointPath = new PathString("/api/token")
            });

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions() { });

            app.UseResourceAuthorization(new AppAuthorization());

            app.UseWebApi(config);
        }