.net 5 Web API - 使用身份和 Microsoft AD 进行身份验证

时间:2021-07-30 06:29:13

标签: c# azure-active-directory asp.net-identity .net-5

我有一个 web api,我正在其中使用 JWT 令牌和 Microsoft AD 寻找身份验证。

登录页面应该有

  1. 登录按钮 - 这将验证使用身份创建的用户。
  2. Microsoft 登录按钮 - 这将使用 Microsoft 广告登录验证用户。首次登录后,我会将用户详细信息保存在身份表中。

我能够使用 UserManager 和 SignInManager 使身份正常工作,如果所有检查都通过,我将在其中生成 JWT 令牌。

现在我必须将 Microsoft Login 添加到这个我不确定的 Web API 中间件。任何建议或链接将不胜感激。

这将在 .net core Web Api 中。 UI 将基于 angular 或 HTML,所以我不确定 microsoft login 将如何进入 web api Controller 以及参数是什么

仅供参考 - 如果可能的话,我希望在没有 IdentityServer 的情况下执行此操作

1 个答案:

答案 0 :(得分:1)

1. 在您的 web api 项目中安装 Microsoft.Identity.Web 库

  • 右键单击项目并管理nuget包并搜索 Microsoft.Identity.Web 库。
  • 添加>> Services.AddMicrosoftIdentityWebApiAuthentication(Configuration) 中 startup.cs 类

    
     

 using Microsoft.Identity.Web;

    public void ConfigureServices(IServiceCollection services)
        {
            //other code
            //

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddMicrosoftIdentityWebApi(Configuration, "AzureAd");
            //
           //other code
        }

2.在 app settings.json 中,复制粘贴应用程序(客户端 ID)和租户 来自客户端 id 中的 azure 广告的 id enter image description here


appsettings.json

{
  "Logging": {
  "LogLevel": {
  "Default": "Information",
  "Microsoft": "Warning",
  "Microsoft.Hosting.Lifetime": "Information"
 }
  },
 "AllowedHosts": "*",
"AzureAd": {
   "Instance": https://login.microsoftonline.com/,
   "ClientId": "93134054-xxxx",
   "TenantId": "aacd4f65-xxxx",
   "CallbackPath": "/signin-oidc",
},
}

enter image description here

3.在startup.cs类的configure()方法中,添加中间件(在最上面 app.UseAuthorization();)

app.UseAuthentication(); 
app.Use(async(context,next)=>
{
If(!context.User.Identity?.IsAuthenticated??false)
{
Context.Response.StatusCode=401;
Await context.Response.WriteAsync(“User is Not Authenticated ”);
}
Else await next();
});

4.构造 URI 如下。 例子:

https://login.microsoftonline.com/<TENANT ID>/oauth2/authorize?
client_id=<AD APP CLIENT ID>
&response_type=token
&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2F // Redirect URL
&resource=<AD APP CLIENT ID>
&response_mode=fragment
&state=12345
&nonce=678910

这个uri可以通过使用azure ad中的endpoints部分来配置 为 AD 租户和 AD 应用程序详细信息提供值 上面的网址。

(端点可以从azure ad portal端点2获取,如下图,可以粘贴在上面url的第一行。)

enter image description here

  • 添加复制的客户端 ID 代替 uri 的客户端 ID 和资源 ID。

  • 从 azure 广告中的身份验证部分复制重定向 uri 和
    粘贴 &redirect_uri 参数

5.然后转到appregistrations>api>authentication>选择 访问令牌作为隐式授权流程

enter image description here

6.控制器可以使用 [Authorize] 属性。

namespace webapi.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class YourApiController : ControllerBase
...
...
//
.
.

注意:调用时修改真实的API端点。

有关详细信息,请参阅 this。 另见this