keycloak-ruby-client 0.0.5

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 8d9e6755953b3b7c1e98116ebeeb55107b54f058
4
+ data.tar.gz: 21ab42c066be34c26e4077a7d10a9884e3f387a5
5
+ SHA512:
6
+ metadata.gz: b5192d922842967e6586dfee0b88a24d5c99e09dcb7d2a75e76136ac5c39ab90479cf23fc6a71acb9938c58d893a05a7b028c6f7b473ab5469f3e58d6296a4ad
7
+ data.tar.gz: c21b0568ce50e660a36b3f7bf905707523f4bb784bafcaba7bfd01ae1e41a0f23c30f9030da1ea700713b020913b6ac4ce3b6d2a5fdf555b6d075bcb9daa2478
data/.gitignore ADDED
@@ -0,0 +1,25 @@
1
+ .ruby-version
2
+ doc/
3
+ .yardoc/
4
+ guides/yardoc/
5
+ pkg/
6
+ Gemfile.lock
7
+ gemfiles/*.lock
8
+ # Test database
9
+ *.db
10
+ .bundle/
11
+ vendor/
12
+ .idea/
13
+
14
+ _site
15
+ .sass-cache
16
+ .jekyll-metadata
17
+ gh-pages/
18
+ tmp/*
19
+ __*.db
20
+ node_modules/
21
+ yarn.lock
22
+ OperationStoreClient.js
23
+ spec/integration/tmp
24
+ .vscode/
25
+ *.gem
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at haofxpro@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in keycloak-ruby-client.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Fuxin Hao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,160 @@
1
+ # Keycloak::Ruby::Client
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/keycloak-ruby-client.svg)](https://badge.fury.io/rb/keycloak-ruby-client)
4
+
5
+ This is a keycloak client implementation in ruby. I mainly use this in a rails project, so this is
6
+ written with some methods that derive from rails.
7
+
8
+ ## Installation
9
+
10
+ Add this line to your application's Gemfile:
11
+
12
+ ```ruby
13
+ gem 'keycloak-ruby-client', require: 'keycloak'
14
+ ```
15
+
16
+ And then execute:
17
+
18
+ $ bundle
19
+
20
+ Or install it yourself as:
21
+
22
+ $ gem install keycloak-ruby-client
23
+
24
+ ## Usage
25
+
26
+ Firstly, you need to register your keycloak config:
27
+
28
+ ```ruby
29
+ Keycloak::Realm.register do |config|
30
+ config.installation_file = Rails.root.join("config/keycloak.json")
31
+ end
32
+ ```
33
+
34
+ or
35
+
36
+ ```ruby
37
+ Keycloak::Realm.register do |config|
38
+ config.auth_server_url = "http://127.0.0.1:8081/auth"
39
+
40
+ config.realm = "shundao-admin"
41
+ end
42
+ ```
43
+
44
+ Then you can authenticate your keycloak JWT token:
45
+
46
+ ```ruby
47
+ token = "your_bearer_token"
48
+ keycloak_token = .parse_access_token(token) # an instance of Keycloak::AccessToken
49
+ raise CanCan::AccessDenied if keycloak_token.expired? || !keycloak_token.has_role?("admin")
50
+
51
+ # authentication succeeded
52
+ ```
53
+
54
+ Or you may need asking if permissions are granted from keycloak server, it's also worth noting that
55
+ this is much expensive than decoding JWT cuz this asks from keycloak server every time.
56
+ Always use JWT unless there is a compelling reason to use this.
57
+
58
+ ```ruby
59
+ token = "your_bearer_token"
60
+ keycloak_token = Keycloak::Realm.shundao_admin.parse_access_token(token)
61
+ raise Cancan::AccessDenied unless Keycloak::Realm.shundao_admin.client.granted_by_server("Admin Resources#view", keycloak_token)
62
+
63
+ # authentication succeeded
64
+ ```
65
+
66
+ Some examples demonstrate how to interact with Keycloak admin REST API:
67
+
68
+ ```ruby
69
+ admin_username = ENV['KEYCLOAK_USERNAME'] || 'admin'
70
+ admin_password = ENV['KEYCLOAK_PASSWORD'] || 'admin'
71
+ auth_server_url = ENV['KEYCLOAK_SERVER_URL'] || 'http://127.0.0.1:8081/auth'
72
+ realm = 'shundao-admin'
73
+
74
+ # authenticate
75
+ client = Keycloak::Client.new(auth_server_url, realm)
76
+ client.authenticate(admin_username, admin_password, "password", "admin-cli", "master")
77
+
78
+ # create the roles
79
+ role_store = {}
80
+ roles = ['user', 'premium', 'admin']
81
+ roles.each do |role|
82
+ role_rep = Keycloak::Model::RoleRepresentation.new({
83
+ name: role
84
+ })
85
+ role_store[role] = client.create_or_find_role(role_rep)
86
+ end
87
+
88
+ # create a user with the roles created above
89
+ user_rep = Keycloak::Model::UserRepresentation.new({
90
+ username: "alice",
91
+ credentials: [
92
+ Keycloak::Model::CredentialRepresentation.new({
93
+ type: "password",
94
+ temporary: false,
95
+ value: '123456'
96
+ })
97
+ ],
98
+ enabled: true,
99
+ requiredActions: ['UPDATE_PASSWORD']
100
+ })
101
+ mapping_roles = role_store.map { |entry| {id: entry[1].id , name: entry[1].name} }
102
+ client.create_user(user_rep, mapping_roles)
103
+ ```
104
+
105
+ ### Connect your rails user model with keycloak user entity:
106
+
107
+ Firstly, we create a user model with `bundle exec rails g model user`
108
+
109
+ In you migration file:
110
+ ```Ruby
111
+ class CreateUsers < ActiveRecord::Migration[5.1]
112
+ def change
113
+ create_table :users, id: :string do |t|
114
+ t.string :username
115
+ end
116
+ end
117
+ end
118
+ ```
119
+
120
+ Authenticate your client in `config/initializers/keycloak.rb`:
121
+
122
+ ```ruby
123
+ Keycloak::Realm.shundao_admin.client.authenticate(admin_username, admin_password, "password", "admin-cli", "master", auto: true)
124
+ ```
125
+
126
+ Your model file `User.rb` as the following:
127
+
128
+ ```ruby
129
+ class User < ApplicationRecord
130
+ include Keycloak::UserEntity
131
+
132
+ use_keycloak_client Keycloak::Realm.shundao_admin.client
133
+ end
134
+ ```
135
+
136
+ Finally, you can get user info with `User` model:
137
+
138
+ ```ruby
139
+ user = User.take
140
+ puts user.user_info
141
+ puts user.realm_roles
142
+ ```
143
+
144
+ ## Development
145
+
146
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
147
+
148
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
149
+
150
+ ## Contributing
151
+
152
+ Bug reports and pull requests are welcome on GitHub at https://github.com/FX-HAO/keycloak-ruby-client. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
153
+
154
+ ## License
155
+
156
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
157
+
158
+ ## Code of Conduct
159
+
160
+ Everyone interacting in the Keycloak::Ruby::Client project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/FX-HAO/keycloak-ruby-client/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,5 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
3
+
4
+ gem 'rails'
5
+ gem 'rest-client'
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "keycloak/ruby/client"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,45 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "keycloak/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "keycloak-ruby-client"
8
+ spec.version = Keycloak::VERSION
9
+ spec.authors = ["Fuxin Hao"]
10
+ spec.email = ["haofxpro@gmail.com"]
11
+
12
+ spec.summary = %q{Keycloak ruby client}
13
+ spec.description = %q{Keycloak ruby client}
14
+ spec.homepage = "https://github.com/FX-HAO/keycloak-ruby-client"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata["allowed_push_host"] = "https://rubygems.org/"
21
+
22
+ spec.metadata["homepage_uri"] = spec.homepage
23
+ spec.metadata["source_code_uri"] = "https://github.com/FX-HAO/keycloak-ruby-client"
24
+ spec.metadata["changelog_uri"] = "https://github.com/FX-HAO/keycloak-ruby-client/blob/master/CHANGELOG.md"
25
+ else
26
+ raise "RubyGems 2.0 or newer is required to protect against " \
27
+ "public gem pushes."
28
+ end
29
+
30
+ # Specify which files should be added to the gem when it is released.
31
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
32
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
33
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
34
+ end
35
+ spec.bindir = "exe"
36
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
37
+ spec.require_paths = ["lib"]
38
+
39
+ spec.add_dependency "rails", ">= 4.0"
40
+ spec.add_dependency "rest-client", "~> 2.0"
41
+ spec.add_dependency "concurrent-ruby", "~> 1.0"
42
+
43
+ spec.add_development_dependency "bundler", "~> 2.0"
44
+ spec.add_development_dependency "rake", "~> 10.0"
45
+ end
@@ -0,0 +1,59 @@
1
+ module Keycloak
2
+ class AccessToken
3
+ attr_reader :metadata, :jti, :exp, :sub, :azp, :roles, :scope,
4
+ :phone_number, :username, :access_token, :client_roles
5
+
6
+ def initialize(realm, access_token, decoded_token)
7
+ @realm = realm
8
+ @access_token = access_token
9
+ @metadata = decoded_token[0]
10
+ @jti = @metadata["jti"]
11
+ @exp = Time.at(@metadata["exp"]).to_datetime
12
+ @sub = @metadata["sub"]
13
+ @azp = @metadata["azp"]
14
+ if realm_access = @metadata["realm_access"]
15
+ @roles = realm_access["roles"] || []
16
+ end
17
+ if resource_access = @metadata["resource_access"]
18
+ @client_roles = resource_access.dig(realm.name, "roles") || []
19
+ end
20
+ @scope = @metadata["scope"]
21
+ @phone_number = @metadata["phone_number"]
22
+ @username = @metadata["username"] || @metadata["preferred_username"]
23
+ end
24
+
25
+ def authorization
26
+ "Bearer #{@access_token}"
27
+ end
28
+
29
+ def expired?
30
+ exp < DateTime.now
31
+ end
32
+
33
+ def has_role?(role, include_client_role = true)
34
+ roles.include?(role.to_s) || (include_client_role && has_client_role?(role))
35
+ end
36
+
37
+ def has_client_role?(role)
38
+ client_roles.include? role.to_s
39
+ end
40
+
41
+ def method_missing(name, *args, &block)
42
+ regex = /^has_(.*?)_role\?$/
43
+ if name.match?(regex)
44
+ return name.match(regex)[1]
45
+ end
46
+
47
+ super
48
+ end
49
+
50
+ def respond_to_missing?(name, include_private = false)
51
+ regex = /^has_(.*?)_role\?$/
52
+ if name.match?(regex)
53
+ return true
54
+ end
55
+
56
+ super
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,27 @@
1
+ module Keycloak
2
+ module API
3
+ module ClientResources
4
+ extend ActiveSupport::Concern
5
+ include Concerns::APIUtil
6
+
7
+ # @param client_id [String] client-id (not id of client)
8
+ # @return [Keycloak::Model::ClientRepresentation] client representation
9
+ def find_client_by_client_id(client_id)
10
+ url = admin_realm_url + "/clients"
11
+ data = JSON.parse(get(url, params: { clientId: client_id }).body)
12
+ data[0] && Model::ClientRepresentation.new(data[0])
13
+ rescue RestClient::NotFound
14
+ nil
15
+ end
16
+
17
+ # @param id [String] id of client (not client-id)
18
+ # @return [Keycloak::Model::ClientRepresentation] client representation
19
+ def find_client_by_id(id)
20
+ url = admin_realm_url + "/clients/#{id}"
21
+ Model::ClientRepresentation.new JSON.parse(get(url).body)
22
+ rescue RestClient::NotFound
23
+ nil
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,55 @@
1
+ module Keycloak
2
+ module API
3
+ module ClientRoleResources
4
+ extend ActiveSupport::Concern
5
+ include Concerns::APIUtil
6
+
7
+ # @param id [String] id of client (not client-id)
8
+ # @param role_rep [Keycloak::Model::RoleRepresentation] role representation
9
+ def create_client_role(id, role_rep)
10
+ url = admin_realm_url + "/clients/#{id}/roles"
11
+ post(url, role_rep.to_json, headers: {content_type: :json})
12
+ end
13
+
14
+ # @param id [String] id of client (not client-id)
15
+ # @return [Array<Keycloak::Model::ClientRepresentation>] an array of client representations
16
+ def find_client_roles(id)
17
+ url = admin_realm_url + "/clients/#{id}/roles"
18
+ JSON.parse(get(url)).map { |role| Model::RoleRepresentation.new role }
19
+ end
20
+
21
+ # @param id [String] id of client (not client-id)
22
+ # @param name [String] name of role
23
+ # @return [Keycloak::Model::RoleRepresentation] role representation
24
+ def find_client_role_by_name(id, name)
25
+ url = admin_realm_url + "/clients/#{id}/roles/#{name}"
26
+ Model::RoleRepresentation.new JSON.parse(get(url))
27
+ rescue RestClient::NotFound
28
+ nil
29
+ end
30
+
31
+ # @param user_id [String] user id
32
+ # @param id_of_client [String] id of client (not client-id)
33
+ # @return [Array<Keycloak::Model::RoleRepresentation>] role representations
34
+ def find_client_roles_for_user(user_id, id_of_client)
35
+ url = admin_realm_url + "/users/#{user_id}/role-mappings/clients/#{id_of_client}"
36
+ JSON.parse(get(url)).map { |role| Model::RoleRepresentation.new role }
37
+ end
38
+
39
+ # Only role id and role name are required in role_mappings
40
+ #
41
+ # @param user_id [String] user id
42
+ # @param id_of_client [String] id of client (not client-id)
43
+ # @param role_mappings [Array<Keycloak::Model::RoleRepresentation>] an array of roles
44
+ def add_client_role_mapping(user_id, id_of_client, role_mappings)
45
+ url = admin_realm_url + "/users/#{user_id}/role-mappings/clients/#{id_of_client}"
46
+ post(url, role_mappings.to_json, headers: {content_type: :json})
47
+ end
48
+
49
+ def remove_client_role_mapping(user_id, id_of_client, role_mappings)
50
+ url = admin_realm_url + "/users/#{user_id}/role-mappings/clients/#{id_of_client}"
51
+ delete(url, payload: role_mappings.to_json, headers: {content_type: :json})
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,37 @@
1
+ module Keycloak
2
+ module API
3
+ module ProtectionResources
4
+ extend ActiveSupport::Concern
5
+ include Concerns::APIUtil
6
+
7
+ # use this when you are mainly interested in either the overall decision
8
+ # or the permissions granted by the server, this is much expensive than
9
+ # decoding JWT cuz this asks from keycloak server every time. Always use
10
+ # JWT unless there is a compelling reason to use this.
11
+ #
12
+ # @param permissions [String] A string representing a set of one or more
13
+ # resources and scopes the client is seeking access. The format of the
14
+ # string must be: RESOURCE_ID#SCOPE_ID. For instance:
15
+ # Resource A#Scope A, Resource A#Scope A, Scope B, Scope C, Resource A,
16
+ # #Scope A. See https://www.keycloak.org/docs/latest/authorization_services/#_service_obtaining_permissions
17
+ # for more details.
18
+ # @param access_token [Keycloak::AccessToken] access token
19
+ # @return [Boolean] true if the permissions granted or false when forbidden
20
+ def granted_by_server(permissions, access_token)
21
+ url = admin_realm_url + "/protocol/openid-connect/token"
22
+ res = JSON.parse post(url, {
23
+ grant_type: "urn:ietf:params:oauth:grant-type:uma-ticket",
24
+ audience: @realm,
25
+ permission: permissions,
26
+ response_mode: "decision"
27
+ },
28
+ headers: {content_type: :json, authorization: access_token.authorization},
29
+ try_refresh_token: false
30
+ )
31
+ res['result']
32
+ rescue RestClient::Forbidden, RestClient::Unauthorized
33
+ false
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,63 @@
1
+ module Keycloak
2
+ module API
3
+ module RoleResources
4
+ extend ActiveSupport::Concern
5
+ include Concerns::APIUtil
6
+
7
+ # @param role_rep [Keycloak::Model::RoleRepresentation] role representation
8
+ def create_role(role_rep)
9
+ url = admin_realm_url + "/roles"
10
+ post(url, role_rep.to_json, headers: {content_type: :json})
11
+ end
12
+
13
+ # @return [Array<Keycloak::Model::RoleRepresentation>] role representations
14
+ def realm_roles
15
+ url = admin_realm_url + "/roles"
16
+ JSON.parse(get(url)).map { |role| Model::RoleRepresentation.new role }
17
+ end
18
+
19
+ # @param name [String] name of role
20
+ # @return [Keycloak::Model::RoleRepresentation] role representation
21
+ def find_role_by_name(name)
22
+ url = admin_realm_url + "/roles/#{name}"
23
+ Model::RoleRepresentation.new JSON.parse(get(url).body)
24
+ rescue RestClient::NotFound
25
+ nil
26
+ end
27
+
28
+ # @param role_rep [Keycloak::Model::RoleRepresentation] role representation
29
+ # @return [Keycloak::Model::RoleRepresentation] role representation
30
+ def create_or_find_role(role_rep)
31
+ create_role(role_rep) && find_role_by_name(role_rep.name)
32
+ rescue RestClient::Conflict
33
+ find_role_by_name(role_rep.name)
34
+ end
35
+
36
+ # @param user_id [String] user id
37
+ # @return [Array<Keycloak::Model::RoleRepresentation>] an array of role representations
38
+ def find_user_realm_roles(user_id)
39
+ JSON.parse(get("#{user_resources_url}/#{user_id}/role-mappings/realm")).map do |role|
40
+ Model::RoleRepresentation.new role
41
+ end
42
+ end
43
+
44
+ # Only role id and role name are required in role_mappings
45
+ #
46
+ # @param user_id [String] user id
47
+ # @param role_mappings [Array<Keycloak::Model::RoleRepresentation>] an array of roles
48
+ def add_role_mapping(user_id, role_mappings)
49
+ url = admin_realm_url + "/users/#{user_id}/role-mappings/realm"
50
+ post(url, role_mappings.to_json, headers: {content_type: :json})
51
+ end
52
+
53
+ # Only role id and role name are required in role_mappings
54
+ #
55
+ # @param user_id [String] user id
56
+ # @param role_mappings [Array<Keycloak::Model::RoleRepresentation>] an array of roles
57
+ def remove_role_mapping(user_id, role_mappings)
58
+ url = admin_realm_url + "/users/#{user_id}/role-mappings/realm"
59
+ delete(url, payload: role_mappings.to_json, headers: {content_type: :json})
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,42 @@
1
+ module Keycloak
2
+ module API
3
+ # see https://www.keycloak.org/docs-api/6.0/rest-api/index.html#_users_resource for params details
4
+ module UserResources
5
+ extend ActiveSupport::Concern
6
+ include Concerns::APIUtil
7
+
8
+ def user_resources_url
9
+ admin_realm_url + "/users"
10
+ end
11
+
12
+ # Keycloak server doesn't support assign roles at creating user,
13
+ # so we actually implement this in 2 steps.
14
+ #
15
+ # @param user_rep [Keycloak::Model::UserRepresentation] user representation
16
+ # @param roles [Array] an array of roles
17
+ def create_user(user_rep, roles = [])
18
+ res = post(user_resources_url, user_rep.to_json, headers: {content_type: :json})
19
+ id = res.headers[:location].split("/")[-1]
20
+ return if roles.empty?
21
+ add_role_mapping(id, roles)
22
+ end
23
+
24
+ # @param id [String] user id
25
+ # @return [Keycloak::Model::UserRepresentation] user representation
26
+ def find_user(id)
27
+ Model::UserRepresentation.new JSON.parse(get("#{user_resources_url}/#{id}"))
28
+ end
29
+
30
+ # see https://www.keycloak.org/docs-api/6.0/rest-api/index.html#_users_resource for params details
31
+ def find_users(params = {})
32
+ res = JSON.parse(get(user_resources_url, params: params))
33
+ res.map { |user| Model::UserRepresentation.new user }
34
+ end
35
+
36
+ def find_user_by_username(username)
37
+ find_users({username: username})[0]
38
+ end
39
+
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,5 @@
1
+ require 'keycloak/api/protection_resources'
2
+ require 'keycloak/api/role_resources'
3
+ require 'keycloak/api/user_resources'
4
+ require 'keycloak/api/client_resources'
5
+ require 'keycloak/api/client_role_resources'
@@ -0,0 +1,112 @@
1
+ module Keycloak
2
+ class Client
3
+ include API::UserResources
4
+ include API::RoleResources
5
+ include API::ProtectionResources
6
+ include API::ClientResources
7
+ include API::ClientRoleResources
8
+
9
+ attr_reader :auth_server_url, :realm
10
+
11
+ def initialize(auth_server_url, realm)
12
+ @auth_server_url = auth_server_url
13
+ @realm = realm
14
+ end
15
+
16
+ def realm_url
17
+ "#{@auth_server_url}/realms/#{@realm}"
18
+ end
19
+
20
+ def admin_realm_url
21
+ "#{@auth_server_url}/admin/realms/#{@realm}"
22
+ end
23
+
24
+ def authenticate(username, password, grant_type, client_id, realm = @realm, auto: true)
25
+ @authenticate_realm = realm
26
+ @authenticate_client_id = client_id
27
+ if auto
28
+ @authenticate_username = username
29
+ @authenticate_password = password
30
+ @authenticate_grant_type = grant_type
31
+ end
32
+
33
+ url = "#{@auth_server_url}/realms/#{realm}/protocol/openid-connect/token"
34
+ res = JSON.parse post(url, {
35
+ username: username,
36
+ password: password,
37
+ grant_type: grant_type,
38
+ client_id: client_id
39
+ }, try_refresh_token: false).body
40
+ @access_token = res["access_token"]
41
+ @refresh_token = res["refresh_token"]
42
+ @refresh_expires_in = DateTime.now + res["refresh_expires_in"].seconds
43
+ @expires_in = DateTime.now + res["expires_in"].seconds
44
+ true
45
+ end
46
+
47
+ def refresh_token!
48
+ raise "need to call `authenticate` first" unless @refresh_token
49
+
50
+ url = "#{@auth_server_url}/realms/#{@authenticate_realm}/protocol/openid-connect/token"
51
+ res = JSON.parse post(url, {
52
+ grant_type: "refresh_token",
53
+ client_id: @authenticate_client_id,
54
+ refresh_token: @refresh_token
55
+ }, try_refresh_token: false)
56
+ @access_token = res["access_token"]
57
+ @refresh_token = res["refresh_token"]
58
+ @refresh_expires_in = DateTime.now + res["refresh_expires_in"].seconds
59
+ @expires_in = DateTime.now + res["expires_in"].seconds
60
+ end
61
+
62
+ def access_token_expired?
63
+ @expires_in && @expires_in < DateTime.now
64
+ end
65
+
66
+ def refresh_token_expired?
67
+ @refresh_expires_in && @refresh_expires_in < DateTime.now
68
+ end
69
+
70
+ def try_refresh_token!
71
+ return unless access_token_expired?
72
+
73
+ if !refresh_token_expired?
74
+ refresh_token!
75
+ elsif @authenticate_username && @authenticate_password
76
+ authenticate(@authenticate_username, @authenticate_password, @authenticate_grant_type, @authenticate_client_id, @authenticate_realm, auto: false)
77
+ else
78
+ raise("Refresh token expired, you should re-authenticate to obtain an access token or enable auto authentication")
79
+ end
80
+ end
81
+
82
+ def post(url, payload, headers: {}, try_refresh_token: true)
83
+ try_refresh_token! if try_refresh_token
84
+
85
+ RestClient.post(url, payload, {
86
+ authorization: "Bearer #{@access_token}",
87
+ accept: "application/json"
88
+ }.merge(headers))
89
+ end
90
+
91
+ def get(url, headers: {}, params: {}, try_refresh_token: true)
92
+ try_refresh_token! if try_refresh_token
93
+
94
+ RestClient.get(url, {
95
+ authorization: "Bearer #{@access_token}",
96
+ accept: "application/json",
97
+ params: params
98
+ }.merge(headers))
99
+ end
100
+
101
+ def delete(url, headers: {}, payload: nil, try_refresh_token: true)
102
+ try_refresh_token! if try_refresh_token
103
+
104
+ RestClient::Request.execute(
105
+ method: :delete, url: url, payload: payload,
106
+ headers: {
107
+ authorization: "Bearer #{@access_token}",
108
+ accept: "application/json"
109
+ }.merge(headers))
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,27 @@
1
+ module Keycloak
2
+ module Concerns
3
+ module APIUtil
4
+ extend ActiveSupport::Concern
5
+
6
+ def realm_url
7
+ raise NotImplementedError
8
+ end
9
+
10
+ def admin_realm_url
11
+ raise NotImplementedError
12
+ end
13
+
14
+ def post(url, payload, headers: {}, try_refresh_token: true)
15
+ raise NotImplementedError
16
+ end
17
+
18
+ def get(url, headers: {}, params: {}, try_refresh_token: true)
19
+ raise NotImplementedError
20
+ end
21
+
22
+ def delete(url, headers: {}, payload: nil, try_refresh_token: true)
23
+ raise NotImplementedError
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1 @@
1
+ require 'keycloak/concerns/api_util'
@@ -0,0 +1,78 @@
1
+ module Keycloak
2
+ module Model
3
+ class BaseRepresentation
4
+ class << self
5
+ def fields(*names)
6
+ names.each do |name|
7
+ field name
8
+ end
9
+ end
10
+
11
+ def field(name, type = :any)
12
+ define_reader name, type
13
+ define_writer name, type
14
+
15
+ name_sym = name.to_sym
16
+ attributes << name_sym
17
+ registry[name_sym] = type
18
+ end
19
+
20
+ def type_resolve(value, type)
21
+ case
22
+ when type == :any
23
+ value
24
+ when type == Integer
25
+ value.to_i
26
+ when type == String
27
+ value.to_s
28
+ when type == Float
29
+ value.to_f
30
+ when type.is_a?(Scalar::ArrayType)
31
+ value.map { |e| type_resolve(e, type.type) }
32
+ when type < BaseRepresentation
33
+ value.is_a?(type) ? value : type.new(value)
34
+ else
35
+ type.new value
36
+ end
37
+ end
38
+
39
+ def define_reader(name, type)
40
+ attr_reader name
41
+ end
42
+
43
+ def define_writer(name, type)
44
+ define_method "#{name}=" do |value|
45
+ instance_variable_set("@#{name}", self.class.type_resolve(value, type))
46
+ end
47
+ end
48
+
49
+ def attributes
50
+ @attributes ||= Concurrent::Array.new
51
+ end
52
+
53
+ def registry
54
+ @registry ||= Concurrent::Hash.new
55
+ end
56
+ end
57
+
58
+ def initialize(payload = {})
59
+ payload.each do |key, value|
60
+ send("#{key}=", value) if self.class.attributes.include?(key.to_sym)
61
+ end
62
+ end
63
+
64
+ def as_json(*options)
65
+ h = {}
66
+ self.class.attributes.each do |attr|
67
+ v = instance_variable_get("@#{attr}")
68
+ h[attr] = v unless v.nil?
69
+ end
70
+ h
71
+ end
72
+
73
+ def to_json
74
+ as_json.to_json
75
+ end
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,12 @@
1
+ module Keycloak
2
+ module Model
3
+ class ClientRepresentation < BaseRepresentation
4
+ fields :id, :clientId, :name, :baseUrl, :surrogateAuthRequired, :enabled,
5
+ :clientAuthenticatorType, :redirectUris, :webOrigins, :notBefore, :bearerOnly,
6
+ :consentRequired, :standardFlowEnabled, :implicitFlowEnabled, :directAccessGrantsEnabled,
7
+ :serviceAccountsEnabled, :publicClient, :frontchannelLogout, :protocol, :attributes,
8
+ :authenticationFlowBindingOverrides, :fullScopeAllowed, :nodeReRegistrationTimeout,
9
+ :protocolMappers, :defaultClientScopes, :optionalClientScopes, :access
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,9 @@
1
+ module Keycloak
2
+ module Model
3
+ class CredentialRepresentation < BaseRepresentation
4
+ fields :algorithm, :config, :counter, :createdDate, :device, :digits,
5
+ :hashIterations, :hashedSaltedValue, :period, :salt, :temporary,
6
+ :type, :value
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,7 @@
1
+ module Keycloak
2
+ module Model
3
+ class RoleRepresentation < BaseRepresentation
4
+ fields :clientRole, :composite, :containerId, :description, :id, :name
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,13 @@
1
+ module Keycloak
2
+ module Model
3
+ class UserRepresentation < BaseRepresentation
4
+ fields :id, :createdTimestamp, :username, :enabled, :totp, :emailVerified,
5
+ :disableableCredentialTypes, :requiredActions, :notBefore, :access,
6
+ :attributes, :clientConsents, :clientRoles, :credentials, :email,
7
+ :federatedIdentities, :federationLink, :firstName, :groups, :lastName,
8
+ :origin, :realmRoles, :self, :serviceAccountClientId
9
+
10
+ field :credentials, Scalar::ArrayType.new(CredentialRepresentation)
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,5 @@
1
+ require 'keycloak/model/base_representation'
2
+ require 'keycloak/model/credential_representation'
3
+ require 'keycloak/model/role_representation'
4
+ require 'keycloak/model/user_representation'
5
+ require 'keycloak/model/client_representation'
@@ -0,0 +1,58 @@
1
+ module Keycloak
2
+ class Realm
3
+ @realms = Concurrent::Map.new
4
+
5
+ class Configuration
6
+ attr_accessor :auth_server_url, :realm, :installation_file
7
+ end
8
+
9
+ class << self
10
+ def register(&block)
11
+ return unless block_given?
12
+
13
+ cfg = Configuration.new
14
+ block.call(cfg)
15
+ if file = cfg.installation_file
16
+ file_cfg = JSON.parse(File.read(file))
17
+ realm_key = file_cfg['realm'].underscore.to_sym
18
+ @realms[realm_key] = Realm.new(file_cfg['auth-server-url'], file_cfg['realm'])
19
+ else
20
+ realm_key = cfg.realm.underscore.to_sym
21
+ @realms[realm_key] = Realm.new(cfg.auth_server_url, cfg.realm)
22
+ end
23
+
24
+ define_singleton_method(realm_key) { @realms[realm_key] }
25
+ end
26
+ end
27
+
28
+ attr_accessor :auth_server_url, :realm
29
+
30
+ def initialize(auth_server_url, realm)
31
+ @auth_server_url = auth_server_url
32
+ @realm = realm
33
+ end
34
+
35
+ def name
36
+ realm
37
+ end
38
+
39
+ def parse_access_token(access_token)
40
+ decoded_token = JWT.decode access_token, public_key, false, { :algorithm => 'RS256' }
41
+ AccessToken.new self, access_token, decoded_token
42
+ end
43
+
44
+ def client
45
+ @client ||= Client.new(auth_server_url, realm)
46
+ end
47
+
48
+ private
49
+
50
+ def public_key
51
+ return @public_key if @public_key
52
+
53
+ keys = JSON.parse(RestClient.get("#{auth_server_url}/realms/#{realm}/protocol/openid-connect/certs").body)['keys']
54
+ jwk = JSON::JWK.new(keys[0])
55
+ @public_key = jwk.to_key
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,11 @@
1
+ module Keycloak
2
+ module Scalar
3
+ class ArrayType
4
+ attr_accessor :type
5
+
6
+ def initialize(type)
7
+ @type = type
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1 @@
1
+ require 'keycloak/scalar/array_type'
@@ -0,0 +1,36 @@
1
+ module Keycloak
2
+ module UserEntity
3
+ extend ActiveSupport::Concern
4
+
5
+ class_methods do
6
+ cattr_reader :keycloak_client
7
+
8
+ # @param client [Keycloak::Client] keycloak client
9
+ def use_keycloak_client(client)
10
+ @keycloak_client = client
11
+ end
12
+ end
13
+
14
+ included do
15
+ def keycloak_identify
16
+ id
17
+ end
18
+
19
+ def user_info(reload = false)
20
+ _set_or_get_keycloak_data(:user_info, reload) { keycloak_client.find_user(keycloak_identify) }
21
+ end
22
+
23
+ def realm_roles(reload = false)
24
+ _set_or_get_keycloak_data(:realm_roles, reload) { keycloak_client.find_user_realm_roles(keycloak_identify) }
25
+ end
26
+
27
+ def has_role?(role)
28
+ realm_roles.include?(role)
29
+ end
30
+
31
+ def _set_or_get_keycloak_data(attr_name, reload)
32
+ reload ? instance_variable_set(yield) : instance_variable_get(attr_name) || instance_variable_set(yield)
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,3 @@
1
+ module Keycloak
2
+ VERSION = "0.0.5"
3
+ end
data/lib/keycloak.rb ADDED
@@ -0,0 +1,10 @@
1
+ require_relative 'keycloak/version'
2
+ require_relative 'keycloak/concerns'
3
+ require_relative 'keycloak/access_token'
4
+ require_relative 'keycloak/realm' # require 'keycloak/realm' not working, weird
5
+ # require 'keycloak/realm'
6
+ require_relative 'keycloak/user_entity'
7
+ require_relative 'keycloak/scalar'
8
+ require_relative 'keycloak/api'
9
+ require_relative 'keycloak/client'
10
+ require_relative 'keycloak/model'
metadata ADDED
@@ -0,0 +1,149 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: keycloak-ruby-client
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.5
5
+ platform: ruby
6
+ authors:
7
+ - Fuxin Hao
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-08-20 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rails
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '4.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '4.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rest-client
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '2.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '2.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: concurrent-ruby
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: bundler
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '2.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '2.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rake
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '10.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '10.0'
83
+ description: Keycloak ruby client
84
+ email:
85
+ - haofxpro@gmail.com
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - ".gitignore"
91
+ - CODE_OF_CONDUCT.md
92
+ - Gemfile
93
+ - LICENSE.txt
94
+ - README.md
95
+ - Rakefile
96
+ - bin/console
97
+ - bin/setup
98
+ - keycloak-ruby-client.gemspec
99
+ - lib/keycloak.rb
100
+ - lib/keycloak/access_token.rb
101
+ - lib/keycloak/api.rb
102
+ - lib/keycloak/api/client_resources.rb
103
+ - lib/keycloak/api/client_role_resources.rb
104
+ - lib/keycloak/api/protection_resources.rb
105
+ - lib/keycloak/api/role_resources.rb
106
+ - lib/keycloak/api/user_resources.rb
107
+ - lib/keycloak/client.rb
108
+ - lib/keycloak/concerns.rb
109
+ - lib/keycloak/concerns/api_util.rb
110
+ - lib/keycloak/model.rb
111
+ - lib/keycloak/model/base_representation.rb
112
+ - lib/keycloak/model/client_representation.rb
113
+ - lib/keycloak/model/credential_representation.rb
114
+ - lib/keycloak/model/role_representation.rb
115
+ - lib/keycloak/model/user_representation.rb
116
+ - lib/keycloak/realm.rb
117
+ - lib/keycloak/scalar.rb
118
+ - lib/keycloak/scalar/array_type.rb
119
+ - lib/keycloak/user_entity.rb
120
+ - lib/keycloak/version.rb
121
+ homepage: https://github.com/FX-HAO/keycloak-ruby-client
122
+ licenses:
123
+ - MIT
124
+ metadata:
125
+ allowed_push_host: https://rubygems.org/
126
+ homepage_uri: https://github.com/FX-HAO/keycloak-ruby-client
127
+ source_code_uri: https://github.com/FX-HAO/keycloak-ruby-client
128
+ changelog_uri: https://github.com/FX-HAO/keycloak-ruby-client/blob/master/CHANGELOG.md
129
+ post_install_message:
130
+ rdoc_options: []
131
+ require_paths:
132
+ - lib
133
+ required_ruby_version: !ruby/object:Gem::Requirement
134
+ requirements:
135
+ - - ">="
136
+ - !ruby/object:Gem::Version
137
+ version: '0'
138
+ required_rubygems_version: !ruby/object:Gem::Requirement
139
+ requirements:
140
+ - - ">="
141
+ - !ruby/object:Gem::Version
142
+ version: '0'
143
+ requirements: []
144
+ rubyforge_project:
145
+ rubygems_version: 2.6.11
146
+ signing_key:
147
+ specification_version: 4
148
+ summary: Keycloak ruby client
149
+ test_files: []