我有一个 web api,我正在其中使用 JWT 令牌和 Microsoft AD 寻找身份验证。
登录页面应该有
我能够使用 UserManager 和 SignInManager 使身份正常工作,如果所有检查都通过,我将在其中生成 JWT 令牌。
现在我必须将 Microsoft Login 添加到这个我不确定的 Web API 中间件。任何建议或链接将不胜感激。
这将在 .net core Web Api 中。 UI 将基于 angular 或 HTML,所以我不确定 microsoft login 将如何进入 web api Controller 以及参数是什么
仅供参考 - 如果可能的话,我希望在没有 IdentityServer 的情况下执行此操作
答案 0 :(得分:1)
1. 在您的 web api 项目中安装 Microsoft.Identity.Web 库
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
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",
},
}
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的第一行。)
添加复制的客户端 ID 代替 uri 的客户端 ID 和资源 ID。
从 azure 广告中的身份验证部分复制重定向 uri 和
粘贴 &redirect_uri 参数
5.然后转到appregistrations>api>authentication>选择 访问令牌作为隐式授权流程
6.控制器可以使用 [Authorize] 属性。
namespace webapi.Controllers
{
[Authorize]
[ApiController]
[Route("[controller]")]
public class YourApiController : ControllerBase
...
...
//
.
.
注意:调用时修改真实的API端点。