Git Product home page Git Product logo

keycloak.net's Introduction

Icon

Keycloak.Net

Build status license NuGet downloads FOSSA Status

C# client for Keycloak 6.x

See documentation at https://www.keycloak.org/docs-api/6.0/rest-api/

Features

  • Attack Detection
  • Authentication Management
  • Client Attribute Certificate
  • Client Initial Access
  • Client Registration Policy
  • Client Role Mappings
  • Client Scopes
  • Clients
  • Component
  • Groups
  • Identity Providers
  • Key
  • Protocol Mappers
  • Realms Admin
  • Role Mapper
  • Roles
  • Roles (by ID)
  • Scope Mappings
  • User Storage Provider
  • Users
  • Root

keycloak.net's People

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  avatar

keycloak.net's Issues

CreateGroupAsync throws 404 not found

I am getting an error when trying to create a group.

var group = new Keycloak.Net.Models.Groups.Group
{
    Name = name,
    Id = id.ToString(),
    Attributes = new Dictionary<string, IEnumerable<string>>
    {
        { JsonKey, new[] { description } },
        { OwnersKey, new[] { $"{Guid.Empty}" } },
    }
};

await _client.CreateGroupAsync(_realm, group); // throws here

Attributes field is missing

Please extend Keycloak.Net.Models.Roles.Role class as follows:

[JsonProperty("attributes")]
public Dictionary<string, string> Attributes { get; set; }

Parsing client ProtocolMapper.Config is broken? (keycloak 15)

When i request information about a client using client.GetClientsAsync(realm, clientId) i get back multiple Client instances, if i then drill down into one and access one ProtocolMappers, and check the Config everything is null.
image

I have done a manual request and then i get the following json response:

{
  "id": "5a0a5ecd-ac69-49ef-8d98-2da9a0a11ba3",
  "name": "Customer ID",
  "protocol": "openid-connect",
  "protocolMapper": "oidc-hardcoded-claim-mapper",
  "consentRequired": false,
  "config": {
    "claim.value": "test",
    "userinfo.token.claim": "false",
    "id.token.claim": "false",
    "access.token.claim": "true",
    "claim.name": "customer_id",
    "jsonType.label": "String",
    "access.tokenResponse.claim": "false"
  }
}

Does this package support keycloak 15 or is it stuck at 6?

`RemoveRolesFromCompositeAsync` uses strange serialisation and fails

hi,
i have noticed, that this method is using some strange serialisation that is nowhere used in the project:

.SendJsonAsync(HttpMethod.Delete, new CapturedJsonContent(_serializer.Serialize(roles)))

and this method fails due to this, i suppose.

Good that there is another method RemoveCompositesFromRoleAsync which still works:

.SendJsonAsync(HttpMethod.Delete, roles)

clientId is HardCoded in FlurlExtensions.cs

                 var result = await url
                .AppendPathSegment($"/auth/realms/{realm}/protocol/openid-connect/token")
                .WithHeader("Content-Type", "application/x-www-form-urlencoded")
                .PostUrlEncodedAsync(new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("grant_type", "client_credentials"),
                    new KeyValuePair<string, string>("client_secret", clientSecret),
                    new KeyValuePair<string, string>("client_id", "admin-cli")    // <-------------------- Hardcoded
                })
                .ReceiveJson().ConfigureAwait(false);

There should be an overload in the constructor of KeycloakClient where client_id could be passed. I could submit a PR.

No proper error message

I am getting the following error when trying to GetUsers. Is this due to some missing configuration in Keycloak server?

image

Create Realm

Great Work,

I just wanted to know if i can create realm by using .net api, i can see GetRealmsAsync , update, and delete.

can u please let me know how can i create new realm ??

thanks again.

this version supports for Keycloak SAML 2.0

Am investigating how to integrate keycloak SAML 2.0 with asp.net application.. Is this Keycloak.Net version supports? and Please provide some sample code would helps me lot.

User attributes serialization issue (dictionary key capitalize issue)

I'm trying to send user attributes during user creation

 var attributes = new Dictionary<string, IEnumerable<string>>
 {
      ["ID"] = new[] {myId}
 };

The problem is that it sends it using "id" key (not "ID").
I think the library creates it's own JsonSerializer with
ContractResolver = (IContractResolver) new CamelCasePropertyNamesContractResolver()
and there is no way to override it with my custom serializer:

new NewtonsoftJsonSerializer(new JsonSerializerSettings
{
      ContractResolver = new DefaultContractResolver
      {
            NamingStrategy = new CamelCaseNamingStrategy
            {
                  ProcessDictionaryKeys = false
            }
       }
});

Should this have more maintainers?

Seems that we have many good PRs waiting and nothing happens.
I have custom build mine for now far too long, Id would like to get this more open and have more maintainers.

@lvermeulen - If you are too busy, maybe fork this to community driven one with more maintainers?

Higher support

Hello,

Is Keycloak.Net supported for versions higher than 6.x?

Thank you in advance!

Kind Regards,
Andrej

Security Warning

I'm not sure that this actually matters to anyone, but when building a license file for a distribution I generally copy-paste the Package name into my browser. In the case of this Package, it sends you to a domain not controlled by Redhat.

Sorry if this is just bloat, but wanted to at least alert the potential security concern.

     Name: KEYCLOAK.NET
    Registry Domain ID: 2134538313_DOMAIN_NET-VRSN
    Domain Status:

    clientDeleteProhibited

    clientTransferProhibited

    clientUpdateProhibited
    Nameservers:

    NS73.DOMAINCONTROL.COM

    NS74.DOMAINCONTROL.COM

Dates

    Registry Expiration: 2021-06-17 05:34:44 UTC
    Created: 2017-06-17 05:34:44 UTC

Role Attributes Type

Hi.

I use keycloak server 10.0.2 and using this library ran into a problem:
Server returns role attributes differently than specified in the class model.

If change role Attributes field from:
IDictionary<string, string>
to:
Dictionary<string, IEnumerable>
Deserialization is successful.

I would be grateful if you update the library and I don't have to use a local modified copy.

With best regards

Add support for GetAllResourcesOwnByCurrentUser

Hello, as we know, in the 'Fine Authorization Mode' in a client, we need to retrieve all resources owning by some user. so i have found the api can do this work:

curl -X POST http://xxxxx.com/auth/realms/{realm}/protocol/openid-connect/token \
    --data "grant_type=urn:ietf:params:oauth:grant-type:uma-ticket" --data "response_mode=permissions" --data "audience={clientID}" -H "Authorization: Bearer $token"

[{"rsid":"48c9b227-87ef-46f9-9fd5-26c6f76a882e","rsname":"Default Resource"},{"rsid":"edb5453a-96be-46c7-9a34-cd966237bd55","rsname":"School"},{"rsid":"6441ddaa-5730-456b-a310-2455e0c4aa27","rsname":"Grade"},{"scopes":["backup","changeStudentInfo","remove"],"rsid":"8b61de15-a6b9-4b64-be1d-0af9481c0d71","rsname":"Student"}]

further more, i hade add some code into Keycloak.Net project and tested, may i PR for this ?

Variabilize grant_type value

@lvermeulen, Can you variabilize the value of the key grant_type in Keycloak.Net/Client/KeycloakClient.cs line 308 please ?

Something like this :


public async Task<IEnumerable<Resource>> GetResourcesOwnedByClientAsync(string realm, string clientId, string grantType) => await GetBaseUrl(realm)
	        .AppendPathSegment($"/realms/{realm}/protocol/openid-connect/token")
	        .PostUrlEncodedAsync(new List<KeyValuePair<string, string>>
	        {
		        new KeyValuePair<string, string>("grant_type", grantType),
		        new KeyValuePair<string, string>("response_mode", "permissions"),
		        new KeyValuePair<string, string>("audience", clientId)
	        })
	        .ReceiveJson<IEnumerable<Resource>>()
	        .ConfigureAwait(false);

I don't have right to commit/push on your repository, so i opend this issue.

Thank you ๐Ÿ˜‰

How to create a new user with client roles

Hello,

I have a basic question and I hope you can help me. Probably it's very stupid.

I'm able to create new users without problems but now I would like to pass client roles with the new user on create. I have to pass a dictionary<string, object> but how does the dictionary really have to look like if I want to pass multiple client-roles for multiple clients?

At the moment I pass it like this but the role is not assigned to the new user afterwards.
ClientRoles = new Dictionary<string, object>() { { "client_name", new string[] { "client_role_name" } }

Can you please give a simple example.

Thank you very much!

Actions for ScopeMapping of Client not working

I have some issue with assign of client-roles in the scope-mappings of client.

This Actions are not working for me:
AddClientRolesScopeMappingToClientAsync
GetClientRolesScopeMappingsForClientAsync
RemoveClientRolesFromClientScopeForClientAsync
GetAvailableClientRolesForClientScopeForClientAsync
GetEffectiveClientRolesForClientScopeForClientAsync

It seems that they are using incorrect api urls / parameters.
For Example : AddClientRolesScopeMappingToClientAsync
the url is POST {realm}/scope-mappings/clients/{clientId}
but it should be: POST /{realm}/clients/{id}/scope-mappings/clients/{client}

see https://www.keycloak.org/docs-api/6.0/rest-api/ (the documentation for scope-mappings of client is in the same section as the docu for scope-mappings of client-scopes. but the api is different...

Administrate across realms

I have a need to use a user defined in one realm to invoke the Keycloak API for a different realm.

KeycloakClient uses the same realm for authentication and API invocation.

Could you provide a way to make these realms different?

ResetUserPassword sends not set optional fields

I trying change password by this:

_client.ResetUserPasswordAsync(_conf.Realm, userId, new Credentials
{
    Value = password,
    Type = "password",
    Temporary = false,
});

Request body is:

{"algorithm":null,"config":null,"counter":null,"createdDate":null,"device":null,"digits":null,"hashIterations":null,"hashSaltedValue":null,"period":null,"salt":null,"temporary":false,"type":"password","value":"123456"}

Throwing exception Flurl.Http.FlurlHttpException: Call failed with status code 400 (Bad Request)

Keycloak answer body:

Unrecognized field "hashSaltedValue" (class org.keycloak.representations.idm.CredentialRepresentation), not marked as ignorable

Issue running tests.

I am having issues running the tests. I keep getting these errors running test.ps1:

ClientAttributeCertificate\KeycloakClientShould.cs(14,51): error CS8306: Tuple element name 'Id' is inferred. Please use language version 7.1 or greater to access an element by its inferred name. [D:\repos\Keycloak.Net\test\Keycloak.Net.Tests\Keycloak.Net.Tests.csproj]
ClientAttributeCertificate\KeycloakClientShould.cs(14,51): error CS8306: Tuple element name 'Key' is inferred. Please use language version 7.1 or greater to access an element by its inferred name. [D:\repos\Keycloak.Net\test\Keycloak.Net.Tests\Keycloak.Net.Tests.csproj]

I have dotnet core sdk 1.1.13 installed:

PS D:\repos\Keycloak.Net\test\Keycloak.Net.Tests> dotnet --info
.NET Command Line Tools (1.1.13)

Product Information:
 Version:            1.1.13
 Commit SHA-1 hash:  b5abece65c

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.16299
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\1.1.13

Host (useful for support):
  Version: 3.0.0
  Commit:  7d57652f33

.NET Core SDKs installed:
  1.1.13 [C:\Program Files\dotnet\sdk]
  2.0.2 [C:\Program Files\dotnet\sdk]
...

Is there something up with my environment?

Add support for user attributes

Hi,
I'd like to access and update custom user attributes. Can you extend the user model with
public Dictionary<string,string> Attributes { get; set; } ?

UserNameStatus deserialization error

Hello,

So I have an issue with the "GetUserNameStatusInBruteForceDetectionAsync" function.
Its response "UserNameStatus" is expecting a long? instead of int? for the field "LastFailure", so it is crashing on the deserialization. Please check the response here below as an example from Keycloak API.

{ "numFailures": 2, "disabled": false, "lastIPFailure": "46.193.6.176", "lastFailure": 1622463072963 }

May you please update the model and the package?

Add Method to pull the list of realms

Sorry I should create a PR for this but I can't at this moment, just create a method under RealmsAdmin/KeycloakClient.cs:

public async Task<IEnumerable<Realm>> GetRealmsAsync(string realm) => await GetBaseUrl(realm) .AppendPathSegment($"/admin/realms") .GetJsonAsync<IEnumerable<Realm>>() .ConfigureAwait(false);

Test method:

[Theory] [InlineData("master")] public async Task GetRealmsAsync(string realm) { var result = await _client.GetRealmsAsync(realm); Assert.NotNull(result); }

Port property missing in SmtpServer Model

In order to be able to set the port in Keycloak, it would be great to have the Port property added on the SmtpServer Model.

I've tried it locally and it works. It's really just a small fix...

Add temporary as parameter

Hi,
Can u please add temporary as parameter in the method ResetUserPasswordAsync ?

public async Task<bool> ResetUserPasswordAsync(string realm, string userId, string password, bool temporary)
		{
			var response = await GetBaseUrl(realm)
				.AppendPathSegment($"/admin/realms/{realm}/users/{userId}/reset-password")
				.PutJsonAsync(new { type = "password", value = password, temporary = temporary })
				.ConfigureAwait(false);
			return response.IsSuccessStatusCode;
		}

Usage with yubikey

Hello,

Is it possible to use the client in association with a Yubikey ? Our keycloak workflow involve user/password + yubikey.

Best regards.

Missing CancellationTokens

Hi,

I noticed that there is no possible way to pass a CancellationToken which results in Flurl using the default value Which is CancellationToken.None.
I'm thinking of making a PR in which I will add the Cancellation Token as an optional parameter for all methods that will trigger an HTTP Call.

Would you be ok with such a change?

GetUserForServiceAccountAsync Obsolete?

Hi you marked GetUserForServiceAccountAsync as oboslete not working.
But for me your function is working with Keycloak Server 6.0.1.
Of course only for clients with ServiceAccountsEnabled, otherwise the api returns 404 which leads to crash in your function.
Is this the reason why it is marked not working or is this deprecated in future keycloak versions?

documentation, says it works with keycloak 6, recently installed keycloak and it is version 13.0.0

Request to update the version this works with.

I see the plugin was recently updated May 7, 2021 so I presume it works but was discouraged when I saw version 6 in the documentation.

Also, the documentation links over to keycloak rest api, but an example with c# would be more helpful. Such as an example which shows what should be in the Startup.cs to get things working on the server side & something similar on the client side.

Non-Existant Documentation

Hi,

Does actual docuementation of the package exist?

The current link to the docs is not documentation for this package, but for something else.

I might be missing something, but I can figure out how to use this package by just the keycloak rest api docs.

Thanks,
Pat

Protocol Mapper Issue

When working with the protocol mappers I encounter a severe bug in the JSON implementation.
This class Keycloak.Net.Models.ProtocolMappers.Config should be changed to Dictionary<string,object>
Per the docs https://www.keycloak.org/docs-api/5.0/rest-api/index.html#_protocolmapperrepresentation this attribute it's type map meaning that there's not defined structure so a named based structure like the one you have is not working and will not retrieve all the information.
please change it to Dictionary class:
see also
https://docs.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonextensiondataattribute?view=net-5.0
https://stackoverflow.com/questions/14893614/how-to-serialize-a-dictionary-as-part-of-its-parent-object-using-json-net

add support for Protection API?

as the title, do we have any plan to support Protection API ?

for example from
Creating a Resource
To create a resource you must send an HTTP POST request as follows:

curl -v -X POST \
  http://${host}:${port}/auth/realms/${realm_name}/authz/protection/resource_set \
  -H 'Authorization: Bearer '$pat \
  -H 'Content-Type: application/json' \
  -d '{
     "name":"Tweedl Social Service",
     "type":"http://www.example.com/rsrcs/socialstream/140-compatible",
     "icon_uri":"http://www.example.com/icons/sharesocial.png",
     "resource_scopes":[
         "read-public",
         "post-updates",
         "read-private",
         "http://www.example.com/scopes/all"
      ]
  }'

Convert Config of Mappings into Dictionaries

Why don't configs of mappings into dictionary?

I used this library recently for audience mapping and role mapping with Keycloak 11.0.0 and I must have to create classes that inherits from configurations and set the corresponding JsonProperty attribute value. For instance:

public class KeycloakClientConfig : ClientConfig
{
    [JsonProperty("multivalued")]
    public string MultiValued { get; set; }

    [JsonProperty("usermodel.clientRoleMapping.clientId")]
    public string UserModelClientRoleMappingClientId { get; set; }

    [JsonProperty("userinfo.token.claim")]
    public string CustomUserInfoTokenClaim { get; set; }

    [JsonProperty("claim.name")]
    public string CustomClaimName { get; set; }

    [JsonProperty("access.token.claim")]
    public string CustomAccessTokenClaim { get; set; }

    [JsonProperty("id.token.claim")]
    public string CustomIdTokenClaim { get; set; }

    [JsonProperty("jsonType.label")]
    public string JsonTypeLabel { get; set; }
}

If you turn this into a dictionary should be easy set such values.

Flurl.StringExtensions

Hello,

I'm getting this error, what doe's it mean?
System.TypeLoadException: Could not load type 'Flurl.StringExtensions' from assembly 'Flurl, Version=3.0.1.0, Culture=neutral, PublicKeyToken=null'

Thank you in advance!

Kind Regards,
Andrej

No longer maintained

If this project is no longer maintained (and it appears to be that way) would you archive the project and add a link to an actively maintained fork (like this one) please?

Find an alternative to JsonConvert.DefaultSettings

In the static constructor for KeycloakClient, a method is assigned to JsonConvert.DefaultSettings that sets the contract resolver to CamelCasePropertyNamesContractResolver. When using this library in a project that is already using Json.Net (Newtonsoft.Json), this will overwrite the default settings across the entire project.

As an example, I have a project that frequently serializes to/deserializes from JSON. Until an instance of KeycloakClient is created Json.Net's default TitleCasing is used, and after the instantiation occurs all of the objects that I've previously serialized can no longer be deserialized.

What makes this worse is that the serialization/deserialization happens in 2 separate services, one that has a reference to Keycloak.Net and one that doesn't. The end result is that while the service that uses Keycloak.Net would be able to deserialize the object correctly, the one that doesn't is still expecting the serialized object to be TitleCased.

I'm definitely planning on putting in the time to work on this and create a PR, but I'm curious about the original motivations to put this in place so I'm not causing a regression.

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.