在ASP.Net Core 2.0项目中实现活动目录,可以通过以下步骤进行:
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = "https://login.microsoftonline.com/{your-tenant-id}";
options.ClientId = "{your-client-id}";
options.ClientSecret = "{your-client-secret}";
options.CallbackPath = "/signin-oidc";
options.ResponseType = "code";
options.SaveTokens = true;
options.Events = new OpenIdConnectEvents
{
OnRemoteFailure = OnAuthenticationFailed
};
});
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
private Task OnAuthenticationFailed(RemoteFailureContext context)
{
context.HandleResponse();
context.Response.Redirect("/Home/Error?message=" + context.Failure.Message);
return Task.CompletedTask;
}
}
在上述代码中,需要替换以下参数:
{your-tenant-id}
: 替换为你的租户ID。{your-client-id}
: 替换为你的客户端ID。{your-client-secret}
: 替换为你的客户端密钥。[Authorize]
属性,以确保只有经过认证的用户可以访问。[Authorize]
public class HomeController : Controller
{
// ...
}
这样,当用户访问需要认证的页面时,系统将会重定向到活动目录登录页面进行认证。
请注意,以上代码仅为示例,实际使用时需要根据自己的具体情况进行配置和调整。
推荐的腾讯云相关产品:腾讯云身份认证服务(CAM)
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云