Spring boot整合 Security
pom.xml中引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
然后编写SecurityConfig文件
@EnableWebSecurity //开启安全
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权的规则
@Override
protected void configure(HttpSecurity http) throws Exception {
//链式授权,首页全部可以访问,后面目录 需要有对应的权限才可以访问,否则报403错误
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限会默认回到登录页面,需要开启登录的权限
http.formLogin();
//修改 传递给login页面的参数
http.formLogin().loginPage("/loginPage").
usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");
http.cors().disable();//关闭跨域攻击防御
http.rememberMe();//开启记住我功能
http.rememberMe().rememberMeParameter("remember");//修改前端传过来的 remember me的参数
}
//认证的规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//从内存里读,应该是从数据库里读 psswordEncoder 将密码加密 否则会报错500,密码未加密
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2").and()
.withUser("maxcui").password("123456").roles("vip1","vip2","vip3").and()
.withUser("guest").password("123456").roles("vip1");
}
}

浙公网安备 33010602011771号