Web API中具有令牌的Azure AD和基于组的授权 [英] Azure AD and Group-based authorization with token in Web API

查看:59
本文介绍了Web API中具有令牌的Azure AD和基于组的授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Azure AD中,我有用户和组.我想根据所属的组为用户提供访问权限.

In my Azure AD I have user and group. I want to give an access to users according to a group the belong to.

我在ASP.NET MVC应用程序中成功实现了它.我如何设置团体声明:

I successfully implement it in ASP.NET MVC application. 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();
    }
}

有效现在的想法是创建一个Web api控制器并限制对某些方法的访问.

It works Now the idea is to create an web api controller and restrict access to some of the method.

//[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

然后发送

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

标题为授权,值为承载者{token} 但获得未授权访问(401).(但是,未受保护的 https://localhost/api/values 可以正常工作).我怀疑我传递了错误的令牌,我在 https://jwt.io/上进行了检查,它不包含有关用户所属组的信息.我是否应该以其他方式在代码中进行配置?谢谢

with header Authorization and value Bearer {token} but get Unauthorized access (401). (Unprotected https://localhost/api/values works as expected though). 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. Should I configure it in the code another way? Thanks

更新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]

推荐答案

当使用 grant_type client_credentials 时,这意味着您正在使用客户端凭据流来获取访问令牌.用于访问资源:

When using grant_type is client_credentials , that means you are using the client credentials flow to acquire access token for accessing the resource :

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

OAuth 2.0客户端凭据授予流程允许Web服务(机密客户端)使用自己的凭据而不是模拟用户,从而在调用另一个Web服务时进行身份验证.在这种情况下,客户端通常是中间层Web服务,守护程序服务或网站.

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. In this scenario, the client is typically a middle-tier web service, a daemon service, or web site.

在这种情况下,客户端使用其自己的凭据而不是模拟用户,在这种情况下不包括用户信息/身份.您应该使用代码授权流程使用用户身份授权对Web应用程序和Web API的访问:

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 :

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

这篇关于Web API中具有令牌的Azure AD和基于组的授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆