我正试图启用对我的rest api的某些部分的匿名访问,但对其余部分禁用该功能。
我尝试的配置看起来像:
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anonymous().and()
.antMatchers(SOME_URL).authenticated()
.and()
.anoymous().disable()
.antMatchers(OTHER_URL).authenticated();
}
但后来,我意识到后面的anonymous((.disable将覆盖之前的设置。
那么,有人能给我一些建议吗?我该如何为我的部分url启用匿名?
非常感谢!!!
您可以定义一个RequestMatcher,一个用于公共URL,另一个用于受保护的URL。然后,重写接受WebSecurity作为参数的configure方法。在这种方法中,您可以将web配置为忽略您的公共URL。
private static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(
new AntPathRequestMatcher("/public/**")
);
private static final RequestMatcher PROTECTED_URLS = new NegatedRequestMatcher(PUBLIC_URLS);
@Override
public void configure(final WebSecurity web) {
web.ignoring().requestMatchers(PUBLIC_URLS);
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(STATELESS)
.and()
.exceptionHandling()
// this entry point handles when you request a protected page and you are not yet
// authenticated
.defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
.anyRequest()
.authenticated();
// and other clauses you would like to add.
}