Reputation: 57
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?
Upvotes: 2
Views: 1762
Reputation: 13025
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.
Upvotes: 2