我已经将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"
}
阿比
@RequestMapping(value="/hello",method=RequestMethod.GET)
@ResponseBody
public String getStandards(){
return "hello";
}
答案 0 :(得分: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
答案 1 :(得分:0)
“/ hello”与配置方法中指定的“/ school-admin *”不匹配。