SpringSecurity匹配規則介紹


SpringSecurity匹配規則
一 URL匹配

requestMatchers() 配置一個request Mather數組,參數為RequestMatcher 對象,其match 規則自定義,需要的時候放在最前面,對需要匹配的的規則進行自定義與過濾
authorizeRequests() URL權限配置
antMatchers() 配置一個request Mather 的 string數組,參數為 ant 路徑格式, 直接匹配url
anyRequest 匹配任意url,無參 ,最好放在最后面

 

二 保護URL

authenticated() 保護UrL,需要用戶登錄
permitAll() 指定URL無需保護,一般應用與靜態資源文件
hasRole(String role) 限制單個角色訪問,角色將被增加 “ROLE_” .所以”ADMIN” 將和 “ROLE_ADMIN”進行比較. 另一個方法是hasAuthority(String authority)
hasAnyRole(String… roles) 允許多個角色訪問. 另一個方法是hasAnyAuthority(String… authorities)
access(String attribute) 該方法使用 SPEL, 所以可以創建復雜的限制 例如如access("permitAll"), access("hasRole('ADMIN') and hasIpAddress('123.123.123.123')")
hasIpAddress(String ipaddressExpression) 限制IP地址或子網

 

三 登錄login

formLogin() 基於表單登錄
loginPage() 登錄頁
defaultSuccessUrl 登錄成功后的默認處理頁
failuerHandler登錄失敗之后的處理器
successHandler登錄成功之后的處理器
failuerUrl登錄失敗之后系統轉向的url,默認是this.loginPage + "?error"

 

四 登出logout

logoutUrl 登出url , 默認是/logout, 它可以是一個ant path url
logoutSuccessUrl 登出成功后跳轉的 url 默認是"/login?logout"
logoutSuccessHandler 登出成功處理器,設置后會把logoutSuccessUrl 置為null
下面的代碼片段就不會攔截/user,因為只會匹配"/api/**"
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
  http.requestMatchers().antMatchers("/api/**")
    .and().authorizeRequests().antMatchers("/user","/api/user").authenticated()
    .anyRequest().authenticated()
    .and().formLogin().loginPage("/login");
  //需要人證
  // http.authorizeRequests().antMatchers("/user").hasRole("Admin");
  // .and().formLogin().loginPage("/login");
  //api請求都不需要權限認證
  // http.authorizeRequests().antMatchers("/api").permitAll();
  // data/** Get請求不需要權限人證
  // http.authorizeRequests().antMatchers(HttpMethod.GET,"/data/**").permitAll();
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM