Giter Site home page Giter Site logo

nordes / identityserver4.ldapextension Goto Github PK

View Code? Open in Web Editor NEW
200.0 17.0 62.0 2.07 MB

IdentityServer4 Ldap Extension (OpenLdap or ActiveDirectory)

License: MIT License

C# 79.14% JavaScript 8.87% Vue 9.67% CSS 1.35% HTML 0.97%
identityserver identityserver4 openldap activedirectory nuget

identityserver4.ldapextension's Introduction

License Build status NuGet

IdentityServer4.LdapExtension

IdentityServer4 Ldap Extension (OpenLdap or ActiveDirectory).

Installation

The plugin is easy to install to your solution. Built using .Net Core 3.1 and .Net 5.0. The Nuget package can be installed by either searching the package IdentityServer.LdapExtension or by typing the following command in your package console:

Install-Package IdentityServer.LdapExtension

Be aware of the dependency with IdentityServer4. The version of the package is visible in your Visual Studio or through Nuget.org.

  • Ldap Extension 2.0.0 goes with IdentityServer 2.2.x
  • Ldap Extension 2.1.7 goes with IdentityServer 2.3.x
  • Ldap Extension 2.1.8 goes with IdentityServer 2.4.x
  • Ldap Extension 3.1.0 goes with IdentityServer 4.1.2

Configuration for IdentityServer4 Server

An easy extension method have been created in order to add the LDAP as a provider to your IdentityServer. For this you simply have to use the AddLdapUsers<TApplicationUser>(LdapConfigSection, StoreTypeOrCustomStore). The configuration has to be provided or it won't work. The configuration is described here.

In the Startup.cs under ConfigureServices method, you will have something similar to the following by default (Starter pack for IdentityServer). The last line is what you will need to add in order to get started.

// ... Code ...
services.AddIdentityServer(/*...*/)
  .AddInMemoryClients(Config.GetClients())                  // [LDAP API Example]
  .AddInMemoryIdentityResources(Config.IdentityResources()) // [LDAP API Example]
  .AddInMemoryApiScopes(Config.GetApiScope())               // [LDAP API Example]
  .AddInMemoryApiResources(Resources.ApiResources)
  .AddSigningCredential()
  /*...*/
  // [START of Usage of LDAP]
  .AddLdapUsers<OpenLdapAppUser>(_config.GetSection("IdentityServerLdap"), UserStore.InMemory)
  .AddProfileService<HostProfileService>() // Upgraded for LDAP (see code in project class for details).
  // [END of usage of LDAP]

Application User: 2 (OpenLdapAppUser, ActiveDirectoryAppUser) have been provided with this extension, but you can use your own as long as you implement the interface IAppUser. I encourage you to provide your own implementation. You might want to have claims/roles based on an active directory group or your attributes within LDAP are not the one I have defined.

Store types:

  1. UserStore.InMemory: Can be used when you test locally. It stores the logged in user in memory in order to avoid querying the LDAP server over and over. It is also used in order to store the external logged in user details (Google, Facebook, etc.).
  2. UserStore.Redis: Same as in memory, but is persisted and will be ready when you restart.
  3. ILdapUserStore implementation: Build your own store implementation and pass it as a parameter.

AppSettings Configuration

The appsettings.json will require a configuration for the extension. Here's an example using OpenLdap:

{
  "MyConfigurationSection": { // Name can be of your choosing
    "Url": "localhost",
    "Port": 389,
    "BindDn": "cn=ldap-ro,dc=contoso,dc=com",
    "BindCredentials": "P@ss1W0Rd!",
    "SearchBase": "ou=users,DC=contoso,dc=com",
    "SearchFilter": "(&(objectClass=posixAccount)(objectClass=person)(uid={0}))"
    // "Redis": "localhost:32771,ssl=false", // Required if using UserStore.Redis 
  }
}

If you want to see a working demo, you can open the implementation available the sample folder. It is based on the QuickStart from IdentityServer4 WebSite.

Multiple concurent Ldap (For different DN, or totally different Ldap)

In the case you would have a need to have multiple configuration to either connect to different LDAP servers or to even connect to different part of the directory (multiple area for the DN), this feature have been requested and it should be able to allow different type of AD to live together. The AAD is of course not part of this. In case you would like to use AAD, there's either other connector or you can also write your own.

The usage of multiple configuration will bring some issues, so here's the rules:

  1. Configurations needs to be all the same type, except if you have a custom LDapUser and you're not using the one provided in this extension.
  2. Rules for preFilterRegex can discriminate in order to not try on all the LDAP servers the credential/password for failure. It also avoid having some kind of DoS on all your servers in case of attack.
  3. If we have multiple LDAP configurations that are ok with the preFilterRegex, then the validation is done async (To be confirmed) and the first server to answer OK will be the one to use in order to get the information. The issue in that case is that it will try to call all your servers and that's probably not something you wish for.
  4. If it does not match anything, the extension will send back automatically a user not found.

By default the cache is using InMemory, but you can also use Redis. It needs to be set in the global configuration when multiple Ldap entries. This avoids having custom code for each Ldap.

Quick and Simple Example of a Configuration

2 configurations using a preFilterRegex for discrimination.

  "IdentityServerLdap": {
    // Example: If you use a redis instead of in-memory (See Startup.cs)
    //"redis": "localhost:32771,ssl=false",
    //"RefreshClaimsInSeconds": 3600,
    "Connections": [
      {
        "FriendlyName": "OpenLdap-Users",
        "Url": "localhost",
        "Port": 389,
        "Ssl": false,
        "BindDn": "cn=ldap-ro,dc=contoso,dc=com",
        "BindCredentials": "P@ss1W0Rd!",
        "SearchBase": "ou=users,DC=contoso,dc=com",
        "SearchFilter": "(&(objectClass=posixAccount)(objectClass=person)(uid={0}))",
        "PreFilterRegex": "^(?![a|A]).*$" // not mandatory and will take everything not starting with A
      },
      {
        "FriendlyName": "OpenLdap-BuzzUsers",
        "Url": "localhost",
        "Port": 389,
        "Ssl": false,
        "BindDn": "cn=ldap-ro,dc=contoso,dc=com",
        "BindCredentials": "P@ss1W0Rd!",
        "SearchBase": "ou=users-buzz,DC=contoso,dc=com",
        "SearchFilter": "(&(objectClass=posixAccount)(objectClass=person)(uid={0}))",
        "PreFilterRegex": "^([a|A]).*$" // not mandatory and will take everything not starting with A
      }
    ]
  }

In startup, the same as a single configuration. Basically the configuration section and nothing more. If it's a single configuration, it will upgrade the single configuration to act like a multi-configuration. It is recommended from now on to use the multi-configuration style. It's easier to handle the Redis and other new features if any comes.

You don't have an LDAP for your tests, use a OpenLdap docker image instead!

It's not a big problem. I wrote a small tutorial/article in order to setup an entire OpenLdap server within Docker in order to not pollute your PC and also to avoid relying on network administrator. That way you can play with existing users or create your own users directory. The tutorial/article is available at HoNoSoFt website.

Features in progress

I plan to work on the following:

  • Implement the SSL
  • Implement a cache invalidation based on time (After x time without being hit, remove from redis or from memory).

Contributors

Main contributor

  • @Nordes: The main author of the package (@me)

Special thanks to

  • @marianahycit: Contribution
  • @uchetfield: Contribution (Issue #10)
  • @ttutko
  • @chrgraefe

License

MIT

Regarding the IdentityServer4 Sample - Apache 2 (due to original code a bit updated)

identityserver4.ldapextension's People

Contributors

codekenpachi avatar dependabot[bot] avatar githubpang avatar marianahycit avatar nordes avatar sven-ernw avatar ttutko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

identityserver4.ldapextension's Issues

Login ldapActiveDirectory Not Working

image

"ldapActiveDirectory": {
// Active directory
"url": "LDAP://79.123.184.30",
"port": 389,
"ssl": false,
"bindDn": "DC=hitit,DC=edu,DC=tr",
"bindCredentials": "******",
"searchBase": "CN=Users,DC=hitit,DC=edu,DC=tr",
// "searchFilter": "(&(objectClass=user)(objectClass=person)(sAMAccountName={0}))",
"searchFilter": "(&(objectClass=user)(SAMAccountName={0}))",
// Example: If you use a redis instead of in-memory
//"redis": "localhost:32771,ssl=false"
}

Is connection pooling implemented in this library

I get below error when I get more traffic
An attempt was made to access a socket in a way forbidden by its access permissions aaa.bbb.ccc.ddd.
An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full
Only one usage of each socket address (protocol/network address/port) is normally permitted

Build custom docker image

I would like to build a "standard" docker image for IdentityServer4.LdapExtension.

This would ease the entry barrier to participate in development. Potential develop doesn't have to configure there own docker image.

any thoughts?

Add the proper Log-In button info

Sign in

<li class="nav-item">
    <a href="/login"><icon icon="sign-in-alt" class="mr-2" /><span>Sign-In</span></a>
</li>

Sign out:

<li class="nav-item" v-if="isAuthenticated">
    <a href="/logout"><icon icon="sign-in-alt" flip="horizontal" class="mr-2" /><span>Sign-Out</span></a>
</li>

Education videosu

Hello Do you know how to use the package with a video. For beginners like me, we can learn more easily and more easily.

How to use other UserStores?

I have identityserver4 setup and was able to get your library to support authenticating against ActiveDirectory. This works when using InMemory UserStore but what I am looking to do is authenticate against ActiveDirectory and then store the user in a database specific to my application. My ultimate objective is to get this working with AspNet.Identity.MongoDbCore but I'm not sure how to even get this working with AspNetCore's built-in EF provider. I am looking for guidance on how to use your library for authentication only but not as the userstore?

Wrong AD user returns token in Docker container

In local environment, tokens are generated sucessfully for existing AD users. When token is requerested for unexisting user or wrong password entered, server logs invalid_username_or_password, which is correct.

After publishing server in a docker container and requesting a token through connect/token endpoint, any value entered in username and password fields generates a token.

Any idea what I could be doing wrong?

Package used are the following:

"IdentityServer.LdapExtension" Version="2.1.49"
"IdentityServer4" Version="2.4.0"

Local environment:
image

Docker container
image

Fix the security alert from github

Basically update all the projects/fix new version implementation for font-awesome (fortawesome).

Also fix the build/exec with the test project.

Where Can I get the source code for V 2.0.0?

I am try to use IdentityServer4.LdapExtension with the IdentityServer4 v.2.2.0. I was told that I must use IdentityServer4.LdapExtension v.2.0.0. Where can I download the source code for V 2.0.0? Is there way to make IdentityServer4.LdapExtension V.2.1.7 work with IdentityServer4 V2.2.0?

Async ILdapUserStore

Since LDAP calls are I/O bound, async calls could add a performance benefit under high-load.

Redirect back to client doesn't work.

Hello,

I have down loaded your code and got it compiled. When I try to run the "MvcClient" with the "QuickstartIdentityServer", it wouldn't redirect me back to the "MvcClient" after I login. I traced it, it looks like the function "FindBySubjectId" always return me null. Any ideas?

Best Regards,
D. L.

Multiple Servers

Is there a way to configure multiple Ldap servers?

I'm thinking that the Startup could look something like below.
.AddLdapUsers<ActiveDirectoryAppUser>(Configuration.GetSection("activeDirectory1"), UserStore.InMemory).AddLdapUsers<ActiveDirectoryAppUser>(Configuration.GetSection("activeDirectory2"), UserStore.InMemory);

I'm not sure how to configure and specify which Active Directory server to connect, currently when I add multiple user stores it only searches the second addition.

Roadmap for support auf IdentityServer4 version 3.1.x and up

Hi,

I want suggest an approach for going ahead for the next upgrade to an actual version of IdentityServer4.
IdentityServer4 version greater than 3.0.0 aren't supporting .NETStandard 2.0 any more.
You have to use TFM netcoreapp3.0 or netcoreapp3.1

What is your thought about branching the cuurent master into a maintenance branch for versions 2.1.x
Afterwards master we coud do the neccesseary changes for going ahead with new supported TFM like netcoreapp3.1.

any thoughts?

How to connect LDAP with GSS-API ?

Hi,

I trying to connect to LDAP with these connection properties but can't find their equivalent of appsettings (GSS-API in particular).

image

Could you help me please?

Is this extension able to create users and manage roles in the Active Directory ?

Hi,
Is it possible to use this extension to turn my IdentityServer into an ActiveDirectory ? By using the AspNetCore.Identity library in .NET Core my website users will be stored in SQL server.
I want to be able to store the users and their roles and permissions in an ActiveDirectory. Is it possible with this extension ?

IdentityServer version 4.1.2

Hello!
I tried to update your example to IdentityServer version 4.1.2 and it didn’t work for me, are you planning to update your IdentityServer.LdapExtension?

invalid_grant and "User has been disabled"

I've implemented IS on my AD ad it work with login page. I'm tring the ResourceOwnerPassword but I always get invalid_grant and in log I see "User has been disabled".

The problem is in then LdapUserProfileService.IsActiveAsync that don't find the user and set context.IsActive to false.

At runtime the Users collection is empty. Anyone has this issue?

Grazie

Active Directory Ldap Test

Hello, is your project time to test with Active Directory Ldap? This matter is important to me, I want to use your refusal. Thank you from now.

Problem with Configuration online-ldap ?

I started with the sample and I cannot log into the ldap of a test server: ldap.forumsys.com
https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server

Here is my configuration: does it seem correct to you?

"IdentityServerLdap": {
    // Example: If you use a redis instead of in-memory (See Startup.cs)
    //"redis": "localhost:32771,ssl=false",
    //"RefreshClaimsInSeconds": 3600,
    "Connections": [
      {
        "FriendlyName": "forumsys",
        "Url": "ldap.forumsys.com",
        "Port": 389,
        "Ssl": false,
        "BindDn": "cn=read-only-admin,dc=example,dc=com",
        "BindCredentials": "password",
        "SearchBase": "dc=example,dc=com  ",
        "SearchFilter": "(&(objectClass=user)(uid={0}))"
        //"PreFilterRegex": "^(?![a|A]).*$" // not mandatory and will take everything not starting with A
      }
    ]
  }

Thank you in advance.

groups/roles support

Hi,

I'm using the LdapExtension with the AD flavour.
Are groups/roles supported yet?

I can't get it working. The authentication process is working well.

Is there anything I've to configure in advanced?

SSL Support for Ldap

The current release does not support SSL, even though there is a configuration option for this. Is this planned for the next release? Is somebody already working on this?

**401 Unauthorized** all the time

I keep on trying to login with a user that is already in our active directory, but it seems it can't find it? I don't know if the connection is the problem or what because there are no errors stating error with the connection. I am using ActiveDirectoryAppUser instead of the OpenLDAP one. I know this is kind of broad but, the problem seems to not lead me to anything specific. I don't know if I am missing something. When I debug it gets to the part of validatingCredentials in the "inMemoryUserStore.cs" file (I downloaded the source code and added it to my solution in order to debug). It gets the correct credentials that are passed by thru postman. Once it trys to use the "_authenticationService.login(username, password)" method I don't know what happens but the user is unauthorized.

this is the validateCredentials method that is included in the ldapExtension project

public IAppUser ValidateCredentials(string username, string password)
{
try
{
var user = _authenticationService.Login(username, password);
if (user != null)
{
return user;
}
}
catch (LoginFailedException)
{
return default(TUser);
}

        return default(TUser);
    }

this is my login controller that is getting the data from postman

[HttpPost("SignIn")]
public async Task SignIn([FromBody]LdapUser model)
{
// validate username/password against Ldap
var user = userStore.ValidateCredentials(model.Username, model.Password);

        if (user != default(IAppUser))
        {
            // Response with authentication cookie
            await HttpContext.SignInAsync(user.SubjectId, user.Username);

            var token = await tools.IssueClientJwtAsync(
               clientId: "MyBackend",
               lifetime: 3600,
               audiences: new[] { "MyBackend1", "MyBackend2" });

            // Get the Access token
            //var accessToken = await this.tools.IssueClientJwtAsync(lifetime: 3600, claims: new Claim[] { new Claim(JwtClaimTypes.Audience, model.ApiResource) });

            // Write the Access token to response
            await HttpContext.Response.WriteAsync(token);

            return Ok();
        }
        else
        {
            return Unauthorized();
        }
    }

this is my startup file

public Startup(IConfiguration configuration)
{
this.Configuration = configuration;
}
public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<IISOptions>(iis =>
        {
            iis.AuthenticationDisplayName = "Windows";
            iis.AutomaticAuthentication = false;
        });

        String sHostname = System.Net.Dns.GetHostName();

        services.AddMvc();

        services.AddIdentityServer()
            .AddDeveloperSigningCredential(persistKey: false)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetAllApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddTestUsers(Config.GetUser())
            .AddLdapUsers<ActiveDirectoryAppUser>(this.Configuration.GetSection("LdapServer"), UserStore.InMemory);
        ;
    }

I am also following this guide

Thank you for your time!

ldap ext with external oidc provider

hi, i´m trying to setup Azure AD as external provider in a deployment i have with LdapExtension, but the callback allways ends up calling the Search method and obviusly the user(Azure AD) does not exist in any ldap and the login fail, can we set up the ldap extension and also external oidc ??

Support Duende Identity instead of just IdentityServer4

Nice extension which i don't really understand why IdentityServer don't bake this into it's core. But since IDSvr is now changing to Duende, will you release a Duende extension?

The type 'IIdentityServerBuilder' exists in both 'Duende.IdentityServer, Version=5.0.5.0, Culture=neutral, PublicKeyToken=null' and 'IdentityServer4, Version=4.1.2.0, Culture=neutral, PublicKeyToken=f294d0afe402bb2b'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.