1. 程式人生 > >SpringSecurity配置多個HttpSecurity(SpringBoot適用)

SpringSecurity配置多個HttpSecurity(SpringBoot適用)

package pers.lbw.digitalmall.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.
EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.util.AntPathMatcher; import javax.servlet.annotation.MultipartConfig; @EnableWebSecurity @Configuration public class MultiHttpSecurityConfig{ @Configuration
@Order(1) public static class ForeConfigurationAdapter extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/fore/**")//多HttpSecurity配置時必須設定這個,除最後一個外,因為不設定的話預設匹配所有,就不會執行到下面的HttpSecurity了 .formLogin() .loginPage("/fore/user/login"
)//登陸介面頁面跳轉URL .loginProcessingUrl("/fore/user/loginPost")//登陸介面發起登陸請求的URL .failureUrl("/fore/user/login")//登陸失敗的頁面跳轉URL .permitAll()//表單登入,permitAll()表示這個不需要驗證 .and()//Return the SecurityBuilder .authorizeRequests()//啟用基於 HttpServletRequest 的訪問限制,開始配置哪些URL需要被保護、哪些不需要被保護 .antMatchers("/user/**", "/detail/toDetailPage*").permitAll()//未登陸使用者允許的請求 .anyRequest().hasAnyRole("USER")//其他/fore路徑下的請求全部需要登陸,獲得USER角色 .and() .csrf().disable(); } } @Configuration @Order(2) public static class AdminSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/admin/**") .formLogin() .loginPage("/fore/user/login")//登陸介面頁面跳轉URL .loginProcessingUrl("/fore/user/login111")//登陸介面發起登陸請求的URL .failureUrl("/fore/user/login")//登陸失敗的頁面跳轉URL .permitAll()//表單登入,permitAll()表示這個不需要驗證 .and()//Return the SecurityBuilder .authorizeRequests()//啟用基於 HttpServletRequest 的訪問限制,開始配置哪些URL需要被保護、哪些不需要被保護 .antMatchers("/admin/**").hasAnyRole("ADMIN")//其他/fore路徑下的請求全部需要登陸,獲得USER角色 .and() .csrf().disable(); } } @Configuration @Order(3) public static class OtherSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests()//啟用基於 HttpServletRequest 的訪問限制,開始配置哪些URL需要被保護、哪些不需要被保護 .antMatchers("/","/code/**","/css/**", "/img/**", "/js/**").permitAll()//其他請求放行 .and() .csrf() .disable();//未登陸使用者允許的請求 } } }