类似于拦截器,过滤器,AOP。这个更为简洁
基于SpringBoot版本2.0.9以下
1.导入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.编写Security配置类
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@EnableWebSecurity //开启WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//1.授权
@Override
protected void configure(HttpSecurity http) throws Exception {
// 首页所有人可以访问,其他页面只有有对应权限的人才可以访问
// 认证请求:authorizeRequests()
http
.authorizeRequests()
.antMatchers("/","/login","/home").permitAll() //所有人可以访问的页面
.antMatchers("/page1/**").hasAnyRole("admin1") //vip1才可以访问的页面
.antMatchers("/page2/**").hasAnyRole("admin2") //vip2才可以访问页面
.antMatchers("/page3/**").hasAnyRole("admin3"); //vip2才可以访问页面
// .anyRequest().authenticated()
// .and()
// .formLogin()
// .loginPage("/login").permitAll()
// .and()
// .logout()
// .permitAll();
//没有权限的话,会跳到login页面
http.formLogin();
//关闭csrf功能,跨站访问
http.cors().disable();
//注销,成功后跳到首页 logoutUrl = "/logout" logoutSuccessUrl = "/login?logout"
http.logout().logoutSuccessUrl("/");
}
//2.认证
//需要 密码编码:PasswordEncoder
// 早Spring Securty 5.0+ 新增了很多的加密方法 ,还有java原生的MD5 等等
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//从数据库认证:jdbcAuthentication() ,没连数据库 从内存认证:inMemoryAuthentication(),这里实验就直接使用实验内存认证了
auth.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder()) //加密的方法
.withUser("lan") //用户名
.password(new BCryptPasswordEncoder().encode("123")) //密码
.roles("admin1") //拥有的权限
.and() //加下一个用户
.withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("admin1","admin2","admin3")
}
}
1504

被折叠的 条评论
为什么被折叠?



