【SpringBoot集成SpringSecurity】

本文详细介绍了如何在SpringBoot项目中集成SpringSecurity进行安全配置,包括环境搭建、用户认证与授权、注销功能、权限控制以及记住我功能的实现。通过配置HttpSecurity和AuthenticationManagerBuilder,实现了基于角色的访问控制,并利用Thymeleaf进行前端页面的权限展示。此外,还展示了如何定制登录页面并启用记住我功能。
摘要由CSDN通过智能技术生成

本笔记内容为狂神说SpringBoot集成SpringSecurity部分

目录

一、介绍

二、环境搭建 

1、新建一个初始的springboot项目web模块,thymeleaf模块

2、导入提供的静态资源 

3、controller跳转

三、认识SpringSecurity

四、认证和授权

1、导入 Spring Security 依赖

2、编写配置类

3、测试

五、注销及权限控制

1、开启自动配置的注销的功能

2、添加注销按钮

3、导入thymeleaf依赖

4、修改前端页面

5、关闭csrf功能

6、设置角色功能块的认证

7、测试

 六、记住我

开启记住我功能

七、定制登录页

1、配置跳转指定登录页

2、修改登录页

3、验证处理

4、在登录页增加记住我的多选框

5、后端验证处理

6、测试


一、介绍


    Spring 是一个非常流行和成功的 Java 应用开发框架。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

    对于上面提到的两种应用情景,Spring Security 框架都有很好的支持。在用户认证方面,Spring Security 框架支持主流的认证方式,包括 HTTP 基本认证、HTTP 表单验证、HTTP 摘要认证、OpenID 和 LDAP 等。在用户授权方面,Spring Security 提供了基于角色的访问控制和访问控制列表(Access Control List,ACL),可以对应用中的领域对象进行细粒度的控制。

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

二、环境搭建 


1、新建一个初始的springboot项目web模块,thymeleaf模块

2、导入提供的静态资源 

3、controller跳转

@Controller
public class RouterController {
    @RequestMapping({"/index","/"})
    public String index(){
        return "index";
    }
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "views/login";
    }
    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable("id") Integer id){
        return "views/level1/"+id;
    }
    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id") Integer id){
        return "views/level2/"+id;
    }
    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id") Integer id){
        return "views/level3/"+id;
    }
}

三、认识SpringSecurity


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

记住几个类:

  • WebSecurityConfigurerAdapter:自定义Security策略

  • AuthenticationManagerBuilder:自定义认证策略

  • @EnableWebSecurity:开启WebSecurity模式

Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。

“认证”(Authentication)

身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。

身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。

“授权” (Authorization)

授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。

这个概念是通用的,而不是只在Spring Security 中存在。

四、认证和授权


使用 Spring Security 来增加认证和授权的功能

1、导入 Spring Security 依赖

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

2、编写配置类

在config包下创建SecurityConfig类(自己命名)

// 开启WebSecurity模式
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    //授权
    /*2.7不用继承WebSecurityConfigurerAdapter了
    把方法换成public SecurityFilterChain filterChain(HttpSecurity http)就行*/
    protected void configure(HttpSecurity http) throws Exception {
        // 定制请求的授权规则
        // 首页所有人可以访问
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        // 开启自动配置的登录功能
        // /login 请求来到登录页
        // /login?error 重定向到这里表示登录失败
        http.formLogin();

        
    }

    //定义认证规则
    //认证, springboot 2.1.X可以直接使用~
    // 密码编码: PasswordEncoder
    // 在Spring Secutiry 5.0+新增了很多的加密方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //一般在数据库读
        //在内存中定义,也可以在jdbc中去拿jdbcAuthentication....
        //Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
        //要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密
        //spring security 官方推荐的是使用bcrypt加密方式。
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2");
    }

}

PS:登录时前端传过来的密码是通过加密的方式传过来的,使用我们在定义认证规则的时候也要对密码进行加密,否则会报错。

3、测试

发现不同角色只能访问自己认证下的规则。

五、注销及权限控制


1、开启自动配置的注销的功能

在配置类的configure方法加上

//定制请求的授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
   //....
   //开启自动配置的注销的功能
   // /logout 注销请求
   //http.logout();

    //注销成功后跳转到首页
    http.logout().logoutSuccessUrl("/");
}

2、添加注销按钮

在前端页面添加注销按钮,到index.html 导航栏中

<a class="item" th:href="@{/logout}">
   <i class="address card icon"></i> 注销
</a>

测试注销功能,成功!

3、导入thymeleaf依赖

我们需要登录后根据用户权限显示用户能访问的功能即可,需要结合thymeleaf中的一些功能。

sec:authorize="isAuthenticated()":是否认证登录!来显示不同的页面。

<!-- thymeleaf-extras-springsecurity5 -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

4、修改前端页面

导入命名空间

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"

修改导航栏,增加认证判断

<!--登录注销-->
<div class="right menu">

   <!--如果未登录-->
   <div sec:authorize="!isAuthenticated()">
       <a class="item" th:href="@{/login}">
           <i class="address card icon"></i> 登录
       </a>
   </div>

   <!--如果已登录-->
   <div sec:authorize="isAuthenticated()">
       <a class="item">
           <i class="address card icon"></i>
          用户名:<span sec:authentication="principal.username"></span>
          角色:<span sec:authentication="principal.authorities"></span>
       </a>
   </div>

   <div sec:authorize="isAuthenticated()">
       <a class="item" th:href="@{/logout}">
           <i class="address card icon"></i> 注销
       </a>
   </div>
</div>

这里我们测试就会发现他会根据不同情况显示对应的按钮。

5、关闭csrf功能

如果注销的时候会报错404,因为它默认防止csrf跨站请求伪造,因为会产生安全问题,我们可以将请求改为post表单提交,或者在spring security中关闭csrf功能;(最新版的security就不用设置)

//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout   请求报错403禁用CSRF http.csrf().disable().cors();
        http.csrf().disable();

6、设置角色功能块的认证

<!-- sec:authorize="hasRole('vip1')" -->
<div class="column" sec:authorize="hasRole('vip1')">
   <div class="ui raised segment">
       <div class="ui">
           <div class="content">
               <h5 class="content">Level 1</h5>
               <hr>
               <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
               <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
               <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
           </div>
       </div>
   </div>
</div>

<div class="column" sec:authorize="hasRole('vip2')">
   <div class="ui raised segment">
       <div class="ui">
           <div class="content">
               <h5 class="content">Level 2</h5>
               <hr>
               <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
               <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
               <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
           </div>
       </div>
   </div>
</div>

<div class="column" sec:authorize="hasRole('vip3')">
   <div class="ui raised segment">
       <div class="ui">
           <div class="content">
               <h5 class="content">Level 3</h5>
               <hr>
               <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
               <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
               <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
           </div>
       </div>
   </div>
</div>

7、测试

发现不用权限的用户登录进去会看到不同的功能

 六、记住我


开启记住我功能

//定制请求的授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
//。。。。。。。。。。。
  //记住我功能 cookie默认保存2周 定制记住我的参数!
  http.rememberMe();
}

登录页面就会显示记住我按钮了。

登录成功后,将cookie发送给浏览器保存,以后登录带上这个cookie,只要通过检查就可以免登录了。如果点击注销,spring security 帮我们自动删除了这个 cookie。

七、定制登录页


1、配置跳转指定登录页

在刚才的登录页配置后加上指定的 loginpage

 http.formLogin().loginPage("/toLogin");

2、修改登录页

login.html 配置提交请求及方式,方式必须为post

<form th:action="@{/login}" method="post">
   <div class="field">
       <label>Username</label>
       <div class="ui left icon input">
           <input type="text" placeholder="Username" name="username">
           <i class="user icon"></i>
       </div>
   </div>
   <div class="field">
       <label>Password</label>
       <div class="ui left icon input">
           <input type="password" name="password">
           <i class="lock icon"></i>
       </div>
   </div>
   <input type="submit" class="ui blue submit button"/>
</form>

3、验证处理

配置接收登录的用户名和密码的参数

//这里loginPage("/login")其实就是登录提交的请求路径,要么 loginPage("/login")可以不写,要写了就要和前端的登录提交路径一致
        http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").successForwardUrl("/login");

4、在登录页增加记住我的多选框

<input type="checkbox" name="remember"> 记住我

5、后端验证处理

//定制记住我的参数!
http.rememberMe().rememberMeParameter("remember");

6、测试

发现登录页已成功更换,并且记住我等功能正常使用。

结束! 

Spring Security 是一个基于 Spring 的安全框架,提供了一组完整的安全性功能,包括身份验证、授权、防止 CSRF 攻击等等。Spring Boot 基于 Spring,自然也集成Spring Security。下面是 Spring Boot 集成 Spring Security 的步骤: 1. 在 pom.xml 中添加 Spring Security 的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 编写一个继承自 WebSecurityConfigurerAdapter 的配置类,并使用 @EnableWebSecurity 注解开启 Spring Security: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } } ``` 上面的代码中,我们配置了 Spring Security 的基本功能:对所有请求进行身份验证,允许访问首页和登录页面,使用 inMemoryAuthentication 来指定用户和密码。 3. 在 application.properties 或 application.yml 中配置登录页面的 URL: ```properties spring.security.login.form=/login ``` 4. 编写一个登录页面,例如一个 Thymeleaf 模板: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <form th:action="@{/login}" method="post"> <div><label>Username: <input type="text" name="username"/></label></div> <div><label>Password: <input type="password" name="password"/></label></div> <div><input type="submit" value="Log in"/></div> </form> </body> </html> ``` 这样就完成了 Spring Boot 集成 Spring Security 的配置。当用户访问受保护的页面时,会被重定向到登录页面进行身份验证。如果用户输入的用户名和密码正确,就会跳转到原来请求的页面。如果不正确,就会显示错误信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值