Get one project needs to access the LDAP server doing auth with Blazor Server App. I search the Blazor resources online but all of them are with System.DirectoryServices but it can't work in Linux (get PlatformNotSupportedException)
Found one solution that he Novell LDAP nuget package can run under Linux. So this repo is an example to do LDAP authentication in Blazor Server.
- VS 2022
- Blazor Server App
- .net 6
- Novell.Directory.Ldap.NETStandard
- AddControllers and AddAuthentication
Program.cs
builder.Services.AddControllers();
builder.Services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
- Login Page (Login.razor)
- Add CascadingAuthenticationState, AuthorizeRouteView in App.razor
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" D
- Modify the MainLayout.razor to show User authentication status and Logout link.
- Modify index.razor for auth content
- Add LDAP auth in LoginController.cs Claim will be username as ClaimTypes.Name and Attribute"gidNumber" as ClaimTypes.Role
var claims = new[]
{
new Claim(ClaimTypes.Name, User.username),
new Claim(ClaimTypes.Role, $"{resultEntity.GetAttribute("gidNumber").StringValue}")
};
Thanks forumsys for the Online LDAP Test Server
LDAP Server Information (read-only access):
Server: ldap.forumsys.com
Port: 389
Bind DN: cn=read-only-admin,dc=example,dc=com Bind Password: password
All user passwords are password.
You may also bind to individual Users (uid) or the two Groups (ou) that include:
ou=mathematicians,dc=example,dc=com
- riemann
- gauss
- euler
- euclid
ou=scientists,dc=example,dc=com
- einstein
- newton
- galieleo
- tesla
You can run docker image by the following command and then see the demo.
docker run -itd -p 8081:80 ieei/blazorserverldaponlinux