How to use Active Directory Authentication in ASP.NET Core?

How to use Active Directory Authentication in ASP.NET Core?

By : Faiz Brown
Date : October 23 2020, 08:10 PM
this one helps. The best way is to use Windows authentication. However, that will only work if the server you run this on is joined to the domain (or a trusted domain).
If not, then you will have to use Forms Authentication, where the user enters their username and password, and you authenticate against AD in your code via LDAP. There are two ways to do this in .NET Core:
code :

Share : facebook icon twitter icon
Using Azure Active Directory authentication in ASP.NET Core 2.0 from Web App to Web API

Using Azure Active Directory authentication in ASP.NET Core 2.0 from Web App to Web API

By : A Turnbull
Date : March 29 2020, 07:55 AM
it should still fix some issue I can't think of how many queries I threw into Google until finally trying "c# asp core get access token" and getting this very helpful blog as result #3:
ASP.NET Core 2.0 LDAP Active Directory Authentication

ASP.NET Core 2.0 LDAP Active Directory Authentication

By : Md Alamgir
Date : March 29 2020, 07:55 AM
this will help to Win's Answer for pointing out that I needed to use Windows Compatibility Pack, I was able to figure this out.
The first thing I had to do was install the Nuget package
code :
Install-Package Microsoft.Windows.Compatibility 
const string LDAP_PATH = "EX://exldap.example.com:5555";
const string LDAP_DOMAIN = "exldap.example.com:5555";

using (var context = new PrincipalContext(ContextType.Domain, LDAP_DOMAIN, "service_acct_user", "service_acct_pswd")) {
    if (context.ValidateCredentials(username, password)) {
        using (var de = new DirectoryEntry(LDAP_PATH))
        using (var ds = new DirectorySearcher(de)) {
            // other logic to verify user has correct permissions

            // User authenticated and authorized
            var identities = new List<ClaimsIdentity> { new ClaimsIdentity("custom auth type") };
            var ticket = new AuthenticationTicket(new ClaimsPrincipal(identities), Options.Scheme);
            return Task.FromResult(AuthenticateResult.Success(ticket));

// User not authenticated
return Task.FromResult(AuthenticateResult.Fail("Invalid auth key."));
Active Directory Authentication with .NET Core Web API and React

Active Directory Authentication with .NET Core Web API and React

By : Vinodkumar Kulkarni
Date : March 29 2020, 07:55 AM
this one helps. For me, step one was to set up JWT authentication, such as described in this MSDN blog post.
Next, I had to find a library to use to check a user against Active Directory. I chose System.DirectoryServices.AccountManagement (available for .NET Core).
code :
    // Notice: We get a custom request object from the body
    public async Task<IActionResult> Login([FromBody] AuthRequest request)
            // Create a context that will allow you to connect to your Domain Controller
            using (var adContext = new PrincipalContext(ContextType.Domain, "mydomain.com"))
                    var result = adContext.ValidateCredentials(request.username, request.password);
                    if (result)
                        // Create a list of claims that we will add to the token. 
                        // This is how you can control authorization.
                        var claims = new[]
                            // Get the user's Name (this can be whatever claims you wish)
                            new Claim(ClaimTypes.Name, request.username)

                        // Read our custom key string into a a usable key object 
                        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetSection("SOME_TOKEN").Value));
                        // create some signing credentials using out key
                        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                        // create a JWT 
                        var token = new JwtSecurityToken(
                            issuer: "mydomain.com",
                            audience: "mydomain.com",
                            claims: claims, // the claims listed above
                            expires: DateTime.Now.AddMinutes(30), // how long you wish the token to be active for
                            signingCredentials: creds);

                        Since we return an IActionResult, wrap the token inside of a status code 200 (OK)
                        return Ok(new
                            token = new JwtSecurityTokenHandler().WriteToken(token)
        // if we haven't returned by now, something went wrong and the user is not authorized
        return Unauthorized();
    public class AuthRequest
        public string username { get; set; }
        public string password { get; set; }
        fetch(`login`, {
            method: "POST",
            headers: {
                'content-type': 'application/json',
                'accept': 'application/json',
            body: JSON.stringify({this.state.username, this.state.password})
        }).then((response) => {
            if (response.status === 401) {
                // handle the 401 gracefully if this user is not authorized
            else {
                // we got a 200 and a valid token
                response.json().then(({ token }) => {
                    // handle saving the token to state/a cookie
await fetch(`someController/someAction`, 
      method: 'GET'
      headers: {
          'content-type': 'application/json',
          'authorization': `Bearer ${YOUR_JWT}`
  .then(response => doSomething());
import * as signalR from '@aspnet/signalr';

var connection = new signalR.HubConnectionBuilder().withUrl('myHub', { accessTokenFactory: () => YOUR_JWT })
Active Directory Authentication by UPN in ASP.NET Core 3.0

Active Directory Authentication by UPN in ASP.NET Core 3.0

By : user3314947
Date : March 29 2020, 07:55 AM
wish of those help Tao option is working. I also found another option, here https://www.brechtbaekelandt.net/blog/post/authenticating-against-active-directory-with-aspnet-core-2-and-managing-users with code https://github.com/brechtb86/dotnet/tree/master/brechtbaekelandt.ldap. This however was for Asp.Net Core 2.0.
I have updated this to run on Asp.Net Core 3.0, and published my code on GitHub https://github.com/CraigTolley/AspNetCore-LdapAuth. It currently also uses the Novell library. I'm not promising that it is perfect, but will hopefully help someone else too.
Web API .Net Core Azure Active Directory Authentication

Web API .Net Core Azure Active Directory Authentication

By : supernoob
Date : March 29 2020, 07:55 AM
help you fix your problem You have to pass the access token to the Authorization header, not the id token.
The id token only contains information (claims) about the signed in user whereas the access token contains information about which protected resources the user has access to.
Related Posts Related Posts :
  • root undoing previous changes after sudo su user
  • Create X509 Certificate from.p12 or .pem certificate
  • Keras layer.set_weights doesn't modify the layer. Why?
  • Available build tasks in TFS 2017
  • Change oracle apex database user
  • How to parse typesafe config with objects
  • Is "Comment" a protected word in the Open API 3.0 spec or Swagger Editor?
  • Display Percentage in a Row in Tableau
  • Bokeh Colorbar Vertical title to right of colorbar?
  • Why the multi-ports model can't import into C++?
  • Nativescript tab page textfield
  • Why does this greedy algorithm work?
  • Nested list mapping using MapStruct
  • How to I find the original row index of a table in a google visualization if I have a filtered rows view
  • Ribbon icon doesn't show up in Word Online
  • Fitting user defined function with MPFIT in IDL
  • yii2 user CRUD create or update with password
  • Does Perl 6 performance suffer by using rationals for decimal numbers
  • How to get Y value at a given X value of a trendline
  • ElastAlert flatline not finding results
  • CSS not extracted for common chunk with extract-text-webpack-plugin
  • Adding element to nested vector
  • How can I trigger an action after updating a Podio Category on zapier?
  • Ninject.MVC5 Release Scope Never Called - OutOfMemoryException
  • Grok custom time format
  • How can I avoid Same Origin Policy exception when using AWS API Gateway and CloudFront
  • How to test ActionCable with Capybara and poltergeist inside Docker?
  • opendaylight: how to include a library jar file?
  • OpenThread using Nest Learning Thermostat
  • In Coq, how to remove a defined variable from the namespace?
  • Adobe DTM Mobile Tracking Rules
  • Accessing Vuex submodules inner state with the $store object
  • Include one widget instead of excluding all others
  • Create folder temp in mac using lotuscript
  • RSU placement in veins/SUMO
  • Exclamation Unary operator stopped working on bindings
  • RxJs how to merge two overlapping observable into one
  • How to add Nuget Package Source at runtime?
  • Absolute positioning a FlatList item react-native
  • Python, using variables in pymodbus.utilities.computeCRC
  • Akamai CDN - Whitelist service by Request header or User agent
  • UIWebView/WKWebView crash on iOS11 (ran out of executable memory)
  • Is ZonePlayerId capability still working?
  • Testing polynomial definition (from natural numbers to integers)
  • Wakanda 2.x cannot set certain tables' scope to publicOnServer
  • Call task from another Verilog module
  • Perl 6 transforms combined graphemes?
  • How to get automake to set libdir to /usr/lib64 on dual-arch Linux platforms
  • Restore RSA private key by modulus, public and private exponents using Java Security
  • Visual Studio 2017 Reset Settings
  • SonarQube 6.5 - Not able to trigger TFS Build Definition
  • Composing tweet in Twitterkit since Xcode 9 with Swift 4 & IOS 11
  • Custom Bing Map Type Issue
  • How to update MvvmCross?
  • pageFunction in Puppeteer returns empty object
  • PyCharm Run --- why does it sometimes display a traceback and error and sometimes not?
  • Yii2, optional parameter in the rounte
  • Hive and Pig on top of same dataset
  • SCM_REPOSITORY_PATH being ignored on Azure web app
  • Pentaho Flow Input->Output->Input not working
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org