.Net Core 6 API使用客户端凭据进行身份验证

huangapple go评论82阅读模式
英文:

.Net core 6 API authentication with client credentials

问题

API的身份验证配置代码如下:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(jwtBearerOptions =>
    { }, msIdentityOptions =>
    {
        configuration.Bind("AzureAd", optionsB);
        var defaultBackChannel = new HttpClient();
        defaultBackChannel.DefaultRequestHeaders.Add("Origin", "shard-manager");
        msIdentityOptions.Backchannel = defaultBackChannel;
    })
    .EnableTokenAcquisitionToCallDownstreamApi(e => { })
    .AddInMemoryTokenCaches();

我想要使用客户端ID和客户端密钥进行身份验证,并调用API中的端点。我可以成功地对 Azure 中的应用程序注册进行身份验证,但是当我使用访问令牌发送请求到API时,它返回401未经授权的错误。

当我使用访问令牌发送请求时,使用Postman也会得到相同的401错误。

应用程序注册:

.Net Core 6 API使用客户端凭据进行身份验证

.Net Core 6 API使用客户端凭据进行身份验证

Postman:

.Net Core 6 API使用客户端凭据进行身份验证

不确定我漏掉了什么。

英文:

API's authentication configfiguration code looks like the following:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                                    .AddMicrosoftIdentityWebApi(jwtBearerOptions =>
                                    { }, msIdentityOptions =>
                                    {
                                        configuration.Bind("AzureAd", optionsB);
                                        var defaultBackChannel = new HttpClient();
                                        defaultBackChannel.DefaultRequestHeaders.Add("Origin", "shard-manager");
                                        msIdentityOptions.Backchannel = defaultBackChannel;
                                        
                                    })
                                    .EnableTokenAcquisitionToCallDownstreamApi(e => { })
                                    .AddInMemoryTokenCaches();

I want to authenticate using a client Id and client secret and call and endpoint in the API. I can authenticate the app registration azure successfully but when I use the access token to send request to the API it returns 401 unauthorized.

I get the same 401 result when I send the request using postman with access token.

App registration:

.Net Core 6 API使用客户端凭据进行身份验证

.Net Core 6 API使用客户端凭据进行身份验证

Postman:

.Net Core 6 API使用客户端凭据进行身份验证

Not sure what I am missing here.

答案1

得分: 0

请注意:由于您正在使用客户端凭据流程,您必须授予应用程序权限。对于委派类型的权限,您必须使用任何用户交互流程,如授权代码流。

我创建了一个Azure AD应用程序并公开了一个API,如下所示:

.Net Core 6 API使用客户端凭据进行身份验证

当在API权限部分添加范围时,它是"委派"类型:

.Net Core 6 API使用客户端凭据进行身份验证

现在我使用Postman通过"客户端凭据流程"生成了访问令牌:

https://login.microsoftonline.com/TenantID/oauth2/v2.0/token

client_id:ClientID
client_secret:ClientSecret
scope:api://ClientID/.default
grant_type:client_credentials

.Net Core 6 API使用客户端凭据进行身份验证

当我解码访问令牌时,"范围"未显示:

.Net Core 6 API使用客户端凭据进行身份验证

当我调用API时,我收到了"401未经授权"错误:

GET https://apiendpoint/weatherforecast

.Net Core 6 API使用客户端凭据进行身份验证

如果您只想使用客户端凭据流程,那么创建"应用程序角色":

.Net Core 6 API使用客户端凭据进行身份验证

现在角色已添加为"应用程序类型"的权限:

.Net Core 6 API使用客户端凭据进行身份验证

我生成了访问令牌,解码后它显示了角色:

.Net Core 6 API使用客户端凭据进行身份验证

否则,对于"委派API权限",请使用"授权代码流程":

使用以下端点生成"授权码":

https://login.microsoftonline.com/TenantID/oauth2/v2.0/authorize?
&client_id=ClientID
&response_type=code
&redirect_uri=https://jwt.ms
&response_mode=query
&scope=api://ClientID/.default
&state=12345

.Net Core 6 API使用客户端凭据进行身份验证

使用以下参数生成"访问令牌":

https://login.microsoftonline.com/TenantID/oauth2/v2.0/token

client_id:ClientID
scope:api://ClientID/.default
grant_type:authorization_code
redirect_uri:https://jwt.ms
code:code
client_secret:ClientSecret

.Net Core 6 API使用客户端凭据进行身份验证

当我解码访问令牌时,范围显示如下:

.Net Core 6 API使用客户端凭据进行身份验证

我能够成功调用API:

GET https://apiendpoint/weatherforecast

.Net Core 6 API使用客户端凭据进行身份验证

  • 确保在清单中将"accessTokenAcceptedVersion"属性设置为2。

您可以参考我在SO Thread中提供的示例代码,通过更改范围来使用"授权代码流程"。

参考链接:

Azure Active Directory ASP.NET Core Web App GitHubjennyf19 提供。

英文:

> Note that: As you are using Client credential flow, you have to grant application permissions. For delegated type permissions you have to make use of any user interactive flow such as Authorization code flow.

I created an Azure AD Application and exposed an API like below:

.Net Core 6 API使用客户端凭据进行身份验证

When the scope is added in the API permission blade it is delegated type:

.Net Core 6 API使用客户端凭据进行身份验证

Now I generated access token using Client Credential Flow via Postman:

https://login.microsoftonline.com/TenantID/oauth2/v2.0/token

client_id:ClientID
client_secret:ClientSecret
scope:api://ClientID/.default
grant_type:client_credentials

.Net Core 6 API使用客户端凭据进行身份验证

When I decoded the access token, scope is not displayed:

.Net Core 6 API使用客户端凭据进行身份验证

When I called the API, I got 401 unauthorized error:

GET https://apiendpoint/weatherforecast

.Net Core 6 API使用客户端凭据进行身份验证

If you want to use Client credential flow only then create App roles:

.Net Core 6 API使用客户端凭据进行身份验证

Now the role is added as Application type permissions:

.Net Core 6 API使用客户端凭据进行身份验证

I generated the access token and when decoded it displays the role:

.Net Core 6 API使用客户端凭据进行身份验证

Otherwise, for delegated API permissions make use of Authorization Code Flow:

Generated auth-code using below endpoint:

https://login.microsoftonline.com/TenantID/oauth2/v2.0/authorize?
&client_id=ClientID
&response_type=code
&redirect_uri=https://jwt.ms
&response_mode=query
&scope=api://ClientID/.default
&state=12345

.Net Core 6 API使用客户端凭据进行身份验证

Generated access token by using below parameters:

https://login.microsoftonline.com/TenantID/oauth2/v2.0/token

client_id:ClientID
scope:api://ClientID/.default
grant_type:authorization_code
redirect_uri:https://jwt.ms
code:code
client_secret:ClientSecret

.Net Core 6 API使用客户端凭据进行身份验证

When I decoded the access token, scopes displayed like below:

.Net Core 6 API使用客户端凭据进行身份验证

I am able to call the API successfully:

GET https://apiendpoint/weatherforecast

.Net Core 6 API使用客户端凭据进行身份验证

  • Make sure to update accessTokenAcceptedVersion property set to 2 in the manifest.

You can refer this SO Thread by me for sample code for Authorization Code Flow by changing the scope.

Reference:

azureactive-directory-aspnetcore-webapp· GitHub by jennyf19

huangapple
  • 本文由 发表于 2023年8月10日 15:51:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873643.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定