如何仅在asp.net核心Web应用程序中将google oauth 2.0限制为特定域? [英] How to restrict google oauth 2.0 to particular domain only in asp.net core web application?
问题描述
我正在使用asp.net核心Web应用程序,我想仅将登录限制为特定域,例如@ domain.com,我按照此视频中涉及的几个步骤进行操作 https://www.youtube.com/watch?v=eCQdo5Njeew 适用于Google外部身份验证是较早的版本,我遵循了本文档 https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/social/google-logins?tabs=aspnetcore2x oauth可以正常工作,但是我只想限制对特定域的访问,该怎么做?
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://docs.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?
推荐答案
从OAuth登录后限制域是不够可靠的.我建议您按照解决更复杂的安全策略中的说明创建自定义安全策略.您的ASP.NET Core应用.
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;
}
}
有了这些权限,您可以在Startup.cs
中添加新的授权策略,以便ASP.NET Core可以了解它:
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")));
});
// ...
}
最后,当在控制器操作上添加[Authorize]
时,您可以参考此策略:
Finally, you can refer to this policy when adding an [Authorize]
on your controller actions:
[Authorize(Policy = "CompanyStaffOnly")]
public IActionResult SomeAction()
{
// ...
}
另请参阅如何在ASP.NET Core中添加全局AuthorizeFilter
或AuthorizeAttribute
?在全球范围内应用此政策.
See also How to add global AuthorizeFilter
or AuthorizeAttribute
in ASP.NET Core? if you want to globally apply this policy.
这篇关于如何仅在asp.net核心Web应用程序中将google oauth 2.0限制为特定域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!