protected override void Render(HtmlTextWriter writer)
        {
            try
            {
                SearchContext _searchContext = SearchContext.Current;

                if (_searchContext != null)
                {
                    Scopes _scopes = new Scopes(_searchContext);
                    string _options = string.Empty;
                    foreach (Scope scop in _scopes.AllScopes)
                    {
                        _options += "<option value='" + scop.Name + "'>" + scop.Name + "</option>";
                    }
                    writer.Write("<table width='90%' class='searchtable' cellpadding='0' cellspacing='0'>"
                    + "<tr  height='32px'>"
                    + "<td colspan='2' class='searchtxt' align='left' style='background-color:#2066aa;'>Search</td></tr>"
                    + "<tr><td colspan='2' class = 'searchtr' align='left'><select id='drpsearchbox' class='drpsearch' >" + _options + "</select></td></tr>"
                    + "<tr><td class='searchtr' align='left'><input name='txtsearchbox' id='txtsearchbox' type='text' class='searchtextbox'  width='100%' /><input type='hidden' name='nameprefix$ASB_SS_scb_1_4' value='nameprefix$ASB_SS_scb_1_4'/></td><td class='searchtr' width='5%' align='left'><input id=\"Submit1\" onclick=\"WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions('nameprefix$ASB_BS_SRCH_1', '', false, '', '/Pages/SearchResult.aspx?k=' + document.getElementById('txtsearchbox').value + '&s=' + document.getElementById('drpsearchbox').value  , false, false))\" type=\"submit\" name=\"nameprefix$ASB_BS_SRCH_1\" value=\"Go\" /> </td></tr>"
                    + "</tr></table>");

                }
            }
            catch (Exception exc)
            {
                writer.Write(exc.Message);
            }
        }
 public static Resources GetScopeResource(Scopes scope)
 {
     if (scope < firstExchangeScope)
         return Resources.Graph;
     else if (scope < firstSharePointScope)
         return Resources.Exchange;
     return Resources.SharePoint;
 }
예제 #3
0
 private string GetScope(Scopes scope)
 {
     switch (scope)
     {
         case Scopes.ReadWrite:
             return "read,write";
         case Scopes.Moderator:
             return "read,write,admin";
         default:
             return "read";
     }
 }
예제 #4
0
파일: API.cs 프로젝트: TlhanGhun/Quote-
 public static ListOfArticles getArticlesListByCategories(List<Category> categories, string language = "", Scopes scope = Scopes.none, decimal page = 0, int pageSize = 0)
 {
     if (categories == null)
     {
         return null;
     }
     List<decimal> ids = new List<decimal>();
     foreach (Category category in categories)
     {
         if (category != null)
         {
             ids.Add(category.id);
         }
     }
     return getArticlesListByCategories(ids, language, scope, page, pageSize);
 }
예제 #5
0
        public static IdentityServerServiceFactory Configure()
        {
            var factory = new IdentityServerServiceFactory();

            var scopeStore = new InMemoryScopeStore(Scopes.Get());

            factory.ScopeStore = new Registration <IScopeStore>(scopeStore);
            var clientStore = new InMemoryClientStore(Clients.Get());

            factory.ClientStore = new Registration <IClientStore>(clientStore);

            factory.CorsPolicyService = new Registration <ICorsPolicyService>(new DefaultCorsPolicyService {
                AllowAll = true
            });

            return(factory);
        }
예제 #6
0
        public void Configuration(IAppBuilder app)
        {
            app.Map("/identity", idsrvApp =>
            {
                var factory = new IdentityServerServiceFactory()
                              .UseInMemoryClients(Clients.Get())
                              .UseInMemoryScopes(Scopes.Get());

                factory.CorsPolicyService = new Registration <ICorsPolicyService>(new DefaultCorsPolicyService {
                    AllowAll = true
                });
                factory.ConfigureUserService();
                factory.ConfigureConsentService();

                var options = new IdentityServerOptions
                {
                    SiteName              = "RealDolmen TicketService STS",
                    SigningCertificate    = LoadCertificate(),
                    Factory               = factory,
                    AuthenticationOptions = new AuthenticationOptions
                    {
                        EnablePostSignOutAutoRedirect = true
                    }
                };

                idsrvApp.UseIdentityServer(options);
            });

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

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

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority    = $"{SecurityConstants.IdentityServerUri}/identity",
                ClientId     = "mvc",
                RedirectUri  = $"{SecurityConstants.IdentityServerUri}/",
                ResponseType = "id_token",

                SignInAsAuthenticationType = "Cookies"
            });
        }
예제 #7
0
파일: Startup.cs 프로젝트: pirumpi/ssoTest
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            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())
                });
            });
        }
예제 #8
0
        public void Configuration(IAppBuilder app)
        {
            app.Map("/identity", idsrvApp =>
            {
                idsrvApp.UseIdentityServer(new IdentityServerOptions
                {
                    SiteName           = "Embedded IdentityServer",
                    IssuerUri          = ExpenseTrackerConstants.IdSrvIssuerUri,
                    SigningCertificate = LoadCertificate(),

                    Factory = InMemoryFactory.Create(
                        users: Users.Get(),
                        clients: Clients.Get(),
                        scopes: Scopes.Get())
                });
            });
        }
예제 #9
0
        private static void ConfigureIdentityServer(
            IServiceCollection services,
            IConfiguration configuration,
            ILogger logger,
            IHostingEnvironment hostingEnvironment)
        {
            if (!hostingEnvironment.IsDevelopment())
            {
                throw new NotSupportedException($"The Identity Server configuration is currently only intended for Development environments. Current environment: '{hostingEnvironment.EnvironmentName}'");
            }

            var clientSource = new ConfigurationBasedClientSource(logger);
            var clients      = clientSource.LoadClients(configuration.GetSection("Identity:Clients"))
                               .ToList();

            var identityServerBuilder = services.AddIdentityServer(options =>
            {
                options.Endpoints.EnableAuthorizeEndpoint = true;
                options.Endpoints.EnableTokenEndpoint     = true;
                options.UserInteraction.ErrorUrl          = "/account/error";
            })
                                        .AddTemporarySigningCredential() // using inbuilt signing cert, but we are explicitly a dev-only service at this point ;-)
                                        .AddInMemoryClients(clients)
                                        .AddInMemoryIdentityResources(Scopes.GetIdentityResources())
                                        .AddInMemoryApiResources(Scopes.GetApiResources())
            ;

            // Facebook Sign-in method

            //var facebookUserAccessTokenEnabled = bool.Parse(configuration["Identity:SignInMethods:Facebook:EnableAccessToken"] ?? "false");
            //if (facebookUserAccessTokenEnabled)
            //{
            //    identityServerBuilder.AddExtensionGrantValidator<FacebookUserAccessTokenExtensionGrantValidator>();
            //}

            identityServerBuilder.AddGrantValidatorIfConfigured <FacebookUserAccessTokenExtensionGrantValidator>("Identity:SignInMethods:Facebook:EnableAccessToken", configuration);
            identityServerBuilder.AddGrantValidatorIfConfigured <GuestAccessTokenExtensionGrantValidator>("Identity:SignInMethods:GuestAccess:Enabled", configuration);


            // Guest access token sign-in
            services.AddTransient <IPasswordHasher, PasswordHasher>();
            services.AddTransient <IProfileService, StoreBackedProfileService>();
            services.AddTransient <IResourceOwnerPasswordValidator, StoreBackedResourceOwnerPasswordValidator>();
            services.AddTransient <UserClaimsProvider>();
            services.AddTransient <FacebookGraphService>();
        }
예제 #10
0
        public void ConfigureIdentityServer3(IAppBuilder app)
        {
            app.Map("/identity", idsrvApp =>
            {
                idsrvApp.UseIdentityServer(new IdentityServerOptions
                {
                    SiteName           = "Embedded IdentityServer",
                    SigningCertificate = LoadCertificate(),
                    CspOptions         = new CspOptions
                    {
                        Enabled = false
                    },
                    Factory = new IdentityServerServiceFactory()
                              .UseInMemoryUsers(Users.Get())
                              .UseInMemoryClients(Clients.Get())
                              .UseInMemoryScopes(Scopes.Get()),

                    AuthenticationOptions = new AuthenticationOptions
                    {
                        EnablePostSignOutAutoRedirect = true
                    }
                });
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies",
                CookieSecure       = CookieSecureOption.Never
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Authority    = "https://localhost:44335/identity",
                ClientId     = "sample",
                Scope        = "openid profile roles api",
                ResponseType = "id_token token",
                RedirectUri  = "https://localhost:44335/",
                SignInAsAuthenticationType = "Cookies",
                UseTokenLifetime           = false,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated     = OnSecurityTokenValidated,
                    RedirectToIdentityProvider = OnRedirectToIdentityProvider
                }
            });
        }
예제 #11
0
        public override Task <IScope> this[string name]
        {
            get
            {
                Log.LogDebug("Fetching scope {0}", name);

                if (name == DefaultScope)
                {
                    if (Scopes.TryGetValue(name, out var scope))
                    {
                        return(Task.FromResult(scope));
                    }
                }

                throw new NotSupportedException("Only the default Scope is supported by Memcached Buckets");
            }
        }
예제 #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "idsvr3test.pfx"), "idsrv3test");

            services.AddMvc();

            services.AddTransient <IUserManager, UserManager>();
            services.AddTransient <IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>();
            services.AddTransient <IProfileService, ProfileService>();

            var builder = services.AddIdentityServer()
                          .SetSigningCredential(cert)
                          .AddInMemoryStores()
                          .AddInMemoryClients(Clients.Get())
                          .AddInMemoryScopes(Scopes.Get())
                          .SetTemporarySigningCredential();
        }
 public override int GetHashCode()
 {
     unchecked
     {
         int hash = 17;
         hash = hash * 31 + EnableSavedGames.GetHashCode();
         hash = hash * 31 + IsForcingRefresh.GetHashCode();
         hash = hash * 31 + IsHidingPopups.GetHashCode();
         hash = hash * 31 + IsRequestingEmail.GetHashCode();
         hash = hash * 31 + IsRequestingAuthCode.GetHashCode();
         hash = hash * 31 + Scopes.GetHashCode();
         hash = hash * 31 + AccountName.GetHashCode();
         hash = hash * 31 + InvitationDelegate.GetHashCode();
         hash = hash * 31 + MatchDelegate.GetHashCode();
         return(hash);
     }
 }
예제 #14
0
            public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception?exception, Func <TState, Exception?, string> formatter)
            {
                ICollection <object>?Scopes = null;

                _ScopeProvider.ForEachScope(
                    (scope, state) =>
                {
                    if (Scopes == null)
                    {
                        Scopes = new Collection <object>();
                    }
                    Scopes.Add(scope);
                },
                    state);

                Message = LoggerJsonMessage.FromLoggerData(null, "Category", Scopes, logLevel, eventId, state, exception, formatter);
            }
예제 #15
0
        public override IScope this[string scopeName]
        {
            get
            {
                Logger.LogDebug("Fetching scope {0}", scopeName);

                if (scopeName == KeyValue.Scope.DefaultScopeName)
                {
                    if (Scopes.TryGetValue(scopeName, out var scope))
                    {
                        return(scope);
                    }
                }

                throw new NotSupportedException("Only the default Scope is supported by Memcached Buckets");
            }
        }
예제 #16
0
        public void Configuration(IAppBuilder app)
        {
            LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider());

            app.Map("/core", coreApp =>
            {
                var factory = InMemoryFactory.Create(
                    clients: Clients.Get(),
                    scopes: Scopes.Get());

                // different examples of custom user services
                var userService = new RegisterFirstExternalRegistrationUserService();
                //var userService = new ExternalRegistrationUserService();
                //var userService = new EulaAtLoginUserService();
                //var userService = new LocalRegistrationUserService();

                factory.UserService = Registration.RegisterFactory <IUserService>(() => userService);

                var options = new IdentityServerOptions
                {
                    IssuerUri  = "https://idsrv3.com",
                    SiteName   = "Thinktecture IdentityServer v3 - CustomUserService",
                    RequireSsl = false,

                    SigningCertificate = Certificate.Get(),
                    Factory            = factory,
                    CorsPolicy         = CorsPolicy.AllowAll,

                    AdditionalIdentityProviderConfiguration = ConfigureAdditionalIdentityProviders,

                    AuthenticationOptions = new AuthenticationOptions
                    {
                        LoginPageLinks = new LoginPageLink[] {
                            new LoginPageLink {
                                Text = "Register",
                                //Href = "~/localregistration"
                                Href = "localregistration"
                            }
                        }
                    }
                };

                coreApp.UseIdentityServer(options);
            });
        }
예제 #17
0
        //When a variable's value is changed.
        public override object VisitStat_setvar([NotNull] algoParser.Stat_setvarContext context)
        {
            //Get the variable/object reference.
            AlgoValue varToSet = Particles.ParseParticleBlock(this, context, context.IDENTIFIER(), context.particle());

            if (varToSet == null)
            {
                Error.Fatal(context, "No value returned to set.");
                return(null);
            }

            //Does, evaluate the expression to set the value.
            AlgoValue value = (AlgoValue)VisitExpr(context.expr());

            //Check if there's a rounding expression.
            if (context.rounding_expr() != null)
            {
                //Evaluate rounding number expression.
                AlgoValue roundingNum = (AlgoValue)VisitExpr(context.rounding_expr().expr());
                if (roundingNum.Type != AlgoValueType.Integer)
                {
                    Error.Warning(context, "Rounding expression did not return an integer to round by, so rounding was ignored.");
                }
                else if ((BigInteger)roundingNum.Value > int.MaxValue)
                {
                    Error.Warning(context, "Rounding number too large, so rounding was ignored.");
                }
                else
                {
                    //Getting rounding integer.
                    int roundingInt = int.Parse(((BigInteger)roundingNum.Value).ToString());

                    //Rounding the value, setting.
                    Scopes.SetVariable(context.IDENTIFIER().GetText(), AlgoOperators.Round(context, value, roundingInt));

                    return(null);
                }
            }

            //Set variable.
            varToSet.Value = value.Value;
            varToSet.Type  = value.Type;

            return(null);
        }
예제 #18
0
        public void Configuration(IAppBuilder app)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Trace()
                         .CreateLogger();

            app.UseIdentityServer(new IdentityServerOptions
            {
                SiteName           = "Embedded IdentityServer",
                SigningCertificate = LoadCertificate("localhost"),

                Factory = new IdentityServerServiceFactory()
                          .UseInMemoryUsers(Users.Get())
                          .UseInMemoryClients(Clients.Get())
                          .UseInMemoryScopes(Scopes.Get())
            });
        }
예제 #19
0
        public void Dispose()
        {
            if (AutoCommit)
            {
                if (_hasException == null)
                {
                    long exceptionCode = Marshal.GetExceptionCode();
                    _hasException = exceptionCode != 0 && exceptionCode != 0xCCCCCCCC;
                }

                if (_hasException.Value || !Item.Commit(ItemType))
                {
                    Item.Rollback(ItemType);
                }
            }
            Transaction.Dispose();
            Scopes.Pop();
        }
예제 #20
0
        public Task <IdentityServiceResult> AddScopeAsync(TApplication application, string scope, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            if (application == null)
            {
                throw new ArgumentNullException(nameof(application));
            }

            if (scope == null)
            {
                throw new ArgumentNullException(nameof(scope));
            }

            Scopes.Add(CreateScope(application, scope));

            return(Task.FromResult(IdentityServiceResult.Success));
        }
예제 #21
0
        public ApiResource(string scopeName, string displayName, IEnumerable <string> userClaimTypes)
        {
            if (scopeName.IsMissing())
            {
                throw new ArgumentNullException(nameof(scopeName));
            }

            Name = scopeName;
            Scopes.Add(new Scope(scopeName, displayName));

            if (!userClaimTypes.IsNullOrEmpty())
            {
                foreach (var type in userClaimTypes)
                {
                    UserClaims.Add(new UserClaim(type));
                }
            }
        }
예제 #22
0
        public void Configuration(IAppBuilder appBuilder)
        {
            var factory = new IdentityServerServiceFactory();

            factory
            .UseInMemoryClients(Clients.Get())
            .UseInMemoryScopes(Scopes.Get())
            .UseInMemoryUsers(Users.Get());

            var options = new IdentityServerOptions
            {
                SiteName           = "EPiServer friendly IdentityServer",
                SigningCertificate = Certificate.Get(),
                Factory            = factory
            };

            appBuilder.UseIdentityServer(options);
        }
        public void Configuration(IAppBuilder appBuilder)
        {
            var factory = InMemoryFactory.Create(
                users:   Users.Get(),
                clients: Clients.Get(),
                scopes:  Scopes.Get());

            var options = new IdentityServerOptions
            {
                IssuerUri = "https://idsrv3.com",
                SiteName  = "Thinktecture IdentityServer v3 (self host)",

                SigningCertificate = Certificate.Get(),
                Factory            = factory,
            };

            appBuilder.UseIdentityServer(options);
        }
예제 #24
0
        private void InitializeLegend()
        {
            legend.Children.Clear();

            int amount = 0;

            for (int i = 0; i < Scopes.Count(); i++)
            {
                if (Scopes[i].Sum != 0)                                      //Initialize LegendItems only for not empty Pies
                {
                    var legendItem = new PieLegendItem(amount, UsersBrushes[amount], Scopes[i].EnumMember.Item);
                    amount++;
                    legendItem.MouseOn  += LegendItem_MouseOn;
                    legendItem.MouseOut += LegendItem_MouseOut;
                    legend.Children.Add(legendItem);
                }
            }
        }
예제 #25
0
        public void Configuration(IAppBuilder app)
        {
            // 設定提供 Identity ( Login 等路徑頁面 )
            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()),
                    //.UseInMemoryScopes(StandardScopes.All)
                });
            });
        }
예제 #26
0
        public QQConnectOptions(string clientId, string clientSecret, bool isMobile, ISet <string> scopes)
        {
            if (string.IsNullOrEmpty(clientId))
            {
                throw new ArgumentNullException(nameof(clientId));
            }
            ClientId = clientId;

            if (string.IsNullOrEmpty(clientSecret))
            {
                throw new ArgumentNullException(nameof(clientSecret));
            }
            ClientSecret = clientSecret;

            IsMobile = isMobile;

            Scopes.AddAll(scopes);
        }
예제 #27
0
        /// <summary>
        ///     Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            unchecked // Overflow is fine, just wrap
            {
                int hashCode = 41;
                // Suitable nullity checks etc, of course :)
                if (IsCanceled != null)
                {
                    hashCode = hashCode * 59 + IsCanceled.GetHashCode();
                }

                if (IsError != null)
                {
                    hashCode = hashCode * 59 + IsError.GetHashCode();
                }

                if (ErrorCode != null)
                {
                    hashCode = hashCode * 59 + ErrorCode.GetHashCode();
                }

                if (AccessToken != null)
                {
                    hashCode = hashCode * 59 + AccessToken.GetHashCode();
                }

                if (IdToken != null)
                {
                    hashCode = hashCode * 59 + IdToken.GetHashCode();
                }

                if (Scopes != null)
                {
                    hashCode = hashCode * 59 + Scopes.GetHashCode();
                }

                if (ExpiresOn != null)
                {
                    hashCode = hashCode * 59 + ExpiresOn.GetHashCode();
                }

                return(hashCode);
            }
        }
예제 #28
0
        public async Task <Utf8String> AuthorizeAsync(CancellationToken cancelToken)
        {
            using (var client = new ClientWebSocket())
            {
                client.Options.SetRequestHeader("origin", Origin);
                await SearchForServerAsync(client, cancelToken).ConfigureAwait(false);

                {
                    var receiveTask = ReceiveAsync(client, null, cancelToken);
                    await WhenAny(new Task[] { receiveTask }, ConnectionTimeoutMillis,
                                  "Timed out waiting for READY").ConfigureAwait(false);

                    var evnt = await receiveTask.ConfigureAwait(false);

                    if (!(evnt.Data is ReadyEvent readyEvent))
                    {
                        throw new Exception("First event was not a READY cmd");
                    }
                }

                await SendAsync(client, cancelToken, new RpcPayload
                {
                    Command = RpcCommand.Authorize,
                    Args    = new AuthorizeParams
                    {
                        ClientId = new Utf8String(ClientId.ToString()),
                        Scopes   = Scopes?.Select(x => new Utf8String(x)).ToArray() ?? Array.Empty <Utf8String>()
                    }
                }).ConfigureAwait(false);

                {
                    var receiveTask = ReceiveAsync(client, null, cancelToken);
                    await WhenAny(new Task[] { receiveTask, Task.Delay(-1, cancelToken) }).ConfigureAwait(false);

                    var evnt = await receiveTask.ConfigureAwait(false);

                    if (!(evnt.Data is AuthorizeResponse authorizeEvent))
                    {
                        throw new Exception("Authorize response was not a AUTHORIZE cmd");
                    }
                    return(authorizeEvent.Code);
                }
            }
        }
        public static IAppBuilder UseIdentityServer(this IAppBuilder app)
        {
            // uncomment to enable HSTS headers for the host
            // see: https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security
            //app.UseHsts();

            app.Map("/core", coreApp =>
            {
                var factory = new IdentityServerServiceFactory()
                              .UseInMemoryUsers(Users.Get())
                              .UseInMemoryClients(Clients.Get())
                              .UseInMemoryScopes(Scopes.Get());

                factory.AddCustomGrantValidators();
                factory.AddCustomTokenResponseGenerator();

                factory.ConfigureClientStoreCache();
                factory.ConfigureScopeStoreCache();
                factory.ConfigureUserServiceCache();

                var idsrvOptions = new IdentityServerOptions
                {
                    Factory            = factory,
                    SigningCertificate = Cert.Load(),

                    Endpoints = new EndpointOptions
                    {
                        // replaced by the introspection endpoint in v2.2
                        EnableAccessTokenValidationEndpoint = false
                    },

                    AuthenticationOptions = new AuthenticationOptions
                    {
                        IdentityProviders = ConfigureIdentityProviders,
                        EnableAutoCallbackForFederatedSignout = true
                    },
                    RequireSsl = false
                };

                coreApp.UseIdentityServer(idsrvOptions);
            });

            return(app);
        }
예제 #30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            var cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "idsvr3test.pfx"), "idsrv3test");

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                options.Cookies.ApplicationCookie.AuthenticationScheme = "Cookies";
                options.ClaimsIdentity.UserIdClaimType   = JwtClaimTypes.Subject;
                options.ClaimsIdentity.UserNameClaimType = JwtClaimTypes.Name;
                options.ClaimsIdentity.RoleClaimType     = JwtClaimTypes.Role;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            var builder = services.AddIdentityServer(options =>
            {
                options.UserInteractionOptions.LoginUrl   = "/login";
                options.UserInteractionOptions.LogoutUrl  = "/logout";
                options.UserInteractionOptions.ConsentUrl = "/consent";
                options.UserInteractionOptions.ErrorUrl   = "/error";
            })
                          .SetSigningCredential(cert)
                          .AddInMemoryClients(Clients.Get())
                          .AddInMemoryScopes(Scopes.Get());

            //.AddInMemoryUsers(new List<ApplicationUser>());


            services.AddTransient <IProfileService, AspIdProfileService>();
            services.AddTransient <IUserClaimsPrincipalFactory <ApplicationUser>, IdentityServerUserClaimsPrincipalFactory>();
            services.AddTransient <IResourceOwnerPasswordValidator, ID4ResourceOwnerPasswordValidator>();

            // for the UI
            services.AddMvc();
            //  services.AddAuthentication(options => new ActiveDirectoryCookieOptions());
            services.AddAuthentication();
            // services.AddTransient<UI.Login.LoginService>();
        }
예제 #31
0
        public void Configuration(IAppBuilder app)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Trace()
                         .CreateLogger();

            app.Map("/core", coreApp =>
            {
                var factory = new IdentityServerServiceFactory()
                              .UseInMemoryUsers(Users.Get())
                              .UseInMemoryClients(Clients.Get())
                              .UseInMemoryScopes(Scopes.Get());


                var opts = new LocaleOptions
                {
                    LocaleProvider = env =>
                    {
                        var owinContext            = new OwinContext(env);
                        var owinRequest            = owinContext.Request;
                        var headers                = owinRequest.Headers;
                        var accept_language_header = headers["accept-language"].ToString();
                        var languages              = accept_language_header.Split(',').Select(StringWithQualityHeaderValue.Parse).OrderByDescending(s => s.Quality.GetValueOrDefault(1));
                        var locale = languages.First().Value;

                        return(locale);
                    }
                };
                factory.Register(new Registration <LocaleOptions>(opts));
                factory.LocalizationService = new Registration <ILocalizationService, GlobalizedLocalizationService>();


                var options = new IdentityServerOptions
                {
                    SiteName = "IdentityServer33 - Localized from accept-language http header Messages",

                    SigningCertificate = Certificate.Get(),
                    Factory            = factory
                };

                coreApp.UseIdentityServer(options);
            });
        }
예제 #32
0
        private object RequestCode(IServiceBase authService, IAuthSession session, AuthUserSession userSession, IAuthTokens tokens)
        {
            var state = Guid.NewGuid().ToString("N");

            userSession.State = state;
            var codeRequest = AuthorizeUrl + "?response_type=code&client_id={0}&redirect_uri={1}&scope={2}&state={3}"
                              .Fmt(ClientId, CallbackUrl.UrlEncode(), Scopes.Join(","), state);

            if (!DomainHint.IsNullOrEmpty())
            {
                codeRequest += "&domain_hint=" + DomainHint;
            }
            if (!tokens.UserName.IsNullOrEmpty())
            {
                codeRequest += "&login_hint=" + tokens.UserName;
            }
            authService.SaveSession(session, SessionExpiry);
            return(authService.Redirect(PreAuthUrlFilter(this, codeRequest)));
        }
예제 #33
0
        public void ConfigureServices(IServiceCollection services)
        {
            var cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "idsrv3test.pfx"), "idsrv3test");

            var builder = services.AddIdentityServer()
                          .SetSigningCredentials(cert)
                          .AddInMemoryClients(Clients.Get())
                          .AddInMemoryScopes(Scopes.Get())
                          .AddInMemoryUsers(Users.Get());

            // for the UI
            services
            .AddMvc()
            .AddRazorOptions(razor =>
            {
                razor.ViewLocationExpanders.Add(new UI.CustomViewLocationExpander());
            });
            services.AddTransient <UI.Login.LoginService>();
        }
예제 #34
0
        //Runs an Algo script, given a file path.
        public void RunAlgoScript(string path, string newScopeName = "")
        {
            //Read the entire text file into a lexer and tokens.
            string input  = File.ReadAllText(path);
            var    chars  = new AntlrInputStream(input);
            var    lexer  = new algoLexer(chars);
            var    tokens = new CommonTokenStream(lexer);

            //Parse the file.
            var parser = new algoParser(tokens);

            parser.BuildParseTree = true;
            var tree = parser.compileUnit();

            //Set the currently loaded file.
            FileInfo fi      = new FileInfo(path);
            string   oldFile = AlgoRuntimeInformation.FileLoaded;

            AlgoRuntimeInformation.FileLoaded = fi.Name;

            //If this is being placed in a separate scope, switch out now.
            AlgoScopeCollection oldScope = null;

            if (newScopeName != "")
            {
                oldScope = Scopes;
                Scopes   = new AlgoScopeCollection();
            }

            //Visit this tree, and fully execute.
            VisitCompileUnit(tree);

            //Set the currently loaded file back.
            AlgoRuntimeInformation.FileLoaded = oldFile;

            //If it was executed in a separate scope, save as a library with this name.
            if (newScopeName != "")
            {
                AlgoScopeCollection importScope = Scopes;
                Scopes = oldScope;
                Scopes.AddLibrary(newScopeName, importScope);
            }
        }
 public static string GetScopeId(Scopes scope)
 {
     return scopeIds[scope];
 }
예제 #36
0
 private bool TryGetScope(string component, out Scopes scope)
 {
     if (ScopesEx.AllValues.Contains(component))
     {
         scope = (Scopes) Enum.Parse(typeof (Scopes), component);
         return true;
     }
     scope = Scopes.build;
     return false;
 }
예제 #37
0
 public static Resources GetScopeResource(Scopes scope)
 {
     //HACK: right now only Microsoft Graph Resources Supported
     return Resources.MicrosoftGraph;
 }
예제 #38
0
파일: API.cs 프로젝트: TlhanGhun/Quote-
 public static ListOfRecommendations getRecommendationsListByArticle(decimal id, decimal page = 0, Scopes scope = Scopes.none)
 {
     if (id == 0)
     {
         return null;
     }
     ListOfRecommendations listOfRecommendations;
     Response webResponse;
     string requestUrl = string.Format("{0}{1}?id={2}", ApiBaseUrl, "/recommendation/listByArticle/", id.ToString());
     if (page != 0)
     {
         requestUrl += "&page=" + page.ToString();
     }
     if(scope != Scopes.none)
     {
         requestUrl += "&scope=" + scope.ToString();
     }
     webResponse = SendGetRequest(requestUrl);
     listOfRecommendations = JsonConvert.DeserializeObject<ListOfRecommendations>(webResponse.Content);
     return listOfRecommendations;
 }
예제 #39
0
파일: API.cs 프로젝트: TlhanGhun/Quote-
        public static ListOfRecommendations getRecommendationsListByUser(string username, decimal page = 0, Scopes scope = Scopes.none)
        {
            if (string.IsNullOrEmpty(username))
            {
                return null;
            }
            ListOfRecommendations listOfRecommendations;
            Response webResponse;
            string requestUrl = string.Format("{0}{1}?username={2}", ApiBaseUrl, "/recommendation/listByUser/", System.Web.HttpUtility.UrlEncode(username));
            if (page != 0)
            {
                requestUrl += "&page=" + page.ToString();
            }
            if(scope != Scopes.none)
            {
                requestUrl += "&scope=" + scope.ToString();
            }
            webResponse = SendGetRequest(requestUrl);
            if (webResponse.Content != null)
            {
                listOfRecommendations = JsonConvert.DeserializeObject<ListOfRecommendations>(webResponse.Content);
            }
            else
            {
                listOfRecommendations = null;
            }

            return listOfRecommendations;
        }
예제 #40
0
 public DsqOAuth(string apiKey, Uri callbackUrl, Scopes scopes)
 {
     this._apiKey = apiKey;
     this._callbackUrl = Uri.EscapeUriString(callbackUrl.OriginalString);
     this._scope = GetScope(scopes);
 }
예제 #41
0
파일: API.cs 프로젝트: TlhanGhun/Quote-
        public static ListOfArticles getArticlesListByCategories(List<decimal> ids, string language = "", Scopes scope = Scopes.none, decimal page = 0, int pageSize = 0)
        {
            if (ids == null)
            {
                return null;
            }
            if (ids.Count() == 0)
            {
                return new ListOfArticles();
            }
            ListOfArticles listOfArticles;
            Response webResponse;

            string requstUrl = string.Format("{0}{1}?ids={2}", ApiBaseUrl, "/article/listByCategories/", string.Join(",", ids));
            if (!string.IsNullOrEmpty(language))
            {
                requstUrl = requstUrl + "&language=" + System.Web.HttpUtility.UrlEncode(language);
            }
            if (scope != Scopes.none)
            {
                requstUrl = requstUrl + "&scope=" + System.Web.HttpUtility.UrlEncode(scope.ToString());
            }
            if (pageSize > 0)
            {
                requstUrl += "&pageSize=" + pageSize.ToString();
            }
            webResponse = SendGetRequest(requstUrl);
            listOfArticles = JsonConvert.DeserializeObject<ListOfArticles>(webResponse.Content);

            return listOfArticles;
        }
예제 #42
0
        private static string GetScope(Scopes scopes)
        {
            var values = new List<string>();

            if (scopes.HasFlag(Scopes.ReadPublic))
                values.Add("read_public");

            if (scopes.HasFlag(Scopes.WritePublic))
                values.Add("write_public");

            if (scopes.HasFlag(Scopes.ReadRelationships))
                values.Add("read_relationships");

            if (scopes.HasFlag(Scopes.WriteRelationShips))
                values.Add("write_relationships");

            return string.Join(",", values);
        }
        private static JArray GenerateRequiredAccess(Scopes[] appScopes)
        {
            var requiredAccess = new JArray();

            var graphAccess = GetResourceNode(Resources.Graph, appScopes);
            if (graphAccess != null)
                requiredAccess.Add(graphAccess);

            var exchangeAccess = GetResourceNode(Resources.Exchange, appScopes);
            if (exchangeAccess != null)
                requiredAccess.Add(exchangeAccess);

            var sharepointAccess = GetResourceNode(Resources.SharePoint, appScopes);
            if (sharepointAccess != null)
                requiredAccess.Add(sharepointAccess);

            return requiredAccess;
        }
예제 #44
0
 /// <summary>
 /// <para>
 ///     Generates a login URL with the required parameters.
 ///     Users will need to visit this URL to authorize your app to use the API on their behalf.
 /// </para>
 /// <para>
 ///     If they accept they will be redirected to the <paramref name="redirectUri"/>
 ///     with two query string parameters - "state" and "code".
 /// </para>
 /// <para>
 ///     Call <see cref="BuildAuthorizationUrl"/> if you want to specify the state value yourself to be able to prevent spoofing.
 /// </para>
 /// <para>
 ///     "code" is used with <see cref="GetAccessTokenAsync"/> to
 ///     get an access token to use with <see cref="PinterestClient"/>.
 /// </para>
 /// </summary>
 /// <param name="clientId">The Client ID (also known as App ID) of your app. See https://developers.pinterest.com/apps/</param>
 /// <param name="redirectUri">
 ///     The URL you want your user to be redirected to after authorizing your app.
 ///     The code needed for <see cref="GetAccessTokenAsync"/> will be added as query string parameter "code".
 /// </param>
 /// <param name="scopes">The scopes you want to request from the user.</param>
 /// <returns></returns>
 public static string BuildAuthorizationUrl(string clientId, string redirectUri, Scopes scopes)
 {
     return BuildAuthorizationUrl(clientId, redirectUri, scopes, CreateRandomState());
 }
예제 #45
0
        /// <summary>
        /// <para>
        ///     Generates a login URL with the required parameters.
        ///     Users will need to visit this URL to authorize your app to use the API on their behalf.
        /// </para>
        /// <para>
        ///     If they accept they will be redirected to the <paramref name="redirectUri"/>
        ///     with two query string parameters - "state" and "code".
        /// </para>
        /// <para>
        ///     "state" verifies that this comes from you.
        ///     "code" is used with <see cref="GetAccessTokenAsync"/> to
        ///     get an access token to use with <see cref="PinterestClient"/>.
        /// </para>
        /// </summary>
        /// <param name="clientId">The Client ID (also known as App ID) of your app. See https://developers.pinterest.com/apps/</param>
        /// <param name="redirectUri">
        ///     The URL you want your user to be redirected to after authorizing your app.
        ///     The code needed for <see cref="GetAccessTokenAsync"/> will be added as query string parameter "code".
        /// </param>
        /// <param name="scopes">The scopes you want to request from the user.</param>
        /// <param name="state">A string that is added to <paramref name="redirectUri"/> as query string parameter "state". This is to prevent spoofing.</param>
        /// <returns></returns>
        public static string BuildAuthorizationUrl(string clientId, string redirectUri, Scopes scopes, string state)
        {
            var scope = GetScope(scopes);

            return $"{BaseUrl}oauth/?response_type=code&client_id={clientId}&redirect_uri={redirectUri}&scope={scope}&state={state}";
        }
예제 #46
0
        private static JArray GenerateRequiredAccess(Scopes[] appScopes)
        {
            var requiredAccess = new JArray();

            var graphAccess = GetResourceNode(Resources.AzureGraph, appScopes);
            if (graphAccess != null)
                requiredAccess.Add(graphAccess);

            var msftGraphResource = GetResourceNode(Resources.MicrosoftGraph, appScopes);
            if (msftGraphResource != null)
                requiredAccess.Add(msftGraphResource);

            return requiredAccess;
        }
예제 #47
0
        private List<Wish> PostProcess(List<Wish> wishes, Wish defaults, Scopes scope)
        {
            wishes = Wish.CloneAndFillInBlanksFrom(wishes, defaults);
            wishes.ForEach(w => {
                w.Scope = scope;
                if( w.Version==null ){
                    w.Version = VersionMatcher.AnyMatcher;
                }
                //TODO:recursive?
                SetChildTransitivies(w);
            });

            SourceLocations.AddToSourceLocations(wishes, Source);
            return wishes;
        }
예제 #48
0
        private static JObject GetResourceNode(Resources resource, Scopes[] appScopes)
        {
            var entries = new JArray();

            foreach (Scopes scope in appScopes)
            {
                if (AppScopes.GetScopeResource(scope) == resource)
                {
                    var entry = new JObject(
                                    new JProperty("id", AppScopes.ScopeIds[scope]),
                                    new JProperty("type", "Scope")
                                    );

                    entries.Add(entry);
                }
            }

            if (entries.Count > 0)
            {
                var node = new JObject(
                                new JProperty("resourceAppId", AppScopes.ResourceIds[resource]),
                                new JProperty("resourceAccess", entries)
                                );

                return node;
            }

            return null;
        }