【问题标题】:spring securtity rest api not secured with keycloakspring security rest api 与 keycloak 不安全
【发布时间】:2017-09-16 19:07:53
【问题描述】:

我已将 keycloak 与旧版 spring 应用程序集成。我已将 keycloak spring 安全适配器添加到我的 pom.xml 文件中并添加了安全配置。完成所有操作后,我无需令牌即可访问其余 api。我该如何解决这个问题?

@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter
{
    /**
     * Registers the KeycloakAuthenticationProvider with the authentication manager.
     */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(keycloakAuthenticationProvider());
    }

    /**
     * Defines the session authentication strategy.
     */
    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        super.configure(http);
        http
                .authorizeRequests()
                .antMatchers("/school-admin*").hasRole("ADMIN")
                .anyRequest().permitAll();
    }
} 

keycloak.json

{
  "realm": "appscook",
  "bearer-only": true,
  "auth-server-url": "http://localhost:8080/auth",
  "ssl-required": "external",
  "resource": "ssd-backend"
}

API

  @RequestMapping(value="/hello",method=RequestMethod.GET)
    @ResponseBody
     public String getStandards(){
        return "hello";
    }

【问题讨论】:

    标签: spring keycloak


    【解决方案1】:

    "/hello" 与您的配置方法中指定的""/school-admin*" 不匹配。

    【讨论】:

    • "/hello" 在类级别请求映射 "/school-admin*" 内
    • 您是否尝试在 * "/school-admin/*" 之前添加斜杠
    【解决方案2】:

    你可以试试,下面的配置功能。

    @Override
    protected void configure(HttpSecurity http) throws Exception {
            super.configure(http);
            http.authorizeRequests()
                .anyRequest().fullyAuthenticated();
    }
    

    您也可以在控制器的功能上使用@PreAuthorize("hasRole('ADMIN')") 注释,并使用以下Spring配置;

    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter
    

    【讨论】:

      猜你喜欢
      • 2019-09-13
      • 2015-12-03
      • 2014-04-27
      • 1970-01-01
      • 2023-01-15
      • 1970-01-01
      • 2014-08-31
      • 2018-03-12
      • 2016-03-20
      相关资源
      最近更新 更多