Beispiel #1
0
        public EmbedIOAuthServer(Uri baseUri, int port, Assembly resourceAssembly, string resourcePath)
        {
            BaseUri = baseUri;
            Port    = port;

            _webServer = new WebServer(port)
                         .WithModule(new ActionModule("/", HttpVerbs.Get, (ctx) =>
            {
                var query = ctx.Request.QueryString;

                AuthorizationCodeReceived?.Invoke(this, new AuthorizationCodeResponse(query["code"] !)
                {
                    State = query["state"]
                });
        public EmbedIOAuthServer(Uri baseUri, int port, Assembly resourceAssembly, string resourcePath)
        {
            Ensure.ArgumentNotNull(baseUri, nameof(baseUri));

            BaseUri = baseUri;
            Port    = port;

            _webServer = new WebServer(port)
                         .WithModule(new ActionModule("/", HttpVerbs.Post, (ctx) =>
            {
                var query = ctx.Request.QueryString;
                if (query["error"] != null)
                {
                    throw new AuthException(query["error"], query["state"]);
                }

                var requestType = query.Get("request_type");
                if (requestType == "token")
                {
                    ImplictGrantReceived?.Invoke(this, new ImplictGrantResponse(
                                                     query["access_token"], query["token_type"], int.Parse(query["expires_in"])
                                                     )
                    {
                        State = query["state"]
                    });
                }
                if (requestType == "code")
                {
                    AuthorizationCodeReceived?.Invoke(this, new AuthorizationCodeResponse(query["code"])
                    {
                        State = query["state"]
                    });
                }

                return(ctx.SendStringAsync("OK", "text/plain", Encoding.UTF8));
            }))
                         .WithEmbeddedResources("/auth_assets", Assembly.GetExecutingAssembly(), AssetsResourcePath)
                         .WithEmbeddedResources(baseUri.AbsolutePath, resourceAssembly, resourcePath);
        }
Beispiel #3
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            // preserve OIDC state in cache (solves problems with AAD and URL lenghts)
            services.AddOidcStateDataFormatterCache();
            // cookie policy to deal with temporary browser incompatibilities
            services.AddSameSiteCookiePolicy();

            // configures IIS out-of-proc settings (see https://github.com/aspnet/AspNetCore/issues/14882)
            services.Configure <IISOptions>(iis =>
            {
                iis.AuthenticationDisplayName = "Windows";
                iis.AutomaticAuthentication   = false;
            });

            // configures IIS in-proc settings
            services.Configure <IISServerOptions>(iis =>
            {
                iis.AuthenticationDisplayName = "Windows";
                iis.AutomaticAuthentication   = false;
            });

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

            services.AddIdentity <ApplicationUser, IdentityRole>(options => {
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 2;
                options.Lockout.AllowedForNewUsers      = true;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            var connectionString   = Configuration.GetConnectionString("Configuration");
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;


            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;

                options.UserInteraction = new UserInteractionOptions
                {
                    LogoutUrl = "/Account/Logout",
                    LoginUrl  = "/Account/Login",
                    LoginReturnUrlParameter = "returnUrl"
                };
            })
                          .AddAspNetIdentity <ApplicationUser>()
                          // this adds the config data from DB (clients, resources)
                          .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(connectionString,
                                                                  sql => sql.MigrationsAssembly(migrationsAssembly));
            })
                          // this adds the operational data from DB (codes, tokens, consents)
                          .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(connectionString,
                                                                  sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup   = true;
                options.TokenCleanupInterval = 30;
            });


            // not recommended for production - you need to store your key material somewhere secure
            builder.AddDeveloperSigningCredential();

            services.AddAuthentication()
            //.AddGoogle(options =>
            //{
            //    // register your IdentityServer with Google at https://console.developers.google.com
            //    // enable the Google+ API
            //    // set the redirect URI to http://localhost:5000/signin-google
            //    options.ClientId = "copy client ID from Google here";
            //    options.ClientSecret = "copy client secret from Google here";
            //})
            .AddOpenIdConnect("AAD", "Azure Active Directory", options =>
            {
                options.SignInScheme              = IdentityConstants.ExternalScheme;
                options.SignOutScheme             = IdentityServerConstants.SignoutScheme;
                options.Authority                 = Globals.Authority;
                options.ClientId                  = Globals.ClientId;
                options.ClientSecret              = Globals.ClientSecret;
                options.ResponseType              = OpenIdConnectResponseType.CodeIdToken;
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = false,
                    NameClaimType  = "name",
                    RoleClaimType  = "role"
                };

                options.Events.OnAuthorizationCodeReceived =
                    async(ctx) => await AuthorizationCodeReceived.CodeRedemptionAsync(ctx);
                options.GetClaimsFromUserInfoEndpoint = true;
                options.SaveTokens = true;
            });

            //services.UseAdminUI();
            ////services.AddScoped<IdentityExpressDbContext, SqlServerIdentityDbContext>(sp => new SqlServerIdentityDbContext(Configuration.GetConnectionString("Users")));
            //services.AddScoped<IdentityExpressDbContext, SqlServerIdentityDbContext>();
        }