我正在设置一个Spring Boot + Keycloak项目。我可以通过调用keycloak端点来生成令牌。当我从应用程序调用api时,出现错误401 Unauthorized Error。但是,我正在传递“承载者生成的令牌”。
控制器:
@PostMapping(path = "/products") public List<String> getProducts(){
return productService.getProducts(); }
KeycloakConfiguration:
@KeycloakConfiguration
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = 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("/products*").hasRole("user")
.anyRequest().permitAll()
.and().csrf().disable();
}
}
属性:
server.port=8090
keycloak.enabled=true
keycloak.auth-server-url=http://localhost:8080/auth
keycloak.realm=chamae-api
keycloak.resource=login-app
keycloak.bearer-only=true
我只想通过传递生成的Bearer令牌来访问api“产品”