Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

migrate to keycloak from spring boot security

i want to migrate to keycloak from my old spring boot security app.Below is my security config.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
    @Autowired
    private CustomUserDetailsService customUserDetailsService;
     @Override
        protected void configure(HttpSecurity http) throws Exception {
         http.csrf().disable();

         http
         .authorizeRequests()
             .antMatchers("/*", "/static/**", "/css/**", "/js/**", "/images/**").permitAll()
             .antMatchers("/school-admin/*").hasAuthority("SCHOOL_ADMIN").anyRequest().fullyAuthenticated()
             .antMatchers("/teacher/*").hasAuthority("TEACHER").anyRequest().fullyAuthenticated()
             .anyRequest().authenticated().and()

         .formLogin()
             .loginPage("/login.html").defaultSuccessUrl("/loginSuccess.html")
            .failureUrl("/login.html?error").permitAll().and()

         .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout.html")).logoutSuccessUrl("/login.html?logout");

     }

     @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
         auth.userDetailsService(customUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
        }
}

I have already installed the keycloak and it is running on port 8080.The problem I found out that, we should create role and user on keycloak admin page, But what my current system is, users and roles are on my MySQL DB. I don't want to insert the users and roles on keycloak for authentication and authorization.

like image 787
boycod3 Avatar asked Mar 16 '17 08:03

boycod3


People also ask

How do I integrate Keycloak with Spring Security?

Spring Security There is a Keycloak Spring Security Adapter, and it’s already included in our Spring Boot Keycloak Starter dependency. We'll now see how to integrate Spring Security with Keycloak. 6.1. Dependency To use Spring Security with Spring Boot, we must add this dependency:

Where can I find the Keycloak Spring Boot starter?

The latest Spring Boot Keycloak Starter dependencies can be found on Maven Central. The Keycloak Spring Boot adapter capitalizes on Spring Boot’s auto-configuration, so all we need to do is add the Keycloak Spring Boot starter to our project.

How does spring boot handle Keycloak authorization server?

As we can see, Spring Boot seamlessly handled the entire process of calling the Keycloak Authorization Server. We did not have to call the Keycloak API to generate the Access Token ourselves, or even send the Authorization header explicitly in our request for protected resources.

How to create a new realm in Spring Boot Keycloak?

Let's navigate to the upper left corner to discover the Add realm button: After clicking the Create button, a new realm will be created and we'll be redirected to it. All the operations in the next sections will be performed in this new SpringBootKeycloak realm. 3.3.


1 Answers

Ok, obviously the first thing is a running keycloak instance, I assume this should be doable with the online documentation. We use i.e. Keycloak on a Wildfly instance. Next step is to define a realm and at least one client in keycloak that you will use to connect to with your spring-boot application. In you application's POM you will need to add dependencies for a keylcoak adapter like i.e.

<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-tomcat8-adapter</artifactId>
</dependency>
<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-spring-boot-adapter</artifactId>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
</dependency>

The rest can be done in your application.properties, that's the place where you configure how the adapter connects to keycloak and which parts of your application should be secured. This can look like

keycloak.realm=myrealm #realm that you have created in keycloak, contains your client
keycloak.auth-server-url=KeycloakHOST:KeycloakPort/auth # Substitute with your settings
keycloak.ssl-required=none
keycloak.resource=myclient
#keycloak.use-resource-role-mappings=true
keycloak.enable-basic-auth=true # we use basic authentication in this example
keycloak.credentials.secret=2dcf74ca-4e4f-44bf-9774-6c32c12783d3 # Secret generated for you client in keycloak
keycloak.cors=true
keycloak.cors-allowed-headers=x-requested-with,origin,content-type,accept,authorization
keycloak.cors-allowed-methods=GET,POST,DELETE,PUT,OPTIONS
keycloak.cors-max-age=3600
keycloak.expose-token=true
keycloak.bearer-only=true
keycloak.securityConstraints[0].securityCollections[0].name=adminRule
keycloak.securityConstraints[0].securityCollections[0].authRoles[0]=SCHOOL_ADMIN
keycloak.securityConstraints[0].securityCollections[0].patterns[0]=/school-admin/*
keycloak.securityConstraints[1].securityCollections[0].name=teacherRule
keycloak.securityConstraints[1].securityCollections[0].authRoles[0]=TEACHER
keycloak.securityConstraints[1].securityCollections[0].patterns[0]=/teacher/*

That's basically all you need to do in your spring-boot application. All other endpoints not covered by the rules above remain available to all. You can find a pretty good tutorial on that here that is the longer version what I have described.

like image 95
hecko84 Avatar answered Nov 01 '22 06:11

hecko84