I am using asp.net core web application, I want to restrict the login only to particular domains like @domain.com , I followed few steps involved in this video https://www.youtube.com/watch?v=eCQdo5Njeew for google external authentication which is the older version and I followed this documentation https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins?tabs=aspnetcore2x The oauth is working but I want to restrict access to particular domain only, how to do this?
Asked
Active
Viewed 1,388 times
2
-
Related question: https://stackoverflow.com/questions/10858813/restrict-login-email-with-google-oauth2-0-to-specific-domain-name It says you need an hd parameter on your challenge. It also implies it requires OpenIdConnect, but Google's APIs have a lot of overlap. You can add this parameter by tacking on `?hd=mydomain` to Options.AuthorizationEndpoint. Or use the OnRedirectToAuthorizationEndpoint event. – Tratcher Feb 02 '18 at 04:34
1 Answers
2
Restricting the domain upon login from OAuth is not reliable enough. I suggest you create a custom security policy as explained in Tackle more complex security policies for your ASP.NET Core app.
First, you need a requirement:
using Microsoft.AspNetCore.Authorization;
public class DomainRequirement : IAuthorizationRequirement
{
public string Domain { get; }
public DomainRequirement(string domain)
{
Domain = domain;
}
}
Then, you need a handler for this requirement:
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
public class DomainHandler : AuthorizationHandler<DomainRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
DomainRequirement requirement)
{
var emailAddressClaim = context.User.FindFirst(claim => claim.Type == ClaimTypes.Email);
if (emailAddressClaim != null && emailAddressClaim.Value.EndsWith($"@{requirement.Domain}"))
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
With those in place, you can add a new authorization policy in Startup.cs so that ASP.NET Core is aware of it:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthorization(options =>
{
options.AddPolicy("CompanyStaffOnly", policy => policy.RequireClaim(ClaimTypes.Email).AddRequirements(new DomainRequirement("company.com")));
});
// ...
}
Finally, you can refer to this policy when adding an [Authorize] on your controller actions:
[Authorize(Policy = "CompanyStaffOnly")]
public IActionResult SomeAction()
{
// ...
}
See also How to add global AuthorizeFilter or AuthorizeAttribute in ASP.NET Core? if you want to globally apply this policy.
Julien Poulin
- 12,737
- 10
- 51
- 76