📅  最后修改于: 2023-12-03 15:20:13.452000             🧑  作者: Mango
Spring Security provides a powerful mechanism to control access to different parts of your application based on the user's role or authorities. Antmatchers is a key feature of Spring Security that allows you to specify which URLs and HTTP methods should be secured.
The Antmatchers ID is a unique identifier that you can assign to an Antmatchers configuration. This ID can be used to reference the configuration from other parts of your application, such as when defining a Login page or Logout page.
To create an Antmatchers configuration with an ID, you can use the antMatchers
method with an argument of type RequestMatcher
.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.deleteCookies("JSESSIONID")
.permitAll();
}
In the above code snippet, we're defining two Antmatchers configurations with IDs "/admin/**"
and "/user/**"
. The hasRole
method is used to specify the roles that are allowed to access these URLs. When a user attempts to access a secured URL, Spring Security checks their authorities to see if they have the required role. If they don't, they'll be redirected to the Login page.
To reference the Antmatchers configuration with an ID, you can use the access
method.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.deleteCookies("JSESSIONID")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/accessDenied");
}
In the above code snippet, we're defining an Antmatchers configuration with an ID of "/public/**"
. The permitAll
method is used to specify that anyone can access this URL. The anyRequest
method is used to specify that any other requests should be authenticated.
Later in the code, we're using the access
method to reference the Antmatchers configuration with ID "/public/**"
to define an AccessDenied page. If a user attempts to access a URL that they don't have access to, they'll be redirected to the AccessDenied page.
In conclusion, the Antmatchers ID is a powerful feature of Spring Security that allows you to reference Antmatchers configurations from other parts of your application. It's particularly useful when defining Login and Logout pages or when handling Access Denied errors.