现在,我正在寻找一个使用Azure AD对用户进行身份验证的API。使用承载令牌会导致HTTP 302错误,从而将用户重定向到登录。但是,如果我有一些cookie,则GET请求可以正常进行。
为什么不单独使用承载令牌并且需要cookie?有办法解决吗?
现在,我正在寻找一个使用Azure AD对用户进行身份验证的API。使用承载令牌会导致HTTP 302错误,从而将用户重定向到登录。但是,如果我有一些cookie,则GET请求可以正常进行。
为什么不单独使用承载令牌并且需要cookie?有办法解决吗?
如果您使用的是.net core,并且想使用访问令牌来认证请求,请确保您使用的AzureADBearer
作为身份验证服务。
转到Startup.cs
并尝试以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WebApplicationAzureAD
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd",options));
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
appsettings.json
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/","Domain": "<your tenant domain>","TenantId": "<your tenant ID>","ClientId": "<your client ID>"
},"Logging": {
"LogLevel": {
"Default": "Information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "Information"
}
},"AllowedHosts": "*"
}