使用Spring Boot + Spring Security + Keycloak验证每个请求的步骤如下:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Keycloak Adapter -->
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>
</dependencies>
# Keycloak Configuration
keycloak.realm=your-realm
keycloak.auth-server-url=http://localhost:8080/auth
keycloak.ssl-required=external
keycloak.resource=your-client-id
keycloak.credentials.secret=your-client-secret
keycloak.use-resource-role-mappings=true
keycloak.bearer-only=true
@Configuration
@EnableWebSecurity
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.antMatchers("/api/public").permitAll()
.antMatchers("/api/private").authenticated();
}
}
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/public")
public String publicEndpoint() {
return "This is a public endpoint.";
}
@GetMapping("/private")
public String privateEndpoint() {
return "This is a private endpoint.";
}
}
这样,你就成功地使用Spring Boot + Spring Security + Keycloak验证每个请求了。
关于Spring Boot、Spring Security和Keycloak的更多详细信息和用法,请参考以下链接:
请注意,以上答案仅供参考,具体实现可能因环境和需求而异。
领取专属 10元无门槛券
手把手带您无忧上云