1.1.55.2. fejezet, SpringBoot3 OpaqueToken integráció

OpaqueToken konfiguráció

SecurityConfig

package hu.infokristaly.keycloakauthenticatoin.security;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
 
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf(t->t.disable());
        http.authorizeRequests(authorize->{
            authorize.anyRequest().authenticated();
        });
        http.oauth2ResourceServer(t->{
            t.opaqueToken(Customizer.withDefaults());
        });
        http.sessionManagement(t->{
            t.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        });
        return http.build();
    }
}

UserController

package hu.infokristaly.keycloakauthenticatoin.controller;
 
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.util.HashMap;
 
@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping(path = "/info")
    public HashMap index() {
 
        OAuth2IntrospectionAuthenticatedPrincipal user = (OAuth2IntrospectionAuthenticatedPrincipal)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
 
        return new HashMap(){{
            put("hello", user.getClaimAsStringList("name"));
            put("your email is", user.getClaimAsStringList("email"));
        }};
    }
}

application.properties beállítások

spring.security.oauth2.resourceserver.opaquetoken.client-id=forras-admin
spring.security.oauth2.resourceserver.opaquetoken.client-secret=[client-secret]
spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=http://server.me.local:8080/realms/infokristaly/protocol/openid-connect/token/introspect