Authorize HttpServletRequests with AuthorizationFilter -- Spring Security()

  本篇文章为你整理了Authorize HttpServletRequests with AuthorizationFilter :: Spring Security()的详细内容,包含有 Authorize HttpServletRequests with AuthorizationFilter :: Spring Security,希望能帮助你了解 Authorize HttpServletRequests with AuthorizationFilter :: Spring Security。

   Authorize HttpServletRequests with AuthorizationFilterThis section builds on Servlet Architecture and Implementation by digging deeper into how authorization works within Servlet-based applications.

  
AuthorizationFilter supersedes FilterSecurityInterceptor.

  To remain backward compatible, FilterSecurityInterceptor remains the default.

  This section discusses how AuthorizationFilter works and how to override the default configuration.

  
You can override the default when you declare a SecurityFilterChain.

  Instead of using authorizeRequests, use authorizeHttpRequests, like so:

  
Uses the simplified AuthorizationManager API instead of metadata sources, config attributes, decision managers, and voters.

  This simplifies reuse and customization.

  
Delays Authentication lookup.

  Instead of the authentication needing to be looked up for every request, it will only look it up in requests where an authorization decision requires authentication.

  
If authorization is denied, an AccessDeniedException is thrown.

  In this case the ExceptionTranslationFilter handles the AccessDeniedException.

  
If access is granted, AuthorizationFilter continues with the FilterChain which allows the application to process normally.

  
We can configure Spring Security to have different rules by adding more rules in order of precedence.

  
.authorizeHttpRequests(authorize - authorize (1)

   .requestMatchers("/resources/**", "/signup", "/about").permitAll() (2)

   .requestMatchers("/admin/**").hasRole("ADMIN") (3)

   .requestMatchers("/db/**").access(new WebExpressionAuthorizationManager("hasRole(ADMIN) and hasRole(DBA)")) (4)

   // .requestMatchers("/db/**").access(AuthorizationManagers.allOf(AuthorityAuthorizationManager.hasRole("ADMIN"), AuthorityAuthorizationManager.hasRole("DBA"))) (5)

   .anyRequest().denyAll() (6)

   return http.build();

  }

 

 

  
There are multiple authorization rules specified.

  Each rule is considered in the order they were declared.

  
We specified multiple URL patterns that any user can access.

  Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about".

  
Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN".

  You will notice that since we are invoking the hasRole method we do not need to specify the "ROLE_" prefix.

  
Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA".

  You will notice that since we are using the hasRole expression we do not need to specify the "ROLE_" prefix.

  
Any URL that has not already been matched on is denied access.

  This is a good strategy if you do not want to accidentally forget to update your authorization rules.

  


@Bean

 

  SecurityFilterChain web(HttpSecurity http, AuthorizationManager RequestAuthorizationContext access)

   throws AuthenticationException {

   http

   .authorizeHttpRequests((authorize) - authorize

   .anyRequest().access(access)

   // ...

   return http.build();

  @Bean

  AuthorizationManager RequestAuthorizationContext requestMatcherAuthorizationManager(HandlerMappingIntrospector introspector) {

   MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector);

   RequestMatcher permitAll =

   new AndRequestMatcher(

   mvcMatcherBuilder.pattern("/resources/**"),

   mvcMatcherBuilder.pattern("/signup"),

   mvcMatcherBuilder.pattern("/about"));

   RequestMatcher admin = mvcMatcherBuilder.pattern("/admin/**");

   RequestMatcher db = mvcMatcherBuilder.pattern("/db/**");

   RequestMatcher any = AnyRequestMatcher.INSTANCE;

   AuthorizationManager HttpServletRequest manager = RequestMatcherDelegatingAuthorizationManager.builder()

   .add(permitAll, (context) - new AuthorizationDecision(true))

   .add(admin, AuthorityAuthorizationManager.hasRole("ADMIN"))

   .add(db, AuthorityAuthorizationManager.hasRole("DBA"))

   .add(any, new AuthenticatedAuthorizationManager())

   .build();

   return (context) - manager.check(context.getRequest());

  }

 

  
Here is an example of mapping a custom authorization manager to the my/authorized/endpoint:

  
.authorizeHttpRequests((authorize) - authorize

   .requestMatchers("/my/authorized/endpoint").access(new CustomAuthorizationManager());

   // ...

   return http.build();

  }

 

 

  
.authorizeHttpRequests((authorize) - authorize

   .anyRequest().access(new CustomAuthorizationManager());

   // ...

   return http.build();

  }

 

 

  
By default, the AuthorizationFilter applies to all dispatcher types.

  We can configure Spring Security to not apply the authorization rules to all dispatcher types by using the shouldFilterAllDispatcherTypes method:

  
Instead of setting shouldFilterAllDispatcherTypes to false, the recommended approach is to customize authorization on the dispatcher types.

  For example, you may want to grant all access on requests with dispatcher type ASYNC or FORWARD.

  
.authorizeHttpRequests((authorize) - authorize

   .dispatcherTypeMatchers(DispatcherType.ASYNC, DispatcherType.FORWARD).permitAll()

   .anyRequest().authenticated()

   // ...

   return http.build();

  }

 

 

  
authorizeHttpRequests {

   authorize(DispatcherTypeRequestMatcher(DispatcherType.ASYNC, DispatcherType.FORWARD), permitAll)

   authorize(anyRequest, authenticated)

   return http.build()

  }

 

 

  
.authorizeHttpRequests((authorize) - authorize

   .dispatcherTypeMatchers(DispatcherType.ERROR).hasRole("ADMIN")

   .anyRequest().authenticated()

   // ...

   return http.build();

  }

 

 

  
authorizeHttpRequests {

   authorize(DispatcherTypeRequestMatcher(DispatcherType.ERROR), hasRole("ADMIN"))

   authorize(anyRequest, authenticated)

   return http.build()

  }

 

 

  
The RequestMatcher interface is used to determine if a request matches a given rule.

  We use securityMatchers to determine if a given HttpSecurity should be applied to a given request.

  The same way, we can use requestMatchers to determine the authorization rules that we should apply to a given request.

  Look at the following example:

  
@Bean

   public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

   http

   .securityMatcher("/api/**") (1)

   .authorizeHttpRequests(authorize - authorize

   .requestMatchers("/user/**").hasRole("USER") (2)

   .requestMatchers("/admin/**").hasRole("ADMIN") (3)

   .anyRequest().authenticated() (4)

   .formLogin(withDefaults());

   return http.build();

  }

 

 

  
authorize("/user/**", hasRole("USER")) (2)

   authorize("/admin/**", hasRole("ADMIN")) (3)

   authorize(anyRequest, authenticated) (4)

   return http.build()

  }

 

 

  
The securityMatcher(s) and requestMatcher(s) methods will decide which RequestMatcher implementation fits best for your application: If Spring MVC is in the classpath, then MvcRequestMatcher will be used, otherwise, AntPathRequestMatcher will be used.

  You can read more about the Spring MVC integration here.

  
If you want to use a specific RequestMatcher, just pass an implementation to the securityMatcher and/or requestMatcher methods:

  


import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; (1)

 

  import static org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher;

  @Configuration

  @EnableWebSecurity

  public class SecurityConfig {

   @Bean

   public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

   http

   .securityMatcher(antMatcher("/api/**")) (2)

   .authorizeHttpRequests(authorize - authorize

   .requestMatchers(antMatcher("/user/**")).hasRole("USER") (3)

   .requestMatchers(regexMatcher("/admin/.*")).hasRole("ADMIN") (4)

   .requestMatchers(new MyCustomRequestMatcher()).hasRole("SUPERVISOR") (5)

   .anyRequest().authenticated()

   .formLogin(withDefaults());

   return http.build();

  public class MyCustomRequestMatcher implements RequestMatcher {

   @Override

   public boolean matches(HttpServletRequest request) {

   // ...

  }

 

  


import org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher (1)

 

  import org.springframework.security.web.util.matcher.RegexRequestMatcher.regexMatcher

  @Configuration

  @EnableWebSecurity

  open class SecurityConfig {

   @Bean

   open fun web(http: HttpSecurity): SecurityFilterChain {

   http {

   securityMatcher(antMatcher("/api/**")) (2)

   authorizeHttpRequests {

   authorize(antMatcher("/user/**"), hasRole("USER")) (3)

   authorize(regexMatcher("/admin/**"), hasRole("ADMIN")) (4)

   authorize(MyCustomRequestMatcher(), hasRole("SUPERVISOR")) (5)

   authorize(anyRequest, authenticated)

   return http.build()

  }

 

  
Import the static factory methods from AntPathRequestMatcher and RegexRequestMatcher to create RequestMatcher instances.

  
Configure HttpSecurity to only be applied to URLs that start with /api/, using AntPathRequestMatcher

  
Allow access to URLs that start with /user/ to users with the USER role, using AntPathRequestMatcher

  
Allow access to URLs that start with /admin/ to users with the ADMIN role, using RegexRequestMatcher

  
Allow access to URLs that match the MyCustomRequestMatcher to users with the SUPERVISOR role, using a custom RequestMatcher

  以上就是Authorize HttpServletRequests with AuthorizationFilter :: Spring Security()的详细内容,想要了解更多 Authorize HttpServletRequests with AuthorizationFilter :: Spring Security的内容,请持续关注盛行IT软件开发工作室。

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: