简体   繁体   中英

Spring boot with Keycloak to secure rest services

I have created two Roles in keycloak, FARMER and FIELD_STAFF

And Created a User Rahul and mapped it with FARMER role.

I have created below client in keycloak. 在此处输入图片说明

I have a web service where I only want to access it by FARMER Role. I have created a token and passing it while calling the rest services.But I am getting unauthorized access error in response.

Below I am adding Token generation screen and Keycloak configuration.

在此处输入图片说明

SecurityConfig.java

    package com.cropin.farmerservice.config;

import com.cropin.farmerservice.controller.FarmerController;
import org.keycloak.adapters.KeycloakConfigResolver;
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.keycloak.adapters.springsecurity.KeycloakSecurityComponents;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.keycloak.adapters.springsecurity.client.KeycloakClientRequestFactory;
import org.keycloak.adapters.springsecurity.client.KeycloakRestTemplate;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;

@Configuration
@ComponentScan(
        basePackageClasses = KeycloakSecurityComponents.class,
        excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.keycloak.adapters.springsecurity.management.HttpSessionManager"))
@EnableWebSecurity
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws  Exception {
        KeycloakAuthenticationProvider keycloakAuthenticationProvider = new KeycloakAuthenticationProvider();
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }

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

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

    @Autowired
    public KeycloakClientRequestFactory keycloakClientRequestFactory;

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public KeycloakRestTemplate keycloakRestTemplate(){
        return new KeycloakRestTemplate(keycloakClientRequestFactory);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        super.configure(http);
        http.authorizeRequests()
                .antMatchers("/farmer/*").hasRole("FARMER")
                .anyRequest().permitAll();
    }
}

application.properties

server.port = 8085


keycloak.enabled=true
keycloak.auth-server-url=http://localhost:8080/auth
keycloak.realm=farmer_demo
keycloak.resource=farmer-service
keycloak.bearer-only=true
keycloak.use-resource-role-mappings = true

Below is the response I am getting.

在此处输入图片说明

You will need RPT token in order to get access to you APIs not just access token, use the generated access_token to generate rpt one, PRT token is the one that actually holds the permissions.

keycloak authorization services

This is how i generate RPT tokens when i work on backend development:

  • From terminal, you can get tokens from keycloak (to use with postman or other rest test tools):

    1. Get access token:

        curl -v -d 'client_secret={keycloak client secret}' -d 'username={user name}' -d 'password={password}' -d 'client_id={keycloak client id}' -d 'grant_type=password' 'http://{keycloak url or host:port}/auth/realms/development/protocol/openid-connect/token' 
    2. Get rpt token which will be used during test

        curl -v -X POST \\ http://{keycloak url or host:port}/auth/realms/development/protocol/openid- connect/token \\ -H "Authorization: Bearer { token string from previous command result }" \\ --data "grant_type=urn:ietf:params:oauth:grant-type:uma-ticket" \\ --data "audience={keycloak client id}" 

Please see this section for more details...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM