Home > database >  What is the way to set up an authentication mechanism using keycloak initial access token?
What is the way to set up an authentication mechanism using keycloak initial access token?

Time:10-26

I want to develop an authentication mechanism for 3rd party applications using keycloak initial access tokens. But I want to do this only by using the access tokens that I have generated in the keycloak. For example, I will give a generated token to the user and allow him to log into the application. Is this possible? How can i do that? Initial Access Token

CodePudding user response:

First, I'm not sure it is a good idea to use "initial access token" for authorizing requests to your own resources. It might even not be allowed. As per the doc:

An initial access token can only be used to create clients

Second, don't use keycloak libs for Spring as suggested in other answer. It is very deprecated.

Last, a REST API secured with Oauth2 is a resource-server (and not a client). As so, the dependency should be spring-boot-starter-oauth2-resource-server. Spring doc is pretty extensive on the subject. You can also have a look at those tutorials for resource-server configuration (and OAuth2 definitions).

Once the resource-server (Spring REST API) is configured, clients will have to authorize their requests as normal for OAuth2: provide with an Authorization header containing a Bearer access-token (a JWT issued by Keycloak to the client with one of standard flows: client-credentials or authorization-code depending you need to authorize the client itself or a user behind it).

Edit

I might have misunderstood your need. If what you want is having new clients register themself programmatically on your Keycloak instance, then those clients will just issue a REST request to Keycloak server API with the "initial access token" in Authorization header as normal.

Once registered, those clients will be able to call you resource-servers as described in my initial answer.

CodePudding user response:

It is possible configure User and Roles to Keycloak admin UI. and follow below in java application:

Dependencies in Pom.xml.

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-spring-boot-starter</artifactId>
            <version>15.0.2</version>
        </dependency>

Add KeycloakConfig.java and SecurityConfig.java class in your project:

import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class KeycloakConfig {

    @Bean
    public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }
}

import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.keycloak.adapters.springsecurity.management.HttpSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;

@KeycloakConfiguration
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

     @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) {
            SimpleAuthorityMapper grantedAuthorityMapper = new SimpleAuthorityMapper();
            grantedAuthorityMapper.setPrefix("ROLE_");

            KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
            keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(grantedAuthorityMapper);
            auth.authenticationProvider(keycloakAuthenticationProvider);
        }

        @Bean
        @Override
        protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
            return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
        }

        @Bean
        @Override
        @ConditionalOnMissingBean(HttpSessionManager.class)
        protected HttpSessionManager httpSessionManager() {
            return new HttpSessionManager();
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            super.configure(http);
            http
                .authorizeRequests()
                .antMatchers("/file/upload").hasAnyRole("user", "admin")
                .antMatchers("/file/edit").hasAnyRole("admin")
                .anyRequest().permitAll();
        }
}

After this configuration from springboot application when I used above URLS this can be access only after Bearer token present with the request. Also It allows role base authentication.

Let me know if this answer is still not helpfull.

  • Related