我使用 Keycloak 7.0.1 和 Spring Boot 1.5.16.RELEASE 通过指定资源、基于角色的策略和权限来保护端点 - 这按预期工作。
棘手的事情是仅保护 POST 并允许对某个特定 URI 进行 GET 请求。我在 application.yml 中做了什么:
policy-enforcer-config:
enforcement-mode: ENFORCING
paths[0]:
name: all
path: /*
paths[1]:
name: test post
path: /my/url
methods[0]:
method: GET
scopes[0]: view
methods[1]:
method: POST
scopes[0]: edit
在 keyclaok 中,我创建了 edit
和 view
范围、/my/url
资源、具有角色和否定决策的策略(如果用户具有该角色 - 拒绝访问),权限包含资源、范围和策略。评估按预期进行,但我的 Spring 应用程序总是收到 403 错误。
您能否为我提供一个资源范围使用的示例,或者建议我还需要做什么才能使其正常工作?
最佳答案
可能有多个问题,但首先,检查您的 SecurityConfig。
这就是我们现有的:
@Configuration
@EnableWebSecurity
@KeycloakConfiguration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableConfigurationProperties(KeycloakSpringBootProperties.class)
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
bla-bla..
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers(HttpMethod.POST, "/auth/**")
.antMatchers(HttpMethod.OPTIONS,"/**")
// allow anonymous resource requests
.and()
.ignoring()
.antMatchers(
HttpMethod.GET,
"/",
"/*.html",
"/favicon.ico",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/actuator/**"
)
;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// we don't need CSRF because our token is invulnerable
.csrf().disable()
.exceptionHandling()
.defaultAuthenticationEntryPointFor(
getRestAuthenticationEntryPoint(),
new AntPathRequestMatcher("/**")
)
.authenticationEntryPoint(unauthorizedHandler).and()
// don't create session
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
// system state endpoint
.antMatchers("/ping").permitAll()
.antMatchers(HttpMethod.GET, "/whatever/you/need/to/open/to/public/one", "/whatever/you/need/to/open/to/public/two").permitAll()
// User authentication actions
.antMatchers("/auth/**").permitAll()
.antMatchers("/**/*.css").permitAll()
.anyRequest().authenticated()
;
http
.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
;
// disable page caching
http
.headers()
.frameOptions().sameOrigin()
.cacheControl();
}
如果您想使用角色限制 REST API 端点,请为您的 Controller 方法添加 @PreAuthorize("hasRole('your.role.from.keycloak')")
关于spring - Keycloak 与 Spring boot - 如何应用资源范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58727765/