Spring-boot 安全Spring Security

Spring Security相当于是一个springboot内部集成的一个安全框架

Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!记住几个类∶
WebSecurityConfigurerAdapter∶ 自定义Security策略AuthenticationManagerBuilder∶ 自定义认证策略
@EnableWebSecurity∶开启WebSecurity模式

授权:给进入的请求页面设置条件
认证:给要进入相关请求页面的用户设置权限,相当于认证一个用户(登记)

配置Spring Security
1.导入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
</dependency>

配置文件中关闭catch

spring.thymeleaf.cache=false

2.设置相关的配置类

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    //授权
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问,功能页只有对应的有权限的人才能访问
        //请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasAnyRole("vip1")
                .antMatchers("/level2/**").hasAnyRole("vip2")
                .antMatchers("/level3/**").hasAnyRole("vip3");
        //没有权限默认到登录界面,需要开启登录的页面、
        //这个登录界面是自带的
        http.formLogin()
       
       
    }
    //密码编码
    //在spring security 5 新增了很多加密方式 没有加密的话不能用
    //密码编码 BCryptPasswordEncoder()

    @Override
    //认证
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("zhou").password(new BCryptPasswordEncoder().encode("1234")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("1")).roles("vip1");
    }
}

3.注销

//注销 注销成功返回首页
        http.logout().logoutSuccessUrl("/");

4.记住我
在这里插入图片描述
前端代码

<div class="field">
      <input type="checkbox" name="remember">记住我
 </div>

配置类代码

 http.rememberMe().rememberMeParameter("remember");

5自定义登录页
登录页默认的是自带的

http.formLogin() .loginProcessingUrl("/login") //当发现/login请求时认为是登录 执行登录
        .loginPage("/login.html");


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值