Spring Security HttpSecurity配置
我尝试了解RequestMatcher,AntMatcher等的工作方式。我阅读了一些帖子并了解了基础知识。其实我有这个简单的基本配置:
@Overrideprotected void configure(HttpSecurity http) throws Exception {
http.requestMatchers() //1
.antMatchers("/login", "/oauth/authorize") //2
.and() //3
.authorizeRequests() //4
.anyRequest() //5
.authenticated() //6;
我真的不理解第1,2和3点。根据我的理解,这意味着/login和的请求/oauth/authorize已映射,应该是授权的请求。所有其他请求都需要验证。
/user/me我必须对端点进行身份验证,因为它受第5点和第6点的限制?对该端点的呼叫正在为我工作。
在我的其他配置中,我尝试另一种方法:
@Overrideprotected void configure(HttpSecurity http) throws Exception { // @formatter:off
http
.authorizeRequests() //1
.antMatchers("/login", "/oauth/authorize", "/img/**").permitAll() //2
.anyRequest() //3
.authenticated() //4
从我的角度来看,这应该与第一个配置具有相同的逻辑。但是实际上端点/user/me不再可访问。
我非常感谢您的澄清
现在这是我的配置:
@Overrideprotected void configure(HttpSecurity http) throws Exception { // @formatter:off
http
.requestMatchers()
.antMatchers("/", "/login", "/oauth/authorize",
"/main", "/logout-success", "/single-logout",
"/password_forgotten", "/enter_new_password", "/img/**",
"/logout", "/access_denied")
.and().authorizeRequests()
.antMatchers("/img/**", "/logout-success", "/password_forgotten",
"/enter_new_password", "/access_denied").permitAll()
.requestMatchers(SecurityUtils::isFrameworkInternalRequest).permitAll()
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.defaultSuccessUrl("/main")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/logout-success")
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.and()
.exceptionHandling()
.accessDeniedPage("/access_denied")
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
.and().csrf().disable();
如果我\user\me以未经身份验证的用户身份输入URL,则会收到401和以下消息:
<oauth><error_description>
Vollständige Authentifikation wird benötigt um auf diese Resource zuzugreifen
</error_description>
<error>unauthorized</error>
</oauth>
没关系,但是意味着此URL发生了其他SecurityFilterChain,对吗?
回答:
requestMatchers()配置URL是否将被该URL处理SecurityFilterChain。因此,如果一个URL不匹配它,整个URL
SecurityFilterChain将被跳过,这意味着Spring Security在此之后将不再处理这个URL。如果未配置,则默认为匹配所有URL。
该authorizeRequests()配置为URL配置授权内容,例如是否需要进行身份验证或仅某些角色可以访问它等。它仅对由该SecurityFilterChain处理的那些URL(即与匹配的URL
requestMatchers())有效。
因此,回到您的第一个示例:
http.requestMatchers() //1 .antMatchers("/login", "/oauth/authorize") //2
.and() //3
.authorizeRequests() //4
.anyRequest() //5
.authenticated() //6;
这意味着此SecurityFilterChain仅对/login和起作用/oauth/authorize。这两个URL都需要进行身份验证。此SecurityFilterChain将不会处理所有其他URL。因此,是否/user/me需要通过身份验证与Spring
Security无关。
http .authorizeRequests() //1
.antMatchers("/login", "/oauth/authorize", "/img/**").permitAll() //2
.anyRequest() //3
.authenticated() //4
这意味着所有URL都将由此SecurityFilterChain(默认值为requestMatchers())处理。/login,/oauth/authorize并且/img/**不需要任何授权。其他URL需要进行身份验证。
以上是 Spring Security HttpSecurity配置 的全部内容, 来源链接: utcz.com/qa/430962.html

