简体   繁体   中英

I need to make Active Directory login works on C# whit net core 3.1

my goal is to authenticate the login to a company application through active directory, I currently asked the company's support to create the app registration and install version 3.0.0-rc1.19457.4 in my code (because later It would not let me install them, they said they were not compatible) my project points to netcore3.1 and the web application already had the internal management of login with database, for security this is a new requirement and I never did something similar, so I'm half lost with this.

So, i started reading some guides and posts from here like this: Azure AD Not Authenticating in .NET Core 3.1 including the sample and the git code, but I don't think I have the necessary seniority to understand where the authentication returns, I don't understand if I need to create a view with the name "signin-oid" nor do I understand how to configure the / secret of the home controller.

The debugging and testing process is complicated because the application needs publish and pull request for every change I make, and I can't test this on localhost.

This is my current configuration in Azure, I think it's fine, since almost all the guides said to do this.

Here below I leave the code of both the startup and the controller I want to go to and the appsettings.json

STARTUP

    namespace name*
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {

            var config = new ConfigurationBuilder() //newForAD
                .SetBasePath(System.IO.Directory.GetCurrentDirectory())//newForAD
                .AddJsonFile("appsettings.json", false)//newForAD
                .Build();//newForAD

            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)//newForAD
                 .AddAzureAD(options => config.Bind("AzureAd", options));//newForAD
            
            services.AddControllersWithViews();//newForAD
     
        }


    // 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();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");            
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting(); // UseRouting must come before UseAuthentication //newForAD
            app.UseAuthentication(); // UseAuthentication must come before UseAuthorization //newForAD
            app.UseAuthorization(); //newForAD
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Appsettings.json :

 "AzureAd": {
    "Instance": "https://login.microsoftonline.com",
    "Domain": "https://*****.azurewebsites.net/",
    "TenantId": "****",
    "ClientId": "*****",
    "CallbackPath": "/signin-oidc"
  }

Then, the Home Controller:

{
[CustomActionFilter]
public class HomeController : Controller
{
    private readonly IHomeApplication _home;
    private readonly IWebHostEnvironment _environment;
    public HomeController(IHomeApplication home, IWebHostEnvironment environment)
    {
        _home = home;
        _environment = environment;
    }
    
    [Route("/")]
    public IActionResult Index()
    {
        return Ok("Home page");
    }

    [Authorize]
    [Route("/secret")]
    public IActionResult Secret()
    {
        var identity = ((ClaimsIdentity)HttpContext.User.Identity);
        var name = identity.Claims.FirstOrDefault(c => c.Type == "name")?.Value;
        var email = identity.Claims.FirstOrDefault(c => c.Type == "email")?.Value;
        return new OkObjectResult(new { name, email });
    }}}

If someone can help me to make this work it will solve my week

As junnas said, change your domain to mytenant.onmicrosoft.com and it will work well.

I don't understand if I need to create a view with the name "signin-oidc" nor do I understand how to configure the / secret of the home controller.

You need to ensure your claim contain name and email, otherwise it will get error. You can simple set the Authorize attribute on Index and if you can login, it means that you have configure right.

For more details you could refer to this article and sample here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM