5

我正在尝试使用 Keycloak 保护我的 rest api 和前端。

前端基于 Angular 4。

后端是使用 Spring boot 构建的 rest api。

我在同一领域(testRealm)中的 keycloak 管理控制台中创建了两个客户端。

前端客户端的 ACCESS-TYPE 是“Public”。

后端客户端(backendService) ACCESS-TYPE 是“仅承载”。

前端工作正常并根据角色显示选项卡。

当我尝试点击/访问后端服务调用时,它在浏览器控制台中出现以下错误-

无法加载http://localhost:9099/api/transaction

预检响应具有无效的 HTTP 状态代码 401。

下面是我用来保护 rest api 的配置。

应用程序属性

server.contextPath=/test
server.port=9090

keycloak.realm: testRealm
keycloak.bearer-only: true
keycloak.auth-server-url: http://localhost:8080/auth
keycloak.ssl-required: external
keycloak.resource: backendService
keycloak.use-resource-role-mappings: true
keycloak.confidential-port: 0
keycloak.credentials.secret=dc04c236-d2b9-560e-b6b2-efa2064b2386

ApiSecurityConfig.java(用于 keycloak 适配器的 Spring Boot 安全配置)

@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class ApiSecurityConfig 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();
    }

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

    /**
     * Api request URI and their mapping roles and access are configured in this
     * method.This is method from spring security web configuration Override this
     * method to configure the HttpSecurity.
     * 
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);

        http
            .authorizeRequests()
            .antMatchers("/api/*")
            .hasRole("admin")
            .anyRequest()
            .permitAll();


    }
}

我已经通过交叉检查来自 Keycloak 服务器的安装 JSON 文件验证了 application.properties 文件中的 keclaok 属性,如下所示。

从 Keycloak 服务器获取的安装 JSON 文件

{
  "realm": "testRealm",
  "bearer-only": true,
  "auth-server-url": "http://localhost:8080/auth",
  "ssl-required": "external",
  "resource": "backendService",
  "use-resource-role-mappings": true,
  "confidential-port": 0
}

我已经检查过 keycloak.credentials.secret 并且它与我使用的完全相同,但它仍然不允许访问后端并提供

未经授权,状态=401

不确定,如果我遗漏了什么,任何帮助都非常感谢..

4

0 回答 0