使用Keycloak调用API安全端点时出现未经授权的错误401

时间:2019-07-19 23:18:44

标签: java spring-boot keycloak

我正在设置一个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“产品”

0 个答案:

没有答案