To secure a specific URL in Spring Security, you can use the antMatchers
method of the HttpSecurity
object. This method takes a list of AntPathRequestMatcher
objects, which represent patterns to match against the incoming request's URL.
Here is an example of how to use antMatchers
to secure a specific URL:
@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/secure").hasRole("USER") .antMatchers("/admin").hasRole("ADMIN") .anyRequest().permitAll() .and() .formLogin(); }
In this example, the /secure
URL is only accessible to users with the USER
role, and the /admin
URL is only accessible to users with the ADMIN
role. All other URLs are accessible to all users.
You can also use the antMatchers
method to specify multiple patterns separated by commas, or to specify a pattern using regular expressions.
For example, to match all URLs that start with /api
, you could use the following code:
antMatchers("/api/**")
Or, to match all URLs that end with .html
, you could use the following code:
antMatchers("*.html")