Beispiel #1
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="configurationManager"></param>
 /// <param name="authorizationConfig"></param>
 public TokenProvider(
     IConfigurationManager configurationManager,
     AuthorizationConfig authorizationConfig)
 {
     this.configurationManager = configurationManager;
     this.authorizationConfig  = authorizationConfig;
 }
        private void CreateAndLoginUser()
        {
            if (!IsValid)
            {
                return;
            }

            var createResult = OpenAuth.CreateUser(ProviderName, ProviderUserId, ProviderUserName, userName.Text);

            if (!createResult.IsSuccessful)
            {
                ModelState.AddModelError("UserName", createResult.ErrorMessage);
            }
            else
            {
                // User created & associated OK
                if (OpenAuth.Login(ProviderName, ProviderUserId, createPersistentCookie: false))
                {
                    //Roles cookie
                    HttpCookie cookie = new HttpCookie("Paper.Roles", AuthorizationConfig.GetRoles(User.Identity.Name));
                    Page.Response.Cookies.Add(cookie);

                    RedirectToReturnUrl();
                }
            }
        }
Beispiel #3
0
        public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            try
            {
                var actionAuthentication = context.ActionContext.ActionDescriptor.GetCustomAttributes <AuthenticationAttribute>();
                //验证
                if (
                    (actionAuthentication.Count > 0 && actionAuthentication.Last().Authenticate == true) ||
                    (actionAuthentication.Count == 0 && AuthenticationConfig.GetAuthenticateNoAttribute() == true)
                    )
                {
                    var ticket = context.Request.Headers.GetValues(AuthenticationConfig.AuthenticationString).FirstOrDefault();
                    if (ticket == null)
                    {
                        throw new AuthenticationException("can not get  ticket !");
                    }
                    object obj = MemCache.Get(AuthenticationConfig.TicketKeyPrefix + ticket);
                    if (obj == null)
                    {
                        AuthorizationConfig.RemoveRoles(ticket);
                        throw new AuthenticationException("Ticket has Expired !");
                    }

                    if (AuthenticationConfig.GetRefreshTicket())
                    {
                        MemCache.Add(AuthenticationConfig.TicketKeyPrefix + ticket, obj, DateTime.Now.AddSeconds(AuthenticationConfig.GetTicketExpire()));
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #4
0
        void OnAuthorizeRequest(object sender, EventArgs args)
        {
            HttpApplication app     = (HttpApplication)sender;
            HttpContext     context = app.Context;

            if (context == null || context.SkipAuthorization)
            {
                return;
            }

            HttpRequest req = context.Request;

#if NET_2_0
            AuthorizationSection config = (AuthorizationSection)WebConfigurationManager.GetSection("system.web/authorization", req.Path, context);
#else
            AuthorizationConfig config = (AuthorizationConfig)context.GetConfig("system.web/authorization");
            if (config == null)
            {
                return;
            }
#endif
            if (!config.IsValidUser(context.User, req.HttpMethod))
            {
                HttpException e        = new HttpException(401, "Unauthorized");
                HttpResponse  response = context.Response;

                response.StatusCode = 401;
                response.Write(e.GetHtmlErrorMessage());
                app.CompleteRequest();
            }
        }
Beispiel #5
0
        public static IServiceCollection ConfigureSecurity(this IServiceCollection services,
                                                           IConfiguration configuration)
        {
            var authorizationConfig = new AuthorizationConfig();

            configuration.Bind(nameof(AuthorizationConfig).Replace("Config", null), authorizationConfig);

            if (string.IsNullOrEmpty(authorizationConfig.SecretKey))
            {
                throw new ArgumentNullException("Jwt secret key is empty.");
            }

            services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(opt =>
            {
                opt.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authorizationConfig.SecretKey)),
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    ValidIssuer = authorizationConfig.Issuer
                };
            });

            return(services);
        }
Beispiel #6
0
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////
        // Module Enter: Get the authorization configuration section
        //    and see if this user is allowed or not
        void OnEnter(Object source, EventArgs eventArgs)
        {
            HttpApplication app;
            HttpContext     context;

            app     = (HttpApplication)source;
            context = app.Context;
            if (context.SkipAuthorization)
            {
                if (context.User.Identity.IsAuthenticated == false)
                {
                    PerfCounters.IncrementCounter(AppPerfCounter.ANONYMOUS_REQUESTS);
                }
                return;
            }

            // Get the authorization config object
            AuthorizationConfig settings = (AuthorizationConfig)context.GetConfig("system.web/authorization");

            // Check if the user is allowed, or the request is for the login page
            if (!settings.IsUserAllowed(context.User, context.Request.RequestType))
            {
                // Deny access
                context.Response.StatusCode = 401;
                WriteErrorMessage(context);
                app.CompleteRequest();
            }
            else
            {
                if (context.User.Identity.IsAuthenticated == false)
                {
                    PerfCounters.IncrementCounter(AppPerfCounter.ANONYMOUS_REQUESTS);
                }
            }
        }
Beispiel #7
0
 public void Configure(object config)
 {
     if (config is AuthorizationConfig authConfig)
     {
         _authConfig = authConfig;
     }
 }
Beispiel #8
0
 protected void LoggedIn(object sender, EventArgs e)
 {
     if (Page.Request.IsAuthenticated)
     {
         HttpCookie cookie = new HttpCookie("Paper.Roles", AuthorizationConfig.GetRoles(Context.User.Identity.Name));
         Page.Response.Cookies.Add(cookie);
     }
 }
Beispiel #9
0
 public Config()
 {
     Port           = "";
     Auth           = new AuthorizationConfig();
     BotConfig      = new BotConfig();
     CoinConfig     = new CoinSystemConfig();
     MiniChatConfig = new MiniChatConfig();
     PlayerConfig   = new PlayerConfig();
 }
Beispiel #10
0
        public RestrictedDemoAttribute(IOptionsSnapshot <AuthorizationConfig> configOptions)
        {
            if (configOptions == null)
            {
                throw new ArgumentNullException(nameof(configOptions));
            }

            _authorizationConfig = configOptions.Value;
        }
Beispiel #11
0
        public bool Authorize(string table, string action, string roles)
        {
            List <Guid> _roles = new List <Guid>();

            foreach (string rol in roles.Split('|'))
            {
                _roles.Add(new Guid(rol));
            }
            return(AuthorizationConfig.Authorize(table, action, _roles));
        }
Beispiel #12
0
        private bool IsAllowAnonymousRequest(ActionExecutingContext context)
        {
            var controlName = context.Controller.GetType().Name;
            var actionName  = context.ActionDescriptor.DisplayName.Split("(")[0].Trim();

            actionName = actionName.Substring(actionName.LastIndexOf('.') + 1);
            var configCenterSetting = AuthorizationConfig.GetIsAllowAnonymousRequest(controlName, actionName);

            return(context.Controller.GetType().CustomAttributes.Any(m => m.AttributeType.Name == typeof(AllowAnonymousAttribute).Name) ||
                   configCenterSetting);
        }
Beispiel #13
0
    protected virtual void Awake()
    {
        _authMethodConfig = this.GetComponent <AuthorizationConfig>();
        if (!_authMethodConfig)
        {
            Debug.LogError("No authorization config found on Spotify Service! Is the selected authorization method's config next to the service?");
            return;
        }

        StartService();
    }
        private void SetupControllerMap(List <Type> controllers)
        {
            var service = _container.Resolve <IControllerMapService>();

            var map = new AuthorizationConfig
            {
                Map = service.BuildControllerMap(controllers)
            };

            _container.Register(Component.For <AuthorizationConfig>().Instance(map).LifestyleSingleton());
        }
 /// <summary>
 /// Initializes the insatnce of the class
 /// </summary>
 /// <param name="httpClientFactory">The HTTP client factory.</param>
 /// <param name="servicesConfig">The services configuration.</param>
 /// <param name="logger">Represents the logger</param>
 /// <param name="authorizationConfig">The authorization configuration.</param>
 public UserIdExistsRequirementHandler(
     IHttpClientFactory httpClientFactory,
     ServicesConfig servicesConfig,
     ILogger <UserIdExistsRequirementHandler> logger,
     AuthorizationConfig authorizationConfig)
 {
     this.httpClientFactory   = httpClientFactory;
     this.servicesConfig      = servicesConfig;
     this.logger              = logger;
     this.authorizationConfig = authorizationConfig;
 }
Beispiel #16
0
        public static void RegisterUserAndRole(object user, List <string> roles)
        {
            string   ticket  = Tools.ToShortMD5(Guid.NewGuid().ToString("N"));
            DateTime expired = DateTime.Now.AddSeconds(AuthenticationConfig.GetTicketExpire());

            HttpContext.Current.Response.Headers.Add(AuthenticationConfig.AuthenticationString, ticket);
            if (user != null)
            {
                MemCache.Add(AuthenticationConfig.TicketKeyPrefix + ticket, user, expired);
            }
            if (roles != null && roles.Count > 0)
            {
                AuthorizationConfig.AddRoles(ticket, roles);
            }
        }
Beispiel #17
0
        static internal bool RequestRequiresAuthorization(HttpContext context)
        {
            if (context.SkipAuthorization)
            {
                return(false);
            }

            AuthorizationConfig settings = (AuthorizationConfig)context.GetConfig("system.web/authorization");

            // Check if the anonymous user is allowed
            if (_AnonUser == null)
            {
                _AnonUser = new GenericPrincipal(new GenericIdentity(String.Empty, String.Empty), new String[0]);
            }

            return(settings.IsUserAllowed(_AnonUser, context.Request.RequestType));
        }
Beispiel #18
0
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            AuthorizationConfig.RegisterOAuth(app);
            WebApiConfig.RegisterRoutes(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);

            WebAppConfig.RegisterRoutes(RouteTable.Routes);
            UnityConfig.RegisterComponents(config);
            SwaggerConfig.Register(config);

            AutoMapper.Mapper.Initialize(cfg => cfg.AddProfile <AutoMapperConfig>());

            Database.SetInitializer(new MigrateDatabaseToLatestVersion <FavBooksContext, FavBooks.DataAccess.Migrations.Configuration>());
        }
Beispiel #19
0
        private void DebugDataConfig()
        {
            BotConfig = new BotConfig()
            {
                IsDualMode = false,
                BotName    = "Valerabot",
                StreamName = "imshadowmafia",
                BotColor   = new BotColor()
                {
                    RbgColor = new System.Windows.Media.SolidColorBrush(Color.FromRgb(255, 0, 0)), Color = ChatColorPresets.Red
                }
            };

            Auth = new AuthorizationConfig()
            {
                BotAuth = new AuthorizationInstance()
                {
                    Tokens = new TwitchAuthResponse()
                    {
                        AccessToken = "51o0g399yiaqsab1vde59kpba4f685"
                    }
                },
                StreamerAuth = new AuthorizationInstance()
                {
                    Tokens = new TwitchAuthResponse()
                    {
                        AccessToken = "51o0g399yiaqsab1vde59kpba4f685"
                    }
                }
            };

            CoinConfig = new CoinSystemConfig()
            {
                StreamOfflineAccrualInterval = 1,
                StreamOnlineAccrualInterval  = 2,
                IsEnabled            = true,
                CoinsName            = "ShadowCoins",
                CoinSystemCustomMode = false,
                Unfollow             = 10,
                Follower             = 15,
                Subscriber           = 20,
            };
        }
Beispiel #20
0
        public SignInManager(IOptionsSnapshot <AuthorizationConfig> configOptions,
                             IHttpContextAccessor contextAccessor,
                             IAuthenticationSchemeProvider schemes)
        {
            if (configOptions == null)
            {
                throw new ArgumentNullException(nameof(configOptions));
            }
            if (contextAccessor == null)
            {
                throw new ArgumentNullException(nameof(contextAccessor));
            }
            if (schemes == null)
            {
                throw new ArgumentNullException(nameof(schemes));
            }

            _authorizationConfig = configOptions.Value;
            _contextAccessor     = contextAccessor;
            _schemes             = schemes;
        }
Beispiel #21
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddCors();
     services.AddMemoryCache();
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
     services.AddAuthorization(options => { options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build(); });
     services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters {
                                                                                                      ValidateIssuer = true, ValidIssuer = AuthorizationConfig.server, ValidateAudience = true, ValidAudience = AuthorizationConfig.issuer, ValidateLifetime = true, IssuerSigningKey = AuthorizationConfig.SymmetricSecurityKey(), ValidateIssuerSigningKey = true
                                                                                                  }; });
     services.AddDbContext <UsersIEP_dev01Context>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionStrings")));
 }
Beispiel #22
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="tokenProvider"></param>
 /// <param name="authorizationConfig"></param>
 public TokenService(ITokenProvider tokenProvider,
                     AuthorizationConfig authorizationConfig)
 {
     this.authorizationConfig = authorizationConfig;
     this.tokenProvider       = tokenProvider;
 }
Beispiel #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AuthController"/> class.
 /// </summary>
 /// <param name="authConfigOptions">The authentication configuration options.</param>
 protected AuthApiController(IOptions <AuthorizationConfig> authConfigOptions)
 {
     this._authConfig = authConfigOptions.Value;
     bearerAuthKeys   = this._authConfig.BearerAuthKeys;
 }
Beispiel #24
0
 public JwtService(IConfiguration configuration)
 {
     _config = new AuthorizationConfig();
     configuration.Bind(nameof(AuthorizationConfig).Replace("Config", null), _config);
 }
Beispiel #25
0
        /// <summary>
        /// Set all application config to default
        /// </summary>
        /// <param name="debugMode">if true then debug mode</param>
        public void DefaultConfig(bool debugMode = true)
        {
            //personal data
            if (debugMode)
            {
                DebugDataConfig();
            }
            else
            {
                BotConfig = new BotConfig()
                {
                    IsDualMode = false,
                    BotName    = "YouBotName",
                    StreamName = "YouStreamName",
                    BotColor   = new BotColor()
                    {
                        RbgColor = new System.Windows.Media.SolidColorBrush(Color.FromRgb(255, 0, 0)), Color = ChatColorPresets.Red
                    }
                };
                Auth = new AuthorizationConfig()
                {
                    BotAuth = new AuthorizationInstance()
                    {
                        Tokens = new TwitchAuthResponse()
                        {
                            AccessToken = "You need get oauth token"
                        }
                    },
                    StreamerAuth = new AuthorizationInstance()
                    {
                        Tokens = new TwitchAuthResponse()
                        {
                            AccessToken = "You need get oauth token"
                        }
                    }
                };
                CoinConfig = new CoinSystemConfig()
                {
                    StreamOfflineAccrualInterval = 1,
                    StreamOnlineAccrualInterval  = 1,
                    IsEnabled            = true,
                    CoinsName            = "Coins",
                    CoinSystemCustomMode = false,
                    Unfollow             = 5,
                    Follower             = 10,
                    Subscriber           = 20,
                };
            }


            Port = "8080";
            MiniChatConfig.ChatUsage            = true;
            MiniChatConfig.Topmost              = true;
            MiniChatConfig.IsLocked             = false;
            MiniChatConfig.ChatSettingsAndInput = true;
            MiniChatConfig.ChatPosition         = new Point(100, 200);
            MiniChatConfig.ChatSize             = new Size(400, 300);
            MiniChatConfig.BgColor              = Color.FromArgb(255, 239, 238, 241);


            PlayerConfig.Autoplay       = true;
            PlayerConfig.ChatPlaylistOn = true;

            PlayerConfig.IsUsingCoinSystem = true;
            PlayerConfig.CurrentSongNotify = true;

            PlayerConfig.SongPrice      = 10;
            PlayerConfig.SkipSongPrice  = 30;
            PlayerConfig.FirstSongPrice = 50;

            PlayerConfig.UnfollowRequestsPerHours   = 3;
            PlayerConfig.FollowerRequestsPerHours   = 6;
            PlayerConfig.SubscriberRequestsPerHours = 10;

            PlayerConfig.MinRequestRang = TwitchRangs.Unfollower;
        }
        private void ProcessProviderResult()
        {
            // Process the result from an auth provider in the request
            ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();

            if (String.IsNullOrEmpty(ProviderName))
            {
                Response.Redirect(FormsAuthentication.LoginUrl);
            }

            // Build the redirect url for OpenAuth verification
            var redirectUrl = "~/Account/RegisterExternalLogin.aspx";
            var returnUrl   = Request.QueryString["ReturnUrl"];

            if (!String.IsNullOrEmpty(returnUrl))
            {
                redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl);
            }

            // Verify the OpenAuth payload
            var authResult = OpenAuth.VerifyAuthentication(redirectUrl);

            ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
            if (!authResult.IsSuccessful)
            {
                Title = "External login failed";
                userNameForm.Visible = false;

                ModelState.AddModelError("Provider", String.Format("External login {0} failed.", ProviderDisplayName));

                // To view this error, enable page tracing in web.config (<system.web><trace enabled="true"/></system.web>) and visit ~/Trace.axd
                Trace.Warn("OpenAuth", String.Format("There was an error verifying authentication with {0})", ProviderDisplayName), authResult.Error);
                return;
            }

            // User has logged in with provider successfully
            // Check if user is already registered locally
            if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false))
            {
                //Roles cookie
                HttpCookie cookie = new HttpCookie("Paper.Roles", AuthorizationConfig.GetRoles(authResult.UserName));
                Page.Response.Cookies.Add(cookie);

                RedirectToReturnUrl();
            }

            // Store the provider details in ViewState
            ProviderName     = authResult.Provider;
            ProviderUserId   = authResult.ProviderUserId;
            ProviderUserName = authResult.UserName;

            // Strip the query string from action
            Form.Action = ResolveUrl(redirectUrl);

            if (User.Identity.IsAuthenticated)
            {
                //Roles cookie
                HttpCookie cookie = new HttpCookie("Paper.Roles", AuthorizationConfig.GetRoles(User.Identity.Name));
                Page.Response.Cookies.Add(cookie);

                // User is already authenticated, add the external login and redirect to return url
                OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name);
                RedirectToReturnUrl();
            }
            else
            {
                // User is new, ask for their desired membership name
                userName.Text = authResult.UserName;
            }
        }
        public void GetEdgeHubConfig_ValidInput_MappingIsCorrect()
        {
            var validator = new Mock <BrokerPropertiesValidator>();

            validator
            .Setup(v => v.ValidateAuthorizationConfig(It.IsAny <AuthorizationProperties>()))
            .Returns(new List <string>());

            var routeFactory = new EdgeRouteFactory(new Mock <IEndpointFactory>().Object);
            var configParser = new EdgeHubConfigParser(routeFactory, validator.Object);

            EdgeHubDesiredProperties properties = ConfigTestData.GetTestData();

            // act
            EdgeHubConfig result = configParser.GetEdgeHubConfig(properties);

            // assert
            validator.Verify(v => v.ValidateAuthorizationConfig(properties.BrokerConfiguration.Authorizations), Times.Once());

            Assert.Equal("1.2.0", result.SchemaVersion);
            AuthorizationConfig authzConfig = result
                                              .BrokerConfiguration
                                              .Expect(() => new InvalidOperationException("missing broker config"))
                                              .Authorizations
                                              .Expect(() => new InvalidOperationException("missing authorization config"));

            Assert.Equal(3, authzConfig.Statements.Count);

            var result0 = authzConfig.Statements[0];

            Assert.Equal(Effect.Deny, result0.Effect);
            Assert.Equal(2, result0.Identities.Count);
            Assert.Equal("device_1", result0.Identities[0]);
            Assert.Equal("device_3", result0.Identities[1]);
            Assert.Equal(1, result0.Operations.Count);
            Assert.Equal("mqtt:publish", result0.Operations[0]);
            Assert.Equal(2, result0.Resources.Count);
            Assert.Equal("system/alerts/+", result0.Resources[0]);
            Assert.Equal("core/#", result0.Resources[1]);

            var result1 = authzConfig.Statements[1];

            Assert.Equal(Effect.Allow, result1.Effect);
            Assert.Equal(2, result1.Identities.Count);
            Assert.Equal("device_1", result1.Identities[0]);
            Assert.Equal("device_3", result1.Identities[1]);
            Assert.Equal(2, result1.Operations.Count);
            Assert.Equal("mqtt:publish", result1.Operations[0]);
            Assert.Equal("mqtt:subscribe", result1.Operations[1]);
            Assert.Equal(2, result1.Resources.Count);
            Assert.Equal("topic/a", result1.Resources[0]);
            Assert.Equal("topic/b", result1.Resources[1]);

            var result2 = authzConfig.Statements[2];

            Assert.Equal(Effect.Allow, result2.Effect);
            Assert.Equal(1, result2.Identities.Count);
            Assert.Equal("device_2", result2.Identities[0]);
            Assert.Equal(2, result2.Operations.Count);
            Assert.Equal("mqtt:publish", result2.Operations[0]);
            Assert.Equal("mqtt:subscribe", result2.Operations[1]);
            Assert.Equal(2, result2.Resources.Count);
            Assert.Equal("topic1", result2.Resources[0]);
            Assert.Equal("topic2", result2.Resources[1]);
        }
        string GenerateToken(string username, double lifetime)
        {
            Claim[]          claims           = new Claim[] { new Claim(ClaimsIdentity.DefaultNameClaimType, username) };
            ClaimsIdentity   claimsIdentity   = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
            JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(issuer: AuthorizationConfig.server, audience: AuthorizationConfig.issuer, notBefore: DateTime.UtcNow, claims: claimsIdentity.Claims, expires: DateTime.UtcNow.Add(TimeSpan.FromMinutes(lifetime)), signingCredentials: new SigningCredentials(AuthorizationConfig.SymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));

            return(new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken));
        }
Beispiel #29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(x => x.EnableEndpointRouting = false);

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var appInsightsConfig = new AppInsightsConfig
            {
                InstrumentationKey = Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]
            };

            services.AddSingleton(appInsightsConfig);
            services.AddApplicationInsightsTelemetry(appInsightsConfig.InstrumentationKey);

            var apiConfig = new ApiConfig
            {
                BaseUrl           = Configuration["ApiUrl"],
                MrcApiUrl         = Configuration["MrcApiUrl"],
                DocEntitiesApiUrl = Configuration["DocEntitiesApiUrl"],
                WidgetApiUrl      = Configuration["WidgetApiUrl"]
            };

            services.AddSingleton(apiConfig);

            var orgConfig = new OrganizationConfig
            {
                Logo = Configuration["OrganizationLogo"],
                Name = Configuration["OrganizationName"],
                Url  = Configuration["OrganizationWebSiteUrl"],
            };

            services.AddSingleton(orgConfig);

            var authorizationConfig = new AuthorizationConfig
            {
                AuthorityUri      = Configuration["AuthorityUri"],
                ResourceUrl       = Configuration["ResourceUrl"],
                RedirectUrl       = Configuration["RedirectUrl"],
                PowerBIApiUrl     = Configuration["PowerBIApiUrl"],
                ApplicationId     = Configuration["ApplicationId"],
                LoggingRequestUrl = Configuration["LoggingRequestUrl"]
            };

#if DEBUG
            authorizationConfig.RedirectUrl = Configuration["RedirectUrlLocalhost"];
#endif
            services.AddSingleton(authorizationConfig);

            var appConfig = new AppConfig
            {
                ApiConfig     = apiConfig,
                AppInsights   = appInsightsConfig,
                Organization  = orgConfig,
                Authorization = authorizationConfig,
                Customizable  = Configuration["Customizable"].Equals("true", StringComparison.InvariantCultureIgnoreCase)
            };
            services.AddSingleton(appConfig);

            services.AddSingleton <IFileProvider>(new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Beispiel #30
0
        public void ConfigureServices(IServiceCollection services)
        {
            // IoC para autoMapper
            services.AddAutoMapper();

            // Obtendo parametros AuthorizationConfigs do appsettings.json
            services.Configure <AuthorizationConfigs>(Configuration.GetSection("AuthorizationConfigs"));

            // Configuração da internacionalização
            services.AddJsonLocalization(options => options.ResourcesPath = "Internationalization");

            WRIoC.Register(services);

            services.AddSingleton <IConfiguration>(Configuration);

            services.AddScoped <IUsuarioBase, UsuarioBase>();

            services.AddDbContext <WRContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
                                              .ConfigureWarnings(x => x.Ignore(RelationalEventId.AmbientTransactionWarning)));

            // Configurando ServiceLocator
            ServiceLocator.Init(services.BuildServiceProvider());

            // Configuração AddIdentityServer
            services.AddIdentityServer()
            .AddSigningCredential(AuthorizationConfig.GetCertificate())
            .AddInMemoryApiResources(AuthorizationConfig.GetApiResources())
            .AddInMemoryClients(AuthorizationConfig.GetClients())
            .AddResourceOwnerValidator <GrantValidator>();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            // Configuração Client
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options => AuthorizationConfig.GetServerAutentication(options));


            CorsAuthorization.SetAllowAll(services);

            services.AddCors(options =>
            {
                options.AddPolicy("ALL", builder => builder
                                  .AllowAnyOrigin()
                                  .AllowAnyHeader()
                                  .AllowAnyMethod()
                                  .AllowCredentials());
            });

            services.AddMvcCore().AddAuthorization();

            var csvFormatterOptions = new CsvFormatterOptions();

            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(DomainExceptionFilter));
                options.ModelBinderProviders.Insert(0, new ProviderModelBinder());
                options.RespectBrowserAcceptHeader = true;
                options.InputFormatters.Add(new CsvInputFormatter(csvFormatterOptions));
                options.OutputFormatters.Add(new CsvOutputFormatter(csvFormatterOptions));
                options.FormatterMappings.SetMediaTypeMappingForFormat("csv", "text/csv");
            })
            .AddCsvSerializerFormatters()
            .AddViewLocalization()
            .AddJsonOptions(x => SetDefaultSerializerSettings(x.SerializerSettings))
            .AddApplicationPart(typeof(Startup).Assembly);
        }