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"); } }