SpringSecurity(安全)

SpringSecurity(安全)

SpringSecurity是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术,它可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量配置,即可实现强大的安全管理。

安全框架有Shiro, SpringSecurity

Shiro, SpringSecurity: 相似,除了类名不一样,名字不一样

作用:

  • 过滤器

  • 拦截器

  • 认证(Authentication)

  • 授权(Authorization)

    • 功能权限
    • 访问权限
    • 菜单权限

常用类:

  • WebSecurityConfigurerAdapter: 自定义Security策略
  • AuthenticationManagerBuilder: 自定义认证也能够策略
  • @EnableWebSecurity: 开始WebSecurity模式

参考官网: https://spring.io/projects/spring-security

https://docs.spring.io/spring-security/site/docs/5.3.5.RELEASE/reference/html5

https://docs.spring.io/spring-boot/docs/2.0.4.RELEASE/reference/htmlsingle/#using-boot


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
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        //请求授权的规则~
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限默认会到登录页面
        http.formLogin();
//        http.formLogin().loginPage("/login"); //指定自己的login地址
        //注销
        http.logout();
    }

    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
        String encodePassword = new BCryptPasswordEncoder().encode("123456");
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("root").password(encodePassword).roles("vip1", "vip2", "vip3")
                .and()
                .withUser("guest").password(encodePassword).roles("vip1")
                .and();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值