我是将Azure AD与OAuth2结合使用的初学者。我在Azure AD中部署了示例WEB API。我通过Postman应用程序使用了我的WEB API。在Postman中使用WEB API之前,我需要生成访问令牌。但是,当我在邮递员中生成访问令牌时,它始终会接受Grant Type - Authentication Code
。当我将值更改为Client Credentials
时,API中将不接受生成的访问令牌。显示UnAuthorized
消息。
在Azure门户中-应用程序设置“证书和秘密”窗口中,我创建了描述为“邮递员”的客户端秘密。我没有在此应用程序中上传证书。
我想生成“授权类型”值为“客户凭证”的访问令牌。有其他配置吗?
答案 0 :(得分:1)
Is there any additional configuration for this ?
否,没有用于使用以下方式生成令牌的其他设置:
client_credentials
。
您都需要以下参数:
client_id
client_secret
resource
(For v2.0
scope
)grant_type
您如何在PostMan中请求令牌:
Your Token Endpoint:
https://login.microsoftonline.com/YourTenent.onmicrosoft.com/oauth2/token
Method Type:
POST
Request Body:
grant_type:client_credentials
client_id:00ab01_Your_Azure-Ad_Application_Id_fbbf8e
client_secret:XNk2zgXx_Your_Azure-Ad_Application_Secret_vjdz2Q
resource:https://graph.microsoft.com/
查看屏幕截图:
代码段:
//Token Request End Point
string tokenUrl = $"https://login.microsoftonline.com/YourTenant.onmicrosoft.com/oauth2/token";
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);
//I am Using client_credentials as It is mostly recommended
tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "client_credentials",
["client_id"] = "b6695c7be_YourClient_Id_e6921e61f659",
["client_secret"] = "Vxf1SluKbgu4PF0Nf_Your_Secret_Yp8ns4sc=",
["resource"] = "https://graph.microsoft.com/"
});
dynamic json;
AccessTokenClass results = new AccessTokenClass();
HttpClient client = new HttpClient();
var tokenResponse = await client.SendAsync(tokenRequest);
json = await tokenResponse.Content.ReadAsStringAsync();
results = JsonConvert.DeserializeObject<AccessTokenClass>(json);
使用的类:
public class AccessTokenClass
{
public string token_type { get; set; }
public string expires_in { get; set; }
public string resource { get; set; }
public string access_token { get; set; }
}
希望有帮助。如果您还有任何顾虑,请随时分享。