1. 程式人生 > >使用SpringBoot搭建SpringSecurity環境與驗證

使用SpringBoot搭建SpringSecurity環境與驗證

Security作用描述源自:
https://www.cnblogs.com/jaylon/p/4905769.html





實操:搭配環境

一.首先需要建立IDEA建立一個SpringBoot專案,需要選擇上Security

 

二.建立完畢後測試一下是否可以執行
(建立完專案後會有一個類,在該類中建立一個URL路徑並測試是否執行)
 

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})//去掉資料庫等資訊的依賴
@RestController//@RestController註解相當於@ResponseBody + @Controller合在一起的作用。
@EnableAutoConfiguration//SpringBoot程式入口

public class QxglxtApplication {
    public static void main(String[] args) {
        SpringApplication.run(QxglxtApplication.class, args);
    }

    //設定一個URL路徑"/",輸入"/"後提示"hello spring boot"頁面
    @RequestMapping("/")
    public String home(){
        return "hello spring boot";
    }
}

 

測試結果:

 

 

 

實操:驗證

一.自行建立一個SpringSecurityConfig類,在裡面進行地址驗證

要求:忽略掉專案中JS或則CSS等檔案(不進行攔截),預設"/"首頁,logout登出,formlogin登入不攔截(可以隨意訪問),當用戶輸入其他的網址url地址會直接進行攔截


 

@Configuration//等同於在Spring建立bean物件
@EnableWebSecurity//Security配置註解
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    //忽略掉JS或則CSS等檔案(不進行攔截)
    @Override
    public void configure(WebSecurity web) throws Exception {
       web.ignoring().antMatchers("/js/**","/css/**","/images/**");
    }

    //預設/首頁,logout登出,formlogin登入不攔截,其他的網址url直接攔截
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .logout()
                .and()
                .formLogin();

    }
}

 

 

測試結果:
亂輸入地址會出現這個介面,而"/"就會出現指定頁面