1.引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
2.編寫相應的配置類
//開啟Spring Security @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override //認證,划分不同的角色 protected void configure(HttpSecurity http) throws Exception { //首頁所有人可以訪問 http.authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/level1/**").hasRole("vip1") .antMatchers("/level2/**").hasRole("vip2") .antMatchers("/level3/**").hasRole("vip3"); //沒登陸前點需要權限的頁面,會跳轉至登陸頁面 //loginPage為自定義頁面,loginProcessUrl為驗證用戶密碼的路徑 http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login"); http.csrf().disable(); //開啟注銷,注銷成功跳轉相應的頁面 http.logout().logoutSuccessUrl("/"); //開啟記住我 http.rememberMe().rememberMeParameter("remember"); } @Override //授權,賦予用戶角色 protected void configure(AuthenticationManagerBuilder auth) throws Exception { //基於內存,授權 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("yzy").password(new BCryptPasswordEncoder().encode("123456")) .roles("vip1"); } }