SpringBoot-整合SpringSecurity安全框架-12

SpringSecurity安全框架

1. 测试(环境的搭建)

  1. 创建springboot项目的带web模块和thymeleaf模块
  2. 导入静态的资源,包含各个等级的表以及login.html与index.html
  3. 实现controller跳转,在controller中新建一个RouterController
@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")int id){
        return "views/level1/"+id;
    }
    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable("id")int id){
        return "views/level2/"+id;
    }
    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable("id")int id){
        return "views/level3/"+id;
    }

}
  1. 启动主方法测试能否成功

2. SpringSecurity是什么

是针对spring项目的安全框架,也是SpringBoot的底层安全模块,可以实现强大的web安全控制,对于安全控制,只需要引入spring-boot-starter-security模块,再进行少量的配置即可实现强大的安全管理
需要知道的几个类

  • WebSecurityConfigurerAdapter: 自定义Security策略
  • AuthenticationmanagerBuilder: 自定义认证策略
  • @EnableWebSecurity: 开启WebSecurity模式
    springsecurity的两大主要特征是"认证","授权"(访问控制)
    认证(Authentication)
    身份是关于验证的凭据,如用户名和密码,以便验证真实的身份
    身份验证通常通过用户名和密码完成,有时与身份验证的因素结合使用
    授权(Authorization)
    授权发生在系统成功验证身份之后,最终会授予访问资源的权限,例如(信息,文件,数据库,资金,位置)
    这个概念不止在spring security中存在

3. 认证和授权

1. 引入模块,在pom.xml中引入安全模块

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

2. 编写springsecurity的配置类

可以参考官网文档

3. 编写自己的基础配置类

1. 需要继承WebSecurityConfigurerAdapter
2. 需要在该配置类上面加入@EnableWebSecurity注解以开启WebSecurity模式
3. 需要重写方法`protected void configure(HttpSecurity http) throws Exception`
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
	}

4. 定制请求的授权规则

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所与人可以访问,功能页面只能有权限的人访问.请求授权的规则
        http.authorizeRequests().antMatchers("/").permitAll()
                                .antMatchers("/level1/**").hasRole("vip1")
                                .antMatchers("/level2/**").hasRole("vip2")
                                .antMatchers("/level3/**").hasRole("vip3");
	}

5. 测试发现只能跳转到首页,因为目前没有登陆的角色,请求需要登陆的角色拥有对应的权限才能进去(在config()中加入以下的配置开启自动配置登陆的功能)\

http.formLogin();

6. 继续测试发现,没有权限的时候会跳转到登陆的页面

7. 查看登录页的注释信息(我们可以重写configure(AuthenticationManagerBuilder auth)方法

    //认证规则
    //会报密码编码错误,需要给密码加密,在spring security新增了很多的加密方法,如果不编译会被反编译
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这些数据正常应该从数据库中读取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("sli").password(new BCryptPasswordEncoder().encode("qeq")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("qwq")).roles("vip1","vip2","vip3");
    }

如果不用加密的话登陆就会报错There is no PasswordEncoding mapped for the id "null"

8. 权限控制以及注销功能的实现

  1. 开启自动配置的注销功能
      //开启了注销,跳转到首页
        http.logout();
    
2. 在前段增加一个注销的按钮,在index.html的导航栏中
	```java
   <div sec:authorize="isAuthenticated()">
                <a class="item" th:href="@{/logout}">
                    <i class="sign-out icon"></i> 注销
                </a>
    </div>
	```
3. 登陆后点击注销,发现注销完成之后会跳转到登陆页面,需要让注销成功后跳转到首页,如何处理
	```java
 //开启了注销,跳转到首页需要加入.logoutSuccessUrl("/")
        http.logout().logoutSuccessUrl("/");
	```
#### 9. 用户没有登陆的时候,导航栏上只显示登陆按钮,登陆了则显示退出按钮,还有例如sli这个用户只有vip1和vip2的权限,能否登陆之后只显示这两个权限的内容,而隐藏了vip3的内容
需要结合thymeleaf
1. 在pom.xml中引入
```xml
		<dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>
  1. 修改前端的页面
  2. 导入命名空间
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
  1. 修改导航栏,增加认证判断
<!--登录注销-->
            <div class="right menu">

                <!--如果未登录,显示登陆按钮-->
                <div sec:authorize="!isAuthenticated()">
                <a class="item" th:href="@{/toLogin}">
                    <i class="address card icon"></i> 登录
                </a>
                </div>
                <!--如果已登录,显示用户名和注销按钮-->
                <div sec:authorize="isAuthenticated()">
                    <a class="item">
                        用户名:<span sec:authentication="name"></span>
                    </a>
                </div>
                <div sec:authorize="isAuthenticated()">
                <a class="item" th:href="@{/logout}">
                    <i class="sign-out icon"></i> 注销
                </a>
                </div>
            </div>
  1. 重启之后可以看到登陆成功之后,显示了注销按钮,未登录则显示登陆按钮
  2. 如果注销404了,就是因为它默认防止csrf跨站请求伪造,因为会产生安全问题,我们可以将请求改为post表单提交,或者在spring security中关闭csrf功能;在 配置中增加 http.csrf().disable();
  3. 继续将不同的权限显示的东西不同的代码完善
  <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>
  1. 测试之后,权限控制以及注销完成

10.记住我功能的实现

  1. 开启记住我功能在SecurityConfig.class中加入 http.rememberMe();
  2. 重启项目,多了个记住我的按钮,记住了之后重开浏览器也可以直接访问
    使用cookie实现的默认保存14天

11. 定制登陆页面

现在的登陆页面都是spring security 默认的,如何让他跳转到我们自己的Login页面呢

  1. 在刚才的登陆页配置中加入.loginPage("/toLogin").loginProcessingUrl("/login");
 http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");
  1. 在前端需要指向我们自己定义的login请求
 			    <a class="item" th:href="@{/toLogin}">
                    <i class="address card icon"></i> 登录
                </a>
  1. 在登陆页面增加记住我的多选框
 							<div class="field">
                                <input type="checkbox" name="remember"> 记住我
                            </div>
  1. 后端的验证处理
//定制记住我的参数!
http.rememberMe().rememberMeParameter("remember");
  1. 测试完成完整的配置代码如下
package com.sli.SecurityConfig;
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;
/**
 * @author 1_f_
 * @create 2021-09-27 8:59
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所与人可以访问,功能页面只能有权限的人访问.请求授权的规则
        http.authorizeRequests().antMatchers("/").permitAll()
                                .antMatchers("/level1/**").hasRole("vip1")
                                .antMatchers("/level2/**").hasRole("vip2")
                                .antMatchers("/level3/**").hasRole("vip3");


        //没有权限默认到登陆页面,需要开启登陆的页面
        http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");


        //防止网站攻击: get不安全 post安全
        http.csrf().disable();


        //开启了注销,跳转到首页
        http.logout().logoutSuccessUrl("/");


        //开启记住我功能   cookie实现,默认保存两周,  自定义接收前端的参数
        http.rememberMe().rememberMeParameter("remember");
    }

    //认证规则
    //会报密码编码错误,需要给密码加密,在spring security新增了很多的加密方法,如果不编译会被反编译
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //这些数据正常应该从数据库中读取
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("sli").password(new BCryptPasswordEncoder().encode("qeq")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("qwq")).roles("vip1","vip2","vip3");
    }
}

12. 实现授权

  1. 在mysql中增加一列对应权限此时记得在User对象中增加perms属性
    alter table user add column perms varchar(20) not null
  2. 在ShiroConfig中增加拦截以及未授权就跳转的页面
 //拦截
        Map<String,String> filterMap = new LinkedHashMap<>();

        //授权,正常未授权会跳转到未授权页面
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/update","perms[user:update]");
        filterMap.put("/user/*","authc");

        bean.setFilterChainDefinitionMap(filterMap);
  1. 在UserRealm中增加拿到当前登陆用户的权限
@Autowired
    UserService userService;
    @Override
    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权方法");
        //权限授权和认证长得很相似
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        info.addStringPermission("user:add");

        //拿到当前用户登陆的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//拿到User对象
        info.addStringPermission(currentUser.getPerms());//获取当前用户的权限
        return info;
    }
  1. 整合thymeleaf

    1. 导入shiro整合thymeleaf的maven资源
com.github.theborakompanioni thymeleaf-extras-shiro 2.0.0
```
2. 导入命名空间
```html

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

	3. 配置bean在ShiroConfig中
	```java
   @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }
    //整合ShiroDialect 用来整合Shiro 和 thymeleaf

    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
4. 修改页面--->只有有权限的才能看到对应的按钮
```html
add
```
posted @ 2021-09-27 12:05  1_f  阅读(66)  评论(0)    收藏  举报