keycloak-ruby 1.0

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: ecddb21c9d2a4b4690a75eb710bd3814d2cfaed8
4
+ data.tar.gz: 373c4aea34bd49fb26cc51a483fef845d0eddc5c
5
+ SHA512:
6
+ metadata.gz: d05916a2ee4fabf132c58806206403503743dfa58c9b2058ff7d752ea1d214df76635288ca46cd4fd181f79749e1af80d256502541ee88240d66f85d4d1a6efd
7
+ data.tar.gz: d018ddb3994d661ccc36f65349502bc8448e390ddcf7fa7a5596d9ace3099cd888876a6a0f3115ad9828ea9b42e2d7c6f1904316ce564b8ea7c541821ea4aba4
data/.gitignore ADDED
@@ -0,0 +1,6 @@
1
+ keycloak-*.gem
2
+ .rspec_status
3
+ .DS_STORE
4
+ .idea/*
5
+ .idea
6
+ .vscode/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.0
5
+ before_install: gem install bundler -v 1.15.1
@@ -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 g_portugues@hotmail.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.gemspec
4
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,55 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ keycloak-ruby (1.0)
5
+ json
6
+ jwt
7
+ rest-client
8
+
9
+ GEM
10
+ remote: https://rubygems.org/
11
+ specs:
12
+ diff-lcs (1.3)
13
+ domain_name (0.5.20180417)
14
+ unf (>= 0.0.5, < 1.0.0)
15
+ http-cookie (1.0.3)
16
+ domain_name (~> 0.5)
17
+ json (2.1.0)
18
+ jwt (2.1.0)
19
+ mime-types (3.2.2)
20
+ mime-types-data (~> 3.2015)
21
+ mime-types-data (3.2018.0812)
22
+ netrc (0.11.0)
23
+ rake (10.5.0)
24
+ rest-client (2.0.2)
25
+ http-cookie (>= 1.0.2, < 2.0)
26
+ mime-types (>= 1.16, < 4.0)
27
+ netrc (~> 0.8)
28
+ rspec (3.7.0)
29
+ rspec-core (~> 3.7.0)
30
+ rspec-expectations (~> 3.7.0)
31
+ rspec-mocks (~> 3.7.0)
32
+ rspec-core (3.7.1)
33
+ rspec-support (~> 3.7.0)
34
+ rspec-expectations (3.7.0)
35
+ diff-lcs (>= 1.2.0, < 2.0)
36
+ rspec-support (~> 3.7.0)
37
+ rspec-mocks (3.7.0)
38
+ diff-lcs (>= 1.2.0, < 2.0)
39
+ rspec-support (~> 3.7.0)
40
+ rspec-support (3.7.1)
41
+ unf (0.1.4)
42
+ unf_ext
43
+ unf_ext (0.0.7.5)
44
+
45
+ PLATFORMS
46
+ ruby
47
+
48
+ DEPENDENCIES
49
+ bundler (~> 1.15)
50
+ keycloak-ruby!
51
+ rake (~> 10.0)
52
+ rspec (~> 3.0)
53
+
54
+ BUNDLED WITH
55
+ 1.16.5
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Guilherme Portugues
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,499 @@
1
+ # Keycloak
2
+
3
+ Keycloak gem was developed to integrate applications and services into [Red Hat](https://www.redhat.com)'s [Keycloak](http://www.keycloak.org/) system for user control, authentication, authorization, and session management.
4
+
5
+ Its development was based on version 3.2 of Keycloak, whose documentation can be found [here](http://www.keycloak.org/archive/documentation-3.2.html).
6
+
7
+ Publication of gem: https://rubygems.org/gems/keycloak
8
+
9
+ Exemple: https://github.com/imagov/example-gem-keycloak
10
+
11
+ ## Installation
12
+
13
+ Add this line in your application's <b>gemfile</b>:
14
+
15
+ ```ruby
16
+ gem 'keycloak'
17
+ ```
18
+
19
+ Install the gem by running:
20
+
21
+ $ bundle install
22
+
23
+ Or install it yourself:
24
+
25
+ $ gem install keycloak
26
+
27
+ To add the configuration file:
28
+
29
+ $ rails generate initializer
30
+
31
+
32
+ ## Use
33
+
34
+ Since you already have a Keycloak environment configured and the gem already installed, the next step is to define how the application will authenticate. Keycloak works with key authentication protocols, such as OpenID Connect, Oauth 2.0 and SAML 2.0, integrating system access through Single-Sign On, and can also provide access to <b>LDAP</b> or <b>Active Directory</b> users.
35
+
36
+ When you register a realm and also a Client in your Keycloak environment, you can download the Client installation file into the root folder of the application so that gem gets the information it needs to interact with Keycloak. To download this, simply access your Client's registry, click the <b>Installation</b> tab, select <b>Keycloak OIDC JSON</b> in the <b>Format option</b> field and click <b>Download</b>. If your application does not only work with a specific client (application server for APIs, for example), then you can tell what is the realm that gem will interact in the `keycloak.rb` configuration file.
37
+
38
+ Gem has a main module called <b>Keycloak</b>. Within this module there are three other modules: <b>Client</b>, <b>Admin</b> and <b>Internal</b>.
39
+
40
+ ### Module Keycloak
41
+
42
+ The Keycloak module has some attributes and its definitions are fundamental for the perfect functioning of the gem in the application.
43
+
44
+ ```ruby
45
+ Keycloak.installation_file = 'path/to/file.json'
46
+ ```
47
+
48
+ Allows you to set the location of installation file if you have one. If not set, it will default to `keycloak.json` in the root of your repository. In any case, it will use installation file only if it's present.
49
+
50
+ ```ruby
51
+ Keycloak.realm
52
+ ```
53
+
54
+ If your application does not only work with a specific client (application server for APIs, for example), then you can tell the realm name that gem will interact in that attribute. When installed, gem creates the `keycloak.rb` file in `config / initializers`. This attribute can be found and defined in this file.
55
+
56
+
57
+ ```ruby
58
+ Keycloak.auth_server_url
59
+ ```
60
+
61
+ For the same scenario as the above attribute, you can tell the url of the realm that the gem will interact in that attribute. When installed, gem creates the `keycloak.rb` file in `config / initializers`. This attribute can be found and defined in this file.
62
+
63
+
64
+ ```ruby
65
+ Keycloak.proxy
66
+ ```
67
+
68
+ If the environment where your application will be used requires the use of proxy for the consumption of the Keycloak APIs, then define it in this attribute. When it is installed, gem creates the `keycloak.rb` file in `config/initializers`. This attribute can be found and defined in this file.
69
+
70
+
71
+ ```ruby
72
+ Keycloak.generate_request_exception
73
+ ```
74
+
75
+ This attribute is to define whether the HTTP exceptions generated in the returns of the requests made to Keycloak will or will not burst in the application. If set to `false`, then the exception will not be blown and the HTTP response will be returned to the application to do its own processing. The default value of this attribute is `true`. When it is installed, gem creates the `keycloak.rb` file in `config/initializers`. This attribute can be found and defined in this file.
76
+
77
+
78
+ ```ruby
79
+ Keycloak.keycloak_controller
80
+ ```
81
+
82
+ It is recommended that your application has a controller that centralizes the session actions that Keycloak will manage, such as login action, logout, session update, password reset, among others. Define in this attribute what is the name of the controller that will play this role. If your controller name is `SessionController`, then the value of this attribute should be `session` only. When it is installed, gem creates the `keycloak.rb` file in `config/initializers`. This attribute can be found and defined in this file.
83
+
84
+
85
+ ```ruby
86
+ Keycloak.proc_cookie_token
87
+ ```
88
+
89
+ This attribute is an anonymous method (lambda). The same must be implemented in the application so that the gem has access to the authentication token which, in turn, must be stored in the cookie. When performing the keycloak authentication through gem, the system must store the token returned in the browser cookie, such as:
90
+ ```ruby
91
+ cookies.permanent[:keycloak_token] = Keycloak::Client.get_token(params[:user_login], params[:user_password])
92
+ ```
93
+
94
+ The application can retrieve the token in the cookie by implementing the `Keycloak.proc_cookie_token` method as follows:
95
+ ```ruby
96
+ Keycloak.proc_cookie_token = -> do
97
+ cookies.permanent[:keycloak_token]
98
+ end
99
+ ```
100
+ This way, every time gem needs to use the token information to consume a Keycloak service, it will invoke this lambda method.
101
+
102
+
103
+ ```ruby
104
+ Keycloak.proc_external_attributes
105
+ ```
106
+
107
+ Keycloak gives the possibility that new attributes are mapped to the user registry. However, when these attributes are application specific, it is recommended that you manage them yourself. To do this, the best solution is to create these attributes in the application - example: create a table in the database of the application itself containing the columns representing each of the attributes, also inserting in this table a unique key column, same as the User Id created in Keycloak, indicating that the one belonging to that Id has those attributes.
108
+ In order for gem to have access to these attributes, set the `Keycloak.proc_external_attributes` attribute to a lambda method by obtaining the attributes of the logged-in user. Example:
109
+ ```ruby
110
+ Keycloak.proc_external_attributes = -> do
111
+ attribute = UsuariosAtributo.find_or_create_by(user_keycloak_id: Keycloak::Client.get_attribute('sub'))
112
+ if attribute.status.nil?
113
+ attribute.status = false
114
+ attribute.save
115
+ end
116
+ attribute
117
+ end
118
+ ```
119
+
120
+
121
+ <b>Note:</b> The `Keycloak.proc_cookie_token` and `Keycloak.proc_external_attributes` attributes can be defined in the `initialize` of the controller `ApplicationController`.
122
+
123
+
124
+ ### Keycloak::Client
125
+
126
+ The `Keycloak::Client` module has the methods that represent the <b>endpoint</b> services. These services are fundamental for creating and updating tokens, logging in and logout, and also for obtaining the synthetic information of a logged in user. What enables gem to make use of all these services is the previously mentioned client installation file.
127
+
128
+ We will detail each of these methods:
129
+
130
+ ```ruby
131
+ Keycloak::Client.get_token(user, password)
132
+ ```
133
+
134
+ If you choose to authenticate users using the screen of your own application, then use this method. Simply invoke it in the method of login in the `controller` defined with the session controller of your application, passing as parameter the <b>user</b> and the <b>password</b> informed by the user. If the authentication is valid, then a JSON containing the `access_token` and the `refresh_token` is returned.
135
+
136
+
137
+ ```ruby
138
+ Keycloak::Client.url_login_redirect(redirect_uri, response_type = 'code')
139
+ ```
140
+
141
+ To authenticate the users of your application using a template configured in Keycloak, redirect the request to the url returned in this method. Pass as a parameter the url that the user will have access in case of successful authentication (`redirect_uri`) and also the type of response (`response_type`), which if not informed, gem will assume the `code` value. If the authentication is successful, then a `code` will be returned that will enable you to request a token from <b>Keycloak</b>.
142
+
143
+
144
+ ```ruby
145
+ Keycloak::Client.get_token_by_code(code, redirect_uri)
146
+ ```
147
+
148
+ When using the `Keycloak::Client.url_login_redirect` method to get a `code`, pass it as a parameter in this method so that Keycloak returns a token, thus logging the user in the application. The second parameter (`redirect_uri`) must be passed so that when a token is made available, Keycloak redirects to the url informed.
149
+
150
+
151
+ ```ruby
152
+ Keycloak::Client.get_token_by_refresh_token(refresh_token = '')
153
+ ```
154
+
155
+ When the user is already logged in and your application internally tracks the token expiration time provided by Keycloak, then this method can be used to renew that token if it is still valid. To do this, simply pass the `refresh_token` as a parameter. If you do not inform `refresh_token`, gem will use the `refresh_token` stored in the cookie.
156
+
157
+
158
+ ```ruby
159
+ Keycloak::Client.get_token_introspection(token = '')
160
+ ```
161
+
162
+ This method returns the information from the `token` session passed as parameter. Among the information returned, the most important is the `active` field, since it informs whether the token session passed in the parameter is active or not. This will help your application control whether the logged-in user session has expired or not. If no token is passed as a parameter, gem will use the last `access_token` stored in the application's cookie.
163
+
164
+
165
+ ```ruby
166
+ Keycloak::Client.get_token_by_client_credentials(client_id = '', secret = '')
167
+ ```
168
+
169
+ There are some Keycloak services like <b>password reset</b>, <b>user registration</b> in the initial screen of the application or even authentication following the standard <b>OAuth 2.0</b>, that the authentication of a user becomes unnecessary. Therefore, we can obtain a token using the credentials of its own application (Client) registered in Keycloak. To obtain this token, pass the `client_id` - informed by the person who registered your application in Keycloak - and the `secret` of your application generated by Keycloak - to generate a `secret`, the Access Type of your Client must be configured as `confidential`. If you do not pass any of these parameters, gem will use the credentials contained in the installation file mentioned above.
170
+
171
+
172
+ ```ruby
173
+ Keycloak::Client.logout(redirect_uri = '', refresh_token = '')
174
+ ```
175
+
176
+ When used before the expiration of the logged on user's session, this method terminates the session. If the `redirect_uri` parameter is fed, then Keycloak will redirect your application to the url informed after logout. The second parameter is `refresh_token`, obtained at the time of authentication or session update. If the latter is not informed, then the gem will use the `refresh_token` of the cookie
177
+
178
+
179
+ ```ruby
180
+ Keycloak::Client.get_userinfo(access_token = '')
181
+ ```
182
+
183
+ This method returns synthetic information from the user represented by the `access_token` passed as a parameter, such as `sub` - which is the authenticated user id -, `preferred_username` - which is the authenticated user name - and `email` - which is the user's email address. If the `access_token` parameter is not informed, then the gem will get this information in the cookie.
184
+
185
+
186
+ ```ruby
187
+ Keycloak::Client.url_user_account
188
+ ```
189
+
190
+ Returns the <b>url</b> for access to the realm user registry of the installation file (`keycloak.json`). To access the screen, Keycloak will require user authentication. After connected, and if has permission, the user will have access to his own personal information and could even change them.
191
+
192
+
193
+ ```ruby
194
+ Keycloak::Client.has_role?(user_role, access_token = '')
195
+ ```
196
+
197
+ The `has_role?` method decodes the JWT `access_token` and verifies that the user who owns the token has the <b>role</b> informed in the `user_role` parameter. If `access_token` is not informed then gem will use the `access_token` of the cookie.
198
+
199
+
200
+ ```ruby
201
+ Keycloak::Client.user_signed_in?(access_token = '')
202
+ ```
203
+
204
+ This method checks whether the `access_token` passed in the parameter is still active. To check whether the user is active or not, the gem invokes the `get_token_introspection` method internally. If `access_token` is not informed then gem will use the `access_token` of the cookie.
205
+
206
+
207
+ ```ruby
208
+ Keycloak::Client.get_attribute(attribute_name, access_token = '')
209
+ ```
210
+
211
+ This method decodes the JWT `access_token` and returns the value of the name attribute passed in the `attribute_name` parameter. This attribute can be a <b>mapper</b> - registered in the <b>Mappers</b> section of the Realm <b>Client</b> registry. If `access_token` is not informed then gem will use the `access_token` of the cookie.
212
+
213
+
214
+ ```ruby
215
+ Keycloak::Client.token
216
+ ```
217
+
218
+ Returns the last authenticated token stored in the cookie. When the `Keycloak.proc_cookie_token` method is implemented in the application and a user authenticates the application, this method returns the token of that user.
219
+
220
+
221
+ ```ruby
222
+ Keycloak::Client.external_attributes
223
+ ```
224
+
225
+ When the `Keycloak.proc_external_attributes` method is implemented, the `external_attributes` method returns it. The purpose of this method is to return the application-specific attributes not mapped in Keycloak.
226
+
227
+
228
+ ### Keycloak::Admin
229
+
230
+ The `Keycloak :: Admin` module provides methods that represent the [REST APIs do Keycloak](http://www.keycloak.org/docs-api/3.2/rest-api/index.html). In order to use these APIs, an active `access_token` is required, that is, authentication must occur before using the methods for a valid token to be used as a credential. If `access_token` is not informed then gem will use the `access_token` of the cookie. The authenticated user must have the `role` of the respective service invoked - roles of the `realm-management` client, which represents the management of the realm.
231
+
232
+ The list of methods is shown below. The `{realm}` route parameter of all APIs will be obtained from the `keycloak.json` installation file:
233
+
234
+ ```ruby
235
+ # GET /admin/realms/{realm}/users
236
+ Keycloak::Admin.get_users(query_parameters = nil, access_token = nil)
237
+ ```
238
+
239
+ `get_users` returns a list of users, filtered according to the parameters <b>hash</b> passed in` query_parameters`.
240
+
241
+
242
+ ```ruby
243
+ # POST /admin/realms/{realm}/users
244
+ Keycloak::Admin.create_user(user_representation, access_token = nil)
245
+ ```
246
+
247
+ `create_user` creates a new user in Keycloak. The `user_representation` parameter must be a hash according to Keycloak [UserRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_userrepresentation). The return of this method will be `true` for success.
248
+
249
+
250
+ ```ruby
251
+ # GET /admin/realms/{realm}/users/count
252
+ Keycloak::Admin.count_users(access_token = nil)
253
+ ```
254
+ `count_users` returns the number of users in the realm.
255
+
256
+
257
+ ```ruby
258
+ # GET /admin/realms/{realm}/users/{id}
259
+ Keycloak::Admin.get_user(id, access_token = nil)
260
+ ```
261
+
262
+ `get_user` returns the user representation identified by the `id` parameter - which is the <b>ID</b> created by Keycloak when creating a new user.
263
+
264
+
265
+ ```ruby
266
+ # PUT /admin/realms/{realm}/users/{id}
267
+ Keycloak::Admin.update_user(id, user_representation, access_token = nil)
268
+ ```
269
+
270
+ `update_user` updates the user registry identified by `id` - which is the <b>ID</b> created by Keycloak when creating a new user. In the `user_representation` parameter should be a hash with the fields that will be changed, respecting the [UserRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_userrepresentation) of Keycloak. The return of this method will be `true` for success.
271
+
272
+
273
+ ```ruby
274
+ # DELETE /admin/realms/{realm}/users/{id}
275
+ Keycloak::Admin.delete_user(id, access_token = nil)
276
+ ```
277
+
278
+ `delete_user` excludes the user ID identified by the `id` - which is the <b>ID</b> created by Keycloak when creating a new user. The return of this method will be `true` for success.
279
+
280
+
281
+ ```ruby
282
+ # DELETE /admin/realms/{realm}/users/{id}/consents/{client}
283
+ Keycloak::Admin.revoke_consent_user(id, client_id = nil, access_token = nil)
284
+ ```
285
+
286
+ `revoke_consent_user` revokes the tokens of a user identified by `id` - which is the <b>ID</b> created by Keycloak when creating a new user - on the client identified by the `client_id` parameter.
287
+
288
+
289
+ ```ruby
290
+ # PUT /admin/realms/{realm}/users/{id}/execute-actions-email
291
+ Keycloak::Admin.update_account_email(id, actions, redirect_uri = '', client_id = nil, access_token = nil)
292
+ ```
293
+
294
+ `update_account_email` sends an account update email to the user represented by the `id` parameter. The email contains a link that the user can click to execute a set of actions represented by the `actions` parameter - which awaits an `array` of [actions defined by Keycloak](http://www.keycloak.org/docs/3.2/server_admin/topics/users/required-actions.html). An example value that can be passed to the `actions` parameter is `['UPDATE_PASSWORD']`, which indicates that the action that the user must take when clicking the link in the email is to change their password. In the `redirect_uri` parameter, if necessary, a url must be passed so that, at the end of sending the e-mail, the application is redirected. The `client_id` parameter should be informed if the Client responsible for the actions to be performed is not the same as the `keycloak.json` installation file.
295
+
296
+
297
+ ```ruby
298
+ # GET /admin/realms/{realm}/users/{id}/role-mappings
299
+ Keycloak::Admin.get_role_mappings(id, access_token = nil)
300
+ ```
301
+
302
+ `get_role_mappings` returns all <b>Role Mappings</b> in the realm assigned to the user identified by the `id` parameter, regardless of the Client.
303
+
304
+
305
+ ```ruby
306
+ # GET /admin/realms/{realm}/clients
307
+ Keycloak::Admin.get_clients(query_parameters = nil, access_token = nil)
308
+ ```
309
+
310
+ `get_clients` returns a list of [ClientRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_clientrepresentation) pertaining to the realm. The `query_parameters` parameter expects a hash with `clientId` attributes - if you want the list to be filtered by `client_id` - and `viewableOnly` - to filter whether the Keycloak Administration Clients will be returned in the list.
311
+
312
+
313
+ ```ruby
314
+ # GET /admin/realms/{realm}/clients/{id}/roles
315
+ Keycloak::Admin.get_all_roles_client(id, access_token = nil)
316
+ ```
317
+
318
+ `get_all_roles_client` returns a [RoleRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_rolerepresentation) list with all client <b>roles</b> identified by the `id` parameter - this parameter must be passed in the ID of the Clint and not `client_id`.
319
+
320
+
321
+ ```ruby
322
+ # GET /admin/realms/{realm}/clients/{id}/roles/{role-name}
323
+ Keycloak::Admin.get_roles_client_by_name(id, role_name, access_token = nil)
324
+ ```
325
+
326
+ `get_roles_client_by_name` returns the [RoleRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_rolerepresentation) of the role identified by the parameter `role_name` - which is the name of the role.
327
+
328
+
329
+ ```ruby
330
+ # POST /admin/realms/{realm}/users/{id}/role-mappings/clients/{client}
331
+ Keycloak::Admin.add_client_level_roles_to_user(id, client, role_representation, access_token = nil)
332
+ ```
333
+
334
+ `add_client_level_roles_to_user` inserts a <b>role</b> from the Client (represented by the `client` parameter) to the user represented by the `id` parameter. The `role_representation` parameter should receive an `array` of [RoleRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_rolerepresentation) that will be entered into the user. On success, the return will be `true`.
335
+
336
+
337
+ ```ruby
338
+ # DELETE /admin/realms/{realm}/users/{id}/role-mappings/clients/{client}
339
+ Keycloak::Admin.delete_client_level_roles_from_user(id, client, role_representation, access_token = nil)
340
+ ```
341
+
342
+ `delete_client_level_roles_from_user` deletes a <b>Client-Role</b> (representado pelo parâmetro `client`) of the user represented by the `id` parameter. The `role_representation` parameter should receive an `array` of [RoleRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_rolerepresentation) that will be removed on the user. On success, the return will be `true`.
343
+
344
+
345
+ ```ruby
346
+ # GET /admin/realms/{realm}/users/{id}/role-mappings/clients/{client}
347
+ Keycloak::Admin.get_client_level_role_for_user_and_app(id, client, access_token = nil)
348
+ ```
349
+
350
+ `get_client_level_role_for_user_and_app` return a list of [RoleRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_rolerepresentation) of client <b>Client-Roles</b>, represented by `client` parameter linked to the user represented by the `id` parameter.
351
+
352
+
353
+ ```ruby
354
+ Keycloak::Admin.update_effective_user_roles(id, client_id, roles_names, access_token = nil)
355
+ ```
356
+
357
+ `update_effective_user_roles` is not on the Keycloak <b>Admin APIs</b> list. This method binds to the user represented by the `id` parameter all the roles passed in an` array` in the `roles_names` parameter. The roles passed in the `roles_names` parameter must belong to the Client represented by the` client_id` parameter. If the user has the link with a role that is not in the `roles_names` parameter, this link will be removed because the purpose of this method is for the user to effectively assume the roles passed in this parameter. On success, the return will be `true`.
358
+
359
+
360
+ ```ruby
361
+ PUT /admin/realms/{realm}/users/{id}/reset-password
362
+ Keycloak::Admin.reset_password(id, credential_representation, access_token = nil)
363
+ ```
364
+
365
+ `reset_password` change the user password represented by `id` parameter. The new password is represented by `credential_representation` parameter, which is a set of information formatted under the [CredentialRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_credentialrepresentation) section of the Keycloak API manual.
366
+
367
+
368
+ ```ruby
369
+ GET /admin/realms/{realm}/groups/{id}/role-mappings/clients/{client}/composite
370
+ Keycloak::Admin.get_effective_client_level_role_composite_user(id, client, access_token = nil)
371
+ ```
372
+
373
+ `get_effective_client_level_role_composite_user` return a list (array) of [RoleRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_rolerepresentation) of a <b>Group</b> represented by `id` parameter attached to a <b>Client</b> represented by `client` parameter.
374
+
375
+
376
+ If there is any service in the manual [Keycloak Admin REST API](http://www.keycloak.org/docs-api/3.2/rest-api/index.html) that has not been implemented in this gem, there is a possibility of being invoked using the <b>Generics Methods</b> of the `Keycloak::Admin` model. The <b>Generics Methods</b> allow you to request any of the APIs, either `GET`,` POST`, `PUT` or` DELETE`, passing the request parameters as `hashes` in the parameters` query_parameters` and `body_parameter` of the <b>Generics Methods</b>.
377
+ <br>
378
+ The following are the <b>Generics Methods</b>:
379
+ <br>
380
+
381
+ ```ruby
382
+ Keycloak::Admin.generic_get(service, query_parameters = nil, access_token = nil)
383
+ ```
384
+
385
+ `generic_get` permite que você faça requisições de serviços `GET` do <b>Keycloak</b>. A parte da URI que identifica o serviço deve ser passada no parâmetro `service`, já com os parâmetros de rota (como o `{client}`, por exemplo) devidamente substituídos. No parâmetro `query_parameters` você poderá passar um `hash` contendo os <b>Queries Parameters</b> da requisição.<br>
386
+ Exemplo:
387
+ ```ruby
388
+ Keycloak::Admin.generic_get("users/", {email: 'admin@test.com'}, "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldU...")
389
+ ```
390
+
391
+
392
+ ```ruby
393
+ Keycloak::Admin.generic_post(service, query_parameters, body_parameter, access_token = nil)
394
+ ```
395
+
396
+ `generic_post` permite que você faça requisições de serviços `POST` do <b>Keycloak</b>. A parte da URI que identifica o serviço deve ser passada no parâmetro `service`, já com os parâmetros de rota (como o `{client}`, por exemplo) devidamente substituídos. No parâmetro `query_parameters` você poderá passar um `hash` contendo os <b>Query Parameters</b> da requisição. No parâmetro `body_parameter` você poderá passar um `hash` contendo os <b>Body Parameters</b> da requisição.<br>
397
+ Exemplo:
398
+ ```ruby
399
+ Keycloak::Admin.generic_post("users/", nil, { username: "admin", email: "admin@test.com", enabled: true }, "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldU...")
400
+ ```
401
+
402
+
403
+ ```ruby
404
+ Keycloak::Admin.generic_put(service, query_parameters, body_parameter, access_token = nil)
405
+ ```
406
+
407
+ `generic_put` permite que você faça requisições de serviços `PUT` do <b>Keycloak</b>. A parte da URI que identifica o serviço deve ser passada no parâmetro `service`, já com os parâmetros de rota (como o `{client}`, por exemplo) devidamente substituídos. No parâmetro `query_parameters` você poderá passar um `hash` contendo os <b>Query Parameters</b> da requisição. No parâmetro `body_parameter` você poderá passar um `hash` contendo os <b>Body Parameters</b> da requisição.
408
+
409
+
410
+ ```ruby
411
+ Keycloak::Admin.generic_delete(service, query_parameters = nil, body_parameter = nil, access_token = nil)
412
+ ```
413
+
414
+ `generic_delete` permite que você faça requisições de serviços `DELETE` do <b>Keycloak</b>. A parte da URI que identifica o serviço deve ser passada no parâmetro `service`, já com os parâmetros de rota (como o `{client}`, por exemplo) devidamente substituídos. No parâmetro `query_parameters` você poderá passar um `hash` contendo os <b>Query Parameters</b> da requisição. No parâmetro `body_parameter` você poderá passar um `hash` contendo os <b>Body Parameters</b> da requisição.
415
+
416
+
417
+
418
+ ### Keycloak::Internal
419
+
420
+ O módulo `Keycloak::internal`disponibiliza métodos criados para facilitar a interação entre a aplicação e o <b>Keycloak</b>. Partindo das informações encontradas no arquivo de instalação `keycloak.json`, todos os métodos invocados serão autenticados automaticamente, utilizando as credências da aplicação (`grant_type = client_credentials`), dependendo assim dos <b>roles</b> atribuídos a mesma para que o retorno da requisição seja autorizado.
421
+
422
+
423
+ ```ruby
424
+ Keycloak::Internal.get_users(query_parameters = nil)
425
+ ```
426
+
427
+ `get_users` invoca o método `Keycloak::Admin.get_users` que, por sua vez, retorna uma lista de usuários, filtrada de acordo com o hash de parâmetros passado em `query_parameters`.
428
+
429
+
430
+ ```ruby
431
+ Keycloak::Internal.change_password(user_id, redirect_uri = '')
432
+ ```
433
+
434
+ `change_password` invocará a API `PUT /admin/realms/{realm}/users/{id}/execute-actions-email` do Keycloak requisitando a action `UPDATE_PASSWORD`. Isso fará com que o Keycloak dispare um e-mail para o usuário representado pelo parâmetro `user_id`. O parâmetro `redirect_uri` é opcional. Se não for preenchido, então não haverá nenhum link para clicar após a ação de reset de senha ter sido concluída.
435
+
436
+
437
+ ```ruby
438
+ Keycloak::Internal.get_user_info(user_login, whole_word = false)
439
+ ```
440
+
441
+ `get_user_info`, baseado no parâmetro `user_login`, que poderá recepcionar o `username` ou o `email` do usuário, retornará uma lista (array) de [UserRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_userrepresentation) no caso em que o parâmetro `whole_word` for `false`, ou retornará um [UserRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_userrepresentation) quando o parâmetro `whole_word` for `true`. O parâmetro `whole_word` indica se o método deverá considerar usuários que tenham no `username` ou `email` parte da expressão passada no parâmetro `user_login` - para os casos de `whole_word = false` -, ou que tenha exatamente a expressão passada nesse parâmetro - para os casos de `whole_word = true`.
442
+
443
+
444
+ ```ruby
445
+ Keycloak::Internal.forgot_password(user_login, redirect_uri = '')
446
+ ```
447
+
448
+ `forgot_password` invocará o método `Keycloak::Internal.change_password` após invocar o método `Keycloak::Internal.get_user_info` - passando no parâmetro `user_login` do método descrito o parâmetro `user_login`deste tópico e passando `true` no parâmetro `whole_word` -. A utilização deste método é indicado para os casos de aplicações permitam o reset da senha dos usuários sem que o mesmo esteja logado.
449
+
450
+
451
+ ```ruby
452
+ Keycloak::Internal.exists_name_or_email(value, user_id = '')
453
+ ```
454
+
455
+ `exists_name_or_email` verifica se no reino já existe algum usuário com `username` ou o `email` passado no parâmetro `value`. O parâmetro `user_id` serve para passar o `ID` de um usuário nos casos em que deseja-se alterar o `username` ou o `email` do mesmo, para que assim sejam considerados na verificação do `username` e do `email` usuários diferentes do usuário com o `ID` informado em `user_id`.
456
+
457
+
458
+ ```ruby
459
+ Keycloak::Internal.get_logged_user_info
460
+ ```
461
+
462
+ `get_logged_user_info` retorna o [UserRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_userrepresentation) do usuário logado na aplicação.
463
+
464
+
465
+ ```ruby
466
+ # GET /admin/realms/{realm}/users
467
+ Keycloak::Internal.logged_federation_user?
468
+ ```
469
+
470
+ `logged_federation_user?` incova o método `Keycloak::Internal.get_logged_user_info` e verifica se o mesmo é um <b>Federation User</b> (um usuário do AD por exemplo).
471
+
472
+
473
+ ```ruby
474
+ # GET /admin/realms/{realm}/users
475
+ Keycloak::Internal.create_starter_user(username, password, email, client_roles_names, proc = nil)
476
+ ```
477
+
478
+ `create_starter_user` é indicado para aplicações que permitam a criação de novos usuários sem que um usuário esteja logado ou até mesmo para criar novos usuários a partir do `rake db:seed`. Nos parâmetros `username`, `password` e `email` devem ser passados o nome do usuário, a senha do usuário, e o e-mail do usuário, respectivamente. No parâmetro `client_roles_names`deve ser passado uma lista (array) com o nome dos `roles` do Client que serão atribuídos ao usuário. O parâmetro `proc` trata-se de um método <b>lambda</b> que disponibilizará como parâmetro a [UserRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_userrepresentation) do usuário criado para que sejam definidas ações por parte da aplicação. Este método terá como retorno o mesmo retorno do método do parâmetro `proc` se o mesmo for definido, caso contrário retornará a [UserRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_userrepresentation) do usuário criado.
479
+
480
+
481
+ ```ruby
482
+ Keycloak::Internal.get_client_roles
483
+ ```
484
+
485
+ `get_client_roles` retornará uma lista (array) de [RoleRepresentation](http://www.keycloak.org/docs-api/3.2/rest-api/index.html#_rolerepresentation) do Client indicado pelo arquivo de instalação `keycloak.json`.
486
+
487
+
488
+ ```ruby
489
+ Keycloak::Internal.get_client_user_roles(user_id)
490
+ ```
491
+
492
+ `get_client_user_roles` invocará o método `Keycloak::Admin.get_effective_client_level_role_composite_user` considerando o Client indicado pelo arquivo de instalação `keycloak.json` e o usuário representado pelo parâmetro `user_id`.
493
+
494
+
495
+ ```ruby
496
+ Keycloak::Internal.has_role?(user_id, user_role)
497
+ ```
498
+
499
+ `has_role?` informará se o usuário representado pelo parâmetro `user_id` possui o <b>role</b> com o nome representado pelo parâmetro `user_role`.