Example #1
0
        //[EnableCors("CorsPolicy")]
        public async Task <Dictionary <string, string> > GetAsync()
        {
            var userData = new Dictionary <string, string>();
            var user     = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            _context.Entry(user)
            .Reference(m => m.Measurement)
            .Load();

            var measurement = user.Measurement;

            _context.Entry(measurement)
            .Reference(g => g.Gender)
            .Load();

            var gender = measurement.Gender;

            if (User.HasClaim(OpenIddictConstants.Claims.Scope, CustomScopes.Name()))
            {
                userData.Add("Name", user.Name);
            }
            if (User.HasClaim(OpenIddictConstants.Claims.Scope, CustomScopes.Gender()))
            {
                userData.Add("Gender", gender.Sex);
            }
            if (User.HasClaim(OpenIddictConstants.Claims.Scope, OpenIddictConstants.Scopes.Email))
            {
                userData.Add("Email", user.Email);
                userData.Add("IsEmailConfirmed", user.EmailConfirmed.ToString());
            }
            if (User.HasClaim(OpenIddictConstants.Claims.Scope, CustomScopes.Measurements()))
            {
                var dataMeasurements = typeof(Measurement).GetProperties().Where(
                    prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute)));
                foreach (var u in dataMeasurements)
                {
                    userData.Add(u.Name, u.GetValue(measurement)?.ToString() ?? "null");
                }
            }


            return(userData);
        }
Example #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            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;
            });

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

                // Register the entity sets needed by OpenIddict.
                // Note: use the generic overload if you need
                // to replace the default OpenIddict entities.
                options.UseOpenIddict();
            });

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();



            services.AddAuthentication();


            // Configure Identity to use the same JWT claims as OpenIddict instead
            // of the legacy WS-Federation claims it uses by default (ClaimTypes),
            // which saves you from doing the mapping in your authorization controller.
            services.Configure <IdentityOptions>(options =>
            {
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.UserIdClaimType   = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.RoleClaimType     = OpenIdConnectConstants.Claims.Role;
            });


            // Register the OpenIddict services.
            services.AddOpenIddict()
            .AddCore(options =>
            {
                // Configure OpenIddict to use the Entity Framework Core stores and entities.
                options.UseEntityFrameworkCore()
                .UseDbContext <ApplicationDbContext>();
            })

            .AddServer(options =>
            {
                // Register the ASP.NET Core MVC binder used by OpenIddict.
                // Note: if you don't call this method, you won't be able to
                // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
                options.UseMvc();

                // Enable the authorization, logout, token and userinfo endpoints.
                options.EnableAuthorizationEndpoint("/connect/authorize")
                .EnableLogoutEndpoint("/connect/logout")
                .EnableTokenEndpoint("/connect/token")
                .EnableUserinfoEndpoint("/api/userinfo");

                // Mark the "email", "profile" and "roles" scopes as supported scopes.
                options.RegisterScopes(OpenIdConnectConstants.Scopes.Email,
                                       OpenIdConnectConstants.Scopes.Profile,
                                       OpenIddictConstants.Scopes.Roles,
                                       CustomScopes.Measurements(),
                                       CustomScopes.Gender(),
                                       CustomScopes.Name());

                // Note: the Mvc.Client sample only uses the authorization code flow but you can enable
                // the other flows if you need to support implicit, password or client credentials.
                options.AllowAuthorizationCodeFlow();

                // When request caching is enabled, authorization and logout requests
                // are stored in the distributed cache by OpenIddict and the user agent
                // is redirected to the same page with a single parameter (request_id).
                // This allows flowing large OpenID Connect requests even when using
                // an external authentication provider like Google, Facebook or Twitter.
                options.EnableRequestCaching();

                // During development, you can disable the HTTPS requirement.
                options.DisableHttpsRequirement();

                // Accept token requests that don't specify a client_id.
                // options.AcceptAnonymousClients();
            })

            .AddValidation();

            //Adding google as authentication option
            // replace id and secrete.
            services.AddAuthentication()
            .AddGoogle(options =>
            {
                options.ClientId     = "560027070069-37ldt4kfuohhu3m495hk2j4pjp92d382.apps.googleusercontent.com";
                options.ClientSecret = "n2Q-GEw9RQjzcRbU3qhfTj8f";
            });
        }
Example #3
0
        public void Configuration(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);

            app.Map("/identity", idsrvApp =>
            {
                var corsPolicyService = new DefaultCorsPolicyService()
                {
                    AllowAll = true
                };

                var defaultViewServiceOptions        = new DefaultViewServiceOptions();
                defaultViewServiceOptions.CacheViews = false;

                var idServerServiceFactory = new IdentityServerServiceFactory()
                                             .UseInMemoryClients(CustomClients.Get())
                                             .UseInMemoryScopes(CustomScopes.Get());
                //.UseInMemoryUsers(CustomUsers.Get());

                idServerServiceFactory.CorsPolicyService = new
                                                           Registration <IdentityServer3.Core.Services.ICorsPolicyService>(corsPolicyService);

                idServerServiceFactory.ConfigureDefaultViewService(defaultViewServiceOptions);

                idServerServiceFactory.Register(new Registration <ApplicationDbContext>());
                idServerServiceFactory.Register(new Registration <UserStore <ApplicationUser> >(resolver =>
                {
                    return(new UserStore <ApplicationUser>(resolver.Resolve <ApplicationDbContext>()));
                }));
                idServerServiceFactory.Register(new Registration <UserManager <ApplicationUser> >(resolver =>
                {
                    return(new ApplicationUserManager(resolver.Resolve <UserStore <ApplicationUser> >()));
                }));

                idServerServiceFactory.UserService = new Registration <IUserService, CustomUserService>();

                var options = new IdentityServerOptions
                {
                    Factory = idServerServiceFactory,

                    // Just for Angular 2 App testing.
                    RequireSsl = false,

                    SiteName              = "TripCompany Security Token Service",
                    SigningCertificate    = LoadCertificate(),
                    IssuerUri             = DBSP.RememberMe.Identity.Constants.TripGalleryIssuerUri,
                    PublicOrigin          = DBSP.RememberMe.Identity.Constants.TripGallerySTSOrigin,
                    AuthenticationOptions = new AuthenticationOptions()
                    {
                        EnablePostSignOutAutoRedirect = true,
                        LoginPageLinks = new List <LoginPageLink>()
                        {
                            new LoginPageLink()
                            {
                                Type = "createaccount",
                                Text = "Create a new account",
                                Href = "~/createuseraccount"
                            }
                        }
                    },
                    CspOptions = new CspOptions()
                    {
                        Enabled = false
                                  // once available, leave Enabled at true and use:
                                  // FrameSrc = "https://localhost:44318 https://localhost:44316"
                                  // or
                                  // FrameSrc = "*" for all URI's.
                    }
                };
                idsrvApp.UseIdentityServer(options);
            });
        }