boycod3
boycod3

Reputation: 5317

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.

Upvotes: 6

Views: 3517

Answers (1)

hecko84
hecko84

Reputation: 1324

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.

Upvotes: 2

Related Questions