baboon-project.org
  • Home
  • Privacy Policy
  • Contact Us
  • Guest Post – Write For Us
  • Sitemap
baboon-project.org

Role-Based Access Control to REST API with Keycloak

  • James Gussie
  • October 31, 2021
Total
0
Shares
0
0
0

Keycloak is the powerful open source Java-based authentication platform that simplifies secure access management with role-based access control. Keycloak provides a REST API to enable applications, such as gaming services, to securely interact with each other without requiring users to store passwords or credentials on their devices.js

Keycloak is a Java-based open source authorization service that simplifies the integration of access control into RESTful APIs. The key point in choosing Keycloak for your project is its role-based access control, which allows you to assign users their own roles so they can only access what’s allowed.

“Keycloak REST API” is a RESTful web service that allows you to create and manage access control policies for your application. It can be used with “Keycloak”, “Apache Tomcat”, “Jetty” and other Java EE servers. The role-based access control feature of Keycloak allows you to assign users to roles, which then determine the permissions they have on your application.

We discussed the fundamentals of using Keycloak with Spring Boot in a recent blog article. We’ll look at Role-based Access Control to Rest API using Keycloak in this blog article. So let’s get this party started!

Assume we have a Research Journal Management System microservice that can serve users with two sorts of responsibilities.

Certain APIs, such as adding or removing a Research paper, approving member requests, and so on, are only accessible by Admin. Similarly, members who have subscribed to the journal have access to particular APIs, such as perusing Research articles and so on. Role-based access to our microservice may be implemented in the above case.

We’ll start with the Keycloak setup steps, which are shown below.

Make a Realm

After login into the Keycloak panel, there is an option to create a new Realm in the upper left corner.

Make a client

There is a Clients option on the left pane. This will display all of the new realm’s customers. To begin, we’ll establish a new client with the following settings.

  • springboot-rolebased-microservice is the client ID.
  • openid-connect is the client protocol.
  • Type of access: private
  • ON (Authorization Enabled)
  • http://localhost:8080/* http://localhost:8080/* http://localhost:8080/* http://localhost:80

Add client

Add client

Add valid redirect URI

Now go to the Client Roles page and create two roles for a research journal: Admin and Member. To begin, choose Add a Role and fill in the relevant information.

Client Roles Tab

Admin should be included as a position.

Add Admin Role

Member is an additional position that may be added.

Add Member Role

Create roles for the Realm.

By assigning appropriate springboot-rolebased-microservice roles to Realm roles called app-member and app-admin, we can now construct Realm roles named app-member and app-admin (Member, Admin). The steps to perform what is described above are listed below.

  • In the left-hand window, choose Roles. Here you’ll find a list of all the realm roles. Then choose Add Role from the drop-down menu.

Add Realm Roles

  • Both positions should have a name and a description.

Add App-Member Role

Add App-Admin Role

  • For both jobs, enable Composite Roles. Then, under the Client Roles drop-down, choose springboot-rolebased-microservice. Then, for realm role app-member, pick Member role and click Add Selected, and for realm role app-admin, select Admin position and click Add Selected.

Composite Roles

Composite Roles

 

Users should be created.

We’ll now create two users, one with admin permissions and the other with member permissions. Go to the Users tab in the left pane and then click Add User to create a user.

User tab

Provide the user’s information. For the time being, we’ll only input the username. Then, on the SAVE button, turn on Email Verified.

Add User 1

Add User 2

To configure passwords for both users, go to the Credentials page now. After that, for both User 1 and User 2, turn off the Temporary Password option.

User 1 Creds

Now, go to the Role Mappings tab and assign Realm roles to both users. The following is the mapping of Realm roles for User1 and User2.

  • app-admin -> User1
  • app-member -> User2

User 1 Roles

User 2 Roles

It’s worth noting that Available Roles refers to all of the roles that may be allocated to a user, while Given Roles refers to the roles that have already been assigned to the user.

Access Tokens may be generated in a variety of ways.

We’re going to produce access tokens for our users right now. Go to Realm Settings first. Click OpenID Endpoint configuration in the Endpoints area. A URL for token endpoint may be found here.

Access Token

Access Token

Now launch Postman Client and pick OAuth2.0 from the Auth Tab. You’ll see the option to Configure New Token here. Then, under the Configuration Options, do the following steps:

  • Give your token a name.
  • Select Password Credentials in the Grant Type column.
  • Set the Access Token URL to the token endpoint value we examined before.
  • Our Client ID will be springboot-rolebased-microservice.
  • Set the Client Secret to the value found in the client’s Credentials tab.
  • Set the Username and Password to the username and password of the users for whom the token is being generated.
  • Remove the Scope from the equation.
  • Client Authentication is set to Send client credentials in the body by default.

Now choose Get New Access Token followed by Use Token.

Get Access Token

Get Access Token

These tokens may now be used to access our REST APIs. We’ve completed all of the Keycloak-related setups, and we’ll now go on to our Spring Boot application.

Configuring a Spring Boot Application

We will continue working on our Maven, Spring Boot Project for a basic Research Journal Management System use case.

pom.xml

This is how our Spring boot application’s pom.xml file looks:

org.springframework.boot 4.0.0 2.5.5 com.example demo spring-boot-starter-parent Demo 0.0.1-SNAPSHOT org.springframework.boot org.springframework.boot org.springframework.boot org.springframework.boot org.springframework. org.springframework.boot org.springframework.boot org.springframework.boot org.springframework.boot org.springframework. org.keycloak.spring-boot-starter-web org.springframework.boot spring-boot-devtools keycloak-spring-boot-starter $keycloak.version org.springframework.boot org.springframework.boot org.springframework.boot org.springframe org.springframework.security spring-boot-starter-test org.keycloak.bom org.keycloak.bom org.keycloak.bom org.keycloak.bo keycloak-adapter-bom pom import org.springframework.boot spring-boot-maven-plugin $keycloak.version

application.properties

The application.properties file looks like this.

  • Provide the value you specified while configuring Keycloak in keycloak-realm.
  • In keycloak-resource, enter your Client ID.
  • Provide the value found in the client’s Credentials tab in keycloak-credentials-secret.

8000 is the server’s port number. keycloak.realm = SpringBootKeycloakRoleBasedAccess keycloak.auth-server-url = http://localhost:8180/auth keycloak.ssl-required = external keycloak.resource = springboot-rolebased-microservice keycloak.ssl-required = external keycloak.ssl-required = external 48a0ae3a-be8b-447a-91ae-3b17286bf030 keycloak.credentials.secret keycloak.role-mappings-from-resources = true keycloak.bearer-only = true

KeyCloakSecurityConfiguration.java

The /member API can only be used by users who have the Member role assigned to them, according to the KeyCloakSecurityConfiguration class. Similarly, the /admin API can only be used by users that have the Admin role assigned to them.

The following code snippet does what was previously said.

.antMatchers(“/member”). hasAnyRole(“Member”) .antMatchers(“/admin”). hasAnyRole(“Admin”)

The following is an example of the KeyCloakSecurityConfiguration file:

import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver; import org.keycloak.adapters.springsecurity.authentication; import org.keycloak.adapters.springsecurity.authentication; import org.keycloak.adapters.springsecurity.authentication; import org.keycloak.adapters.springsecurity.authentication; import org.keycloak.adapters.springsecurity.authentication org.keycloak.adapters.springsecurity.config.KeycloakAuthenticationProvider; import org.keycloak.adapters.springsecurity.config.KeycloakAuthenticationProvider Import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation; import WebSecurityConfigurerAdapter. Import org.springframework.security.config.annotation.authentication.builders; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation. Import org.springframework.security.config.annotation.method.configuration into AuthenticationManagerBuilder. Enable Import org.springframework.security.config.annotation.web.builders from GlobalMethodSecurity. Import org.springframework.security.config.annotation.web.configuration.Enable from HttpSecurity. @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(jsr250Enabled = true); import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper; import org.springframework.security.core.session.SessionRegistryImpl; import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrate class in the open @Override protected void KeycloakSecurityConfig implements KeycloakWebSecurityConfigurerAdapter super.configure(http); http.authorizeRequests() returns an exception when configure(HttpSecurity http) is used. antMatchers(“/member”). hasAnyRole(“Member”).antMatchers(“/admin”). hasAnyRole(“Admin”). anyRequest() is a function that may be used to make every request. http.csrf; permitAll() (). disabling(); public void @Autowired configure world-wide (AuthenticationManagerBuilder auth) Exception is thrown AuthenticationProviderKeycloak keycloakAuthenticationProvider = keycloakAuthenticationProvider(); keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper()); auth.authenticationProvider(keycloakAuthenticationProvider); auth.authenticationProvider(keycloakAuthenticationProvider); auth.authenticationProvider(keycloakAuthenticationProvider); auth.authenticationProvider(keycloak @Bean @Override protected @Bean @Override protected @Bean @Bean @ return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()); SessionAuthenticationStrategy sessionAuthenticationStrategy(); public @Bean KeycloakConfigResolver return new KeycloakSpringBootConfigResolver() from KeycloakConfigResolver();

Controller

Our role-based access controller looks like this. We’ve merely created two basic GET APIs here, one for members who have subscribed to the journal and the other for the Research Journal Management System’s administrator.

import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation; package com.example.demo; import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity; import org.springframework.http.Response Import org.springframework.web.bind.annotation for RequestMapping. Import org.springframework.web.bind.annotation into RequestMethod. @RestController public class; RestController; RestController; RestController; RestController; RestController; Rest RoleBasedAccessController @RequestMapping(value = “/member”, method = RequestMethod.GET) @RequestMapping(value = “/member”, method = RequestMethod.GET) @RequestMapping(value = “/member return ResponseEntity.ok(“Hello Member”); public ResponseEntity getMember(); @RequestMapping(value = “/admin”, method = RequestMethod.GET) @RequestMapping(value = “/admin”, method = RequestMethod.GET) @RequestMapping(value return ResponseEntity.ok(“Hello Admin”); public ResponseEntity getAdmin();

Testing

The user with the role Member has access to the /member API, whereas the user with the role Admin has access to the /admin API, according to our KeyCloak Security Configuration class. Let’s put our app to the test using Postman.

We’re using the /member API and the Available Token value is set to the token value of a user with the Member role.

Get Member API

The end outcome is exactly what you’d anticipate. We’ll now attempt to utilize the same API with the Available Token value set to the token value of a user with the Admin role. Let’s have a look at the results.

Get Member API

The end outcome is exactly what you’d anticipate. The user is FORBIDDEN from using this API, according to the error notice.

Conclusion

With that, we’ve come to the conclusion of our blog post on Role-based Access Control to the Spring Boot Rest API with Keycloak. We covered how to configure Keycloak step by step in this post, and then we explored how to link our Spring Boot application to Keycloak. We also used Postman to test our application for role-based access restriction. We’ll cover more fascinating topics connected to Keycloak Authorization Services and Spring Boot in upcoming articles.

We hope you found the content interesting. Please utilize the comment area if you have any questions or feedback. If you’re interested in learning more about Keycloak, visit this site’s Keycloak tutorials page.

Good luck with your coding!

The “keycloak authorization example” is a role-based access control to REST API with Keycloak. It provides an easy way to allow users to create and manage their own API keys.

Related Tags

  • keycloak roles and permissions
  • keycloak authorization rest api
  • keycloak rest api example
  • keycloak api
  • keycloak rest api documentation
Total
0
Shares
Share 0
Tweet 0
Pin it 0
James Gussie

Previous Article

Download Galinha Pintadinha 1234 songs kids for PC Windows 10,8,7

  • James Gussie
  • October 31, 2021
View Post
Next Article

Game Pigeon not working: 7 Fixes

  • James Gussie
  • November 1, 2021
View Post
Table of Contents
  1. Make a Realm
  2. Make a client
  3. Create roles for the Realm.
  4. Users should be created.
  5. Access Tokens may be generated in a variety of ways.
  6. Configuring a Spring Boot Application
    1. pom.xml
    2. application.properties
    3. KeyCloakSecurityConfiguration.java
    4. Controller
  7. Testing
  8. Conclusion
Featured
  • 1
    Download Twitter videos in HD quality
    • June 4, 2022
  • 2
    What Is The Story Of Planet Earth 2 All About
    • April 14, 2022
  • 3
    How to Clear Cookies in Windows 11
    • December 24, 2021
  • 4
    7 of the most iconic black characters in manga history – Geekymint
    • December 23, 2021
  • 5
    Samsung Galaxy A52s 5G Review: New at Heart
    • December 22, 2021
Must Read
  • 1
    8+ Best Apps to Download YouTube Videos Offline
  • 2
    What Are The Benefits of CBD Products Near Me?
  • 3
    Game Pigeon not working: 7 Fixes
baboon-project.org
  • Home
  • Privacy Policy
  • Contact Us
  • Guest Post – Write For Us
  • Sitemap
Stay Updated Always.

Input your search keywords and press Enter.