简体   繁体   English

Web API中具有令牌的Azure AD和基于组的授权

[英]Azure AD and Group-based authorization with token in Web API

In my Azure AD I have user and group. 在我的Azure AD中,我有用户和组。 I want to give an access to users according to a group the belong to. 我想根据所属的组为用户提供访问权限。

I successfully implement it in ASP.NET MVC application. 我在ASP.NET MVC应用程序中成功实现了它。 How I set up group claims: 我如何设置团体索赔:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
        .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddSpaStaticFiles(c => { c.RootPath = "ClientApp/dist";});

     services.AddAuthorization(options =>
    {
        options.AddPolicy("Admins",
            policyBuilder =>
            {
                policyBuilder.RequireClaim("groups",
                    Configuration.GetValue<string>("AzureSecurityGroup:AdminObjectId"));
            });
    });

    services.AddAuthorization(options =>
    {
        options.AddPolicy("Employees",
            policyBuilder =>
            {
                policyBuilder.RequireClaim("groups",
                    Configuration.GetValue<string>("AzureSecurityGroup:EmployeeObjectId"));
            });
    });

    services.AddAuthorization(options =>
    {
        options.AddPolicy("Managers",
            policyBuilder => policyBuilder.RequireClaim("groups", Configuration.GetValue<string>("AzureSecurityGroup:ManagerObjectId")));
    });

    services.Configure<AzureADOptions>(Configuration.GetSection("AzureAd"));
}

And if I want to restrict access for non-admin user to Contacts page I do this: 如果我想限制非管理员用户对“联系人”页面的访问,请执行以下操作:

public class HomeController : Controller
{
    [Authorize(Policy = "Admins")]
    public IActionResult Contact()
    {
        ViewData["Message"] = "Your contact page.";

        return View();
    }
}

It works Now the idea is to create an web api controller and restrict access to some of the method. 它可以正常工作现在的想法是创建一个Web api控制器并限制对某些方法的访问。

//[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] {"value1", "value2"};
    }

    // GET api/values/5
    [Authorize(Policy = "Admins")]
    [HttpGet("{id}")]
    public ActionResult<string> Get(int id)
    {
        return "value";
    }
}

I use postman. 我用邮递员。 I get an access token: 我得到一个访问令牌:

POST https://login.microsoftonline.com/ {tenant_id}/oauth2/token POST https://login.microsoftonline.com/ {tenant_id} / oauth2 / token

then send 然后发送

GET https://localhost/api/values/1 获取https:// localhost / api / values / 1

with header Authorization and value Bearer {token} but get Unauthorized access (401). 具有标头Authorization和值Bearer {token},但获得未经授权的访问(401)。 (Unprotected https://localhost/api/values works as expected though). (但不受保护的https:// localhost / api / values可以正常工作)。 I suspect that I pass wrong token, I check it on https://jwt.io/ and it does not contain information about a group the user belongs to. 我怀疑传递了错误的令牌,我在https://jwt.io/上对其进行了检查,它不包含有关用户所属组的信息。 Should I configure it in the code another way? 是否应该以其他方式在代码中进行配置? Thanks 谢谢

Update 1 (decoded token): 更新1(已解码令牌):

{
  "typ": "JWT",
  "alg": "RS256",
  "x5t": "nbCwW11w3XkB-xUaXwKRSLjMHGQ",
  "kid": "nbCwW11w3XkB-xUaXwKRSLjMHGQ"
}.{
  "aud": "00000002-0000-0000-c000-000000000000",
  "iss": "https://sts.windows.net/xxxxxxxx-1835-453d-a552-28feda08393e/",
  "iat": 1544770435,
  "nbf": 1544770435,
  "exp": 1544774335,
  "aio": "42RgYPjkVuw2Z/fJtp+RF/mUp7Z5AQA=",
  "appid": "963418bb-8a31-4c47-bc91-56b6e51181dc",
  "appidacr": "1",
  "idp": "https://sts.windows.net/xxxxxxxx-1835-453d-a552-28feda08393e/",
  "oid": "0dfb0f07-b6e1-4318-ba33-066e1fc3c0ac",
  "sub": "0dfb0f07-b6e1-4318-ba33-066e1fc3c0ac",
  "tenant_region_scope": "EU",
  "tid": "xxxxxxxx-1835-453d-a552-28feda08393e",
  "uti": "cxlefO0ABkimo2z-7L0IAA",
  "ver": "1.0"
}.[Signature]

When using grant_type is client_credentials , that means you are using the client credentials flow to acquire access token for accessing the resource : 当使用grant_typeclient_credentials ,这意味着您正在使用客户机凭证流来获取用于访问资源的访问令牌:

https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-oauth2-client-creds-grant-flow https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-oauth2-client-creds-grant-flow

The OAuth 2.0 Client Credentials Grant Flow permits a web service (confidential client) to use its own credentials instead of impersonating a user, to authenticate when calling another web service. OAuth 2.0客户端凭据授予流程允许Web服务(机密客户端)使用自己的凭据而不是模拟用户,从而在调用另一个Web服务时进行身份验证。 In this scenario, the client is typically a middle-tier web service, a daemon service, or web site. 在这种情况下,客户端通常是中间层Web服务,守护程序服务或网站。

In this scenario , the client use its own credentials instead of impersonating a user , no user information/identity is included in this scenario. 在这种情况下,客户端使用自己的凭据而不是模拟用户,在这种情况下不包括用户信息/身份。 You should use Code Grant Flow to authorize access to web applications and web APIs using user's identity : 您应该使用代码授予流来使用用户身份授权对Web应用程序和Web API的访问:

https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Azure AD身份验证令牌使Web API授权失败 - Azure AD authentication token fails web api authorization 基于令牌的授权Web API - Token Based Authorization Web API ASP.NET Core 2.0 Web API Azure Ad v2令牌授权无效 - ASP.NET Core 2.0 Web API Azure Ad v2 Token Authorization not working Azure AD 带有用于 Web API 的不记名令牌身份验证的 AD 无法正常工作,抛出错误,因为“此请求的授权已被拒绝”。 - Azure AD with Bearer token authentication for Web API not working throwing error as “Authorization has been denied for this request.” 在 Web API 上验证 Azure AD ID 令牌 - Validating Azure AD ID Token on Web API 如何在 .Net 核心 Web API 中进行 Azure AD 组授权? - How to do Azure AD groups authorization in .Net core web API? 带有 JWT 令牌的 Azure AD 多租户、.Net Core Web API - Azure AD Multi Tenant ,.Net Core Web API with JWT Token Azure AD 在 Web API 中使用来自客户端应用程序的令牌 - Azure AD using token from client application in Web API 如何使用 C# WEBAPI(基于令牌).netcore 进行身份验证和授权 Azure AD 应用程序 - How to do Authentication & Authorization Azure AD App, using C# WEBAPI (token based) .netcore 如何根据Azure AD组进行授权? - How to do Authorization based on Azure AD groups?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM