4

Is it possible, with the boilerplate Google OAuth code a fresh MVC project generates, to restrict the users who can create accounts.

i.e. as standard anyone with a Google account can create an account on the website. I want to restrict account creation to a pre-authorised list of email addresses - effectively a whitelist.

Before I write any custom code, is this requirement facilitated in the standard, out-of-the-box login framework?

Pseudonymous
  • 839
  • 5
  • 13
  • 1
    You can try restricting by domain in your request, take a look at this: http://stackoverflow.com/a/11001585/4628087 – johnster Jul 17 '15 at 15:57

1 Answers1

4

I did this by changing these two lines in the boilerplate AccountController (forgive the rough code),

Old:

            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Hometown = model.Hometown };
            var result = await UserManager.CreateAsync(user);

New:

            var user = new ApplicationUser { UserName = info.Email, Email = info.Email, Hometown = model.Hometown };
            IdentityResult result = null;
            if (!allowedUsers.Contains(info.Email))
            {
                result = IdentityResult.Failed("User is not in permitted list");
            }
            else
            {
                result = await UserManager.CreateAsync(user);
            }

Also, the (at first commented-out) OAuth stuff in Startup.Auth does not request email addresses, so you'll need to add this Scope bit as well - otherwise info.Email will be null:

        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = "",
            ClientSecret = "",
            Scope = { "email" }
        });

Each OAuth provider has different scope items, e.g., Microsoft names email "wl.emails" when using Scope in MicrosoftAccountAuthenticationOptions.

user224567893
  • 636
  • 4
  • 18
  • 28
makhdumi
  • 1,308
  • 11
  • 35
  • Can you please explain why you are using `UserName = info.Email, Email = info.Email` instead of just `UserName = model.Email, Email = model.Email`. Why use `info` instead of `model`, since `model` also has the `Email` property? – user224567893 Oct 21 '16 at 00:43
  • @user224567893 IIRC `model.Email` comes from the request by the user and `info.Email` comes from the OAuth provider. – makhdumi Oct 21 '16 at 14:54
  • Where does the info object come from in this code sample? What type of object is it? – Dbloom Feb 21 '17 at 23:01