Esempio n. 1
0
        /// <summary>
        /// Set up a mapping function to get the correct EF provider
        /// </summary>
        /// <param name="databaseTypeEnum"></param>
        /// <param name="connectionString"></param>
        /// <param name="migrationsAssembly"></param>
        /// <param name="contextOptionBuilder"></param>
        private void SetupEFProvider(EFRepository.DatabaseTypeEnum databaseTypeEnum, string connectionString, string migrationsAssembly, DbContextOptionsBuilder contextOptionBuilder)
        {
            switch (databaseTypeEnum)
            {
            case EFRepository.DatabaseTypeEnum.mysql:
                contextOptionBuilder.UseMySql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
                break;

            case EFRepository.DatabaseTypeEnum.mssql:
                contextOptionBuilder.UseSqlServer(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
                break;

            default:
                throw new ArgumentException();
            }
        }
Esempio n. 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IdentityModelEventSource.ShowPII = true;

            // this is for ef migration file generation
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            string connectionString = Configuration.GetConnectionString("Database");

            #region Setup Identity Server
            string database_type = Configuration["database_provider"];
            EFRepository.DatabaseTypeEnum databaseType = EFRepository.GetDatabaseTypeEnum(database_type);

            // use mysql to interact with customized identity db context
            services.AddDbContext <EFApplicationDbContext>(options =>
                                                           SetupEFProvider(databaseType, connectionString, migrationsAssembly, options));

            // use customized identity user in identity & take application db context as the db for entity framework
            services.AddIdentity <EFApplicationUser, EFApplicationRole>()
            .AddEntityFrameworkStores <EFApplicationDbContext>()
            .AddDefaultTokenProviders();


            // Configure asp.net Identity settings
            services.Configure <IdentityOptions>(options =>
            {
                // Password settings
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireLowercase       = false;
            });



            // Add identity server for OAuth 2.0
            services.AddTransient <IProfileService, IdentityProfileService>(); // customized IProfile servoce

            services.AddIdentityServer(options =>
            {
                // set up the login page url
                options.UserInteraction.LoginUrl  = "/login";
                options.UserInteraction.LogoutUrl = "/logout";
            })
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = b => SetupEFProvider(databaseType, connectionString, migrationsAssembly, b);
            })
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = b => SetupEFProvider(databaseType, connectionString, migrationsAssembly, b);
                options.EnableTokenCleanup = true;
            })
            .AddAspNetIdentity <EFApplicationUser>()       // use asp.net identity user as the user of identity server
            .AddSigningCredential(GetCertificate())        // use the certificate so that the token is still valid after application is rebooted
            .AddProfileService <IdentityProfileService>(); // add the service of customization of token
            #endregion

            #region Setup JWT Bearer Authentication
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            // add authentication using bearer
            services.AddAuthentication(options =>
            {
                // this is for telling asp.net core identity that the user has been logined
                options.DefaultSignInScheme  = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                // this is for authenticating when calling API
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.Authority = Configuration["auth_url"];
                options.Audience  = CommonConstant.AGSIdentityScopeConstant;
                //options.TokenValidationParameters = new TokenValidationParameters()
                //{
                //    ValidateIssuerSigningKey = false,
                //    d
                //};
                options.BackchannelHttpHandler = GetJWTBearerTokenHandler();
                options.RequireHttpsMetadata   = false;
            });
            #endregion

            // add controllers
            services.AddControllersWithViews();
            services.AddRazorPages();

            // Add API Versioning
            services.AddApiVersioning(config =>
            {
                // Specify the default API Version as 1.0
                config.DefaultApiVersion = new ApiVersion(1, 0);
                // If the client hasn't specified the API version in the request, use the default API version number
                config.AssumeDefaultVersionWhenUnspecified = true;
            });

            // add repository object
            services.AddHttpContextAccessor();
            services.AddTransient <IAuthService, IdentityAuthService>();
            services.AddTransient(typeof(FunctionClaimsHelper));
            services.AddTransient(typeof(GroupsHelper));
            services.AddTransient(typeof(UsersHelper));
            services.AddTransient <IRepository, EFRepository>();
            services.AddTransient <IFunctionClaimsRepository, EFFunctionClaimsRepository>();
            services.AddTransient <IGroupsRepository, EFGroupsRepository>();
            services.AddTransient <IUsersRepository, EFUsersRepository>();

            // for data initialization
            services.AddTransient <IDataSeed, EFDataSeed>();

            services.AddAuthorization(options =>
            {
                SetupAuthentticaionPolicy(options);
            });


            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "v1.0",
                    Title       = "AGS Identity API",
                    Description = "AGS Identity API v1"
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);

                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. <br/>" +
                                  "Enter 'Bearer' [space] and then your token in the text input below. <br/>" +
                                  "Example: 'Bearer 12345abcdef'",
                    Name   = "Authorization",
                    In     = ParameterLocation.Header,
                    Type   = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer"
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            },
                            Scheme = "oauth2",
                            Name   = "Bearer",
                            In     = ParameterLocation.Header,
                        },
                        new List <string>()
                    }
                });
            });
        }