SpringSecurity安全管理

SpringSecurity安全管理

介绍

SpringSecurity是spring的一个生态圈,用于安全管理,其核心就是一组过滤链,启动项目后将会自动配置。其核心就是Basic Authentication Filter 用来认证用户的身份。

SpringSecurity的核心功能主要有

  • Authentication认证(你是谁)
  • Authorization授权(你能干什么)
  • 攻击防护(防止身份伪造)

使用

  1. 创建一个springboot项目,勾选web功能

  2. 添加依赖SpringSecurity

    <!-- Security+Thymeleaf整合 -->
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        <version>3.0.4.RELEASE</version>
    </dependency>
    <!-- security -->
    <dependency>
    	<groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <!-- Thymeleaf依赖 -->
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-java8time</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  3. 在application.yaml中配置mvc视图解析器

    spring:
      thymeleaf:
        cache: false
      mvc:
        view:
          suffix: .html
          prefix: classpath:/templates/
    # mvc视图解析器
    
  4. 在resources文件夹下编写html

  5. views/level1/1.html/(2.html-3.html)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1 align="center">one-1</h1>
        <hr>
    </body>
    </html>
    
  6. views/level2/1.html/(2.html-3.html)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1 align="center">two-1</h1>
        <hr>
    </body>
    </html>
    
  7. views/level3/1.html/(2.html-3.html)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1 align="center">three-1</h1>
        <hr>
    </body>
    </html>
    
  8. 首页index.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org"
                    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            dev span{
                padding-right: 20px;
            }
        </style>
    </head>
    <body>
    <!--
    如果未登入就就显示登入按钮,
    如果以登入显示用户名和注销按钮,
    需要用到thymeleaf+Security整合模板
    -->
        <h1 align="center">首页</h1>
        <!--登入成功后显示用户名-->
        <div sec:authorize="isAuthenticated()">
            <p align="center">
                <a>
                    用户名:<spqn sec:authentication="name"></spqn>
                    <!--角色:<spqn sec:authentication="principal.getAuthorities()"></spqn>-->
                </a>
            </p>
        </div>
        <!--如果用户未登入,显示登入页面-->
        <div sec:authorize="!isAuthenticated()">
            <p>
                <a th:href="@{/toLogin}">登入</a>
            </p>
        </div>
        <!--如果登入成功则显示注销按钮-->
        <div sec:authorize="isAuthenticated()">
            <p>
                <a th:href="@{/logout}">注销</a>
            </p>
        </div>
    <dev>
        <dev>
            <p align="center">lenel1</p>
            <hr>
            <dev class="b" sec:authorize="hasRole('vip1')">
                <span><a th:href="@{/level1/1}">one-1</a></span>
                <span><a th:href="@{/level1/2}">one-2</a></span>
                <span><a th:href="@{/level1/3}">one-3</a></span>
            </dev>
        </dev>
        <dev>
            <dev class="b" sec:authorize="hasRole('vip2')">
                <p align="center">lenel2</p>
                <hr>
                <span><a th:href="@{/level2/1}">two-1</a></span>
                <span><a th:href="@{/level2/2}">two-2</a></span>
                <span><a th:href="@{/level2/3}">two-3</a></span>
            </dev>
        </dev>
        <dev>
            <dev class="b" sec:authorize="hasRole('vip3')">
                <p align="center">lenel3</p>
                <hr>
                <span><a th:href="@{/level3/1}">three-1</a></span>
                <span><a th:href="@{/level3/2}">three-2</a></span>
                <span><a th:href="@{/level3/3}">three-3</a></span>
            </dev>
        </dev>
    </dev>
    </body>
    </html>
    
  9. 登入页login.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Spring Security</title>
        <meta charset="utf-8">
    </head>
    <body>
    <div>
        <div>
            <div>
                <span>登 录</span>
            </div>
            <form th:action="@{/toLogin}" method="post">
                <div>
                    <span>用户名:</span>
                    <input type="text" name="username" placeholder="请输入用户名">
                    <span></span>
                </div>
                <div>
                    <span >密&nbsp;&nbsp;&nbsp;&nbsp;码:</span>
                    <input type="password" name="password" placeholder="请输入用户名">
                    <span></span>
                </div>
                <div>
                    <div>
                        <input class="input-checkbox" id="ckb1" type="checkbox" name="remember-me">
                        <label class="label-checkbox" for="ckb1">记住我</label>
                    </div>
                    <div>
                        <a href="/">忘记密码?</a>
                    </div>
                </div>
                <div>
                    <input type="submit" value="提交">
                </div>
            </form>
        </div>
    </div>
    </body>
    </html>
    
    
  10. controller实现视图跳转

    package com.sheep.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class RouterController{
    
        /*
         * 首页
         * */
        @RequestMapping({"/","/index","index.html"})
        public String index(){
            return "index";
        }
        /*
         * 登入页
         * */
        @RequestMapping("/toLogin")
        public String toLogin(){
            return "views/login";
        }
        /*
        * VIP1
        * */
        @RequestMapping("/level1/{id}")
        public String level1(@PathVariable("id") int id){
            return "views/level1/"+id;
        }
        /*
         * VIP2
         * */
        @RequestMapping("/level2/{id}")
        public String level2(@PathVariable("id") int id){
            return "views/level2/"+id;
        }
        /*
         * VIP3
         * */
        @RequestMapping("/level3/{id}")
        public String level3(@PathVariable("id") int id){
            return "views/level1/"+id;
        }
    }
    
  11. 自定义Security策略

    注解及类作用:

    • @EnableWebSecurity:开启WebSecurituy模式
    • WebSecurityConfigurerAdapter:自定义Securituy
    • HttpSecurity:拦截授权
    • AuthenticationManagerBuilder:自定义认证
    package com.sheep.config;
    
    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 {
            //首页所有人可以访问,功能页只有对应有权限的人才能访问(所有人可以访问/,vip1的用户可以访问/level1/**,vip2的用户可以访问/level2/**,vip3的用户可以访问/level3/**)
            http.authorizeRequests().antMatchers("/").permitAll()
                    .antMatchers("/level1/**").hasRole("vip1")
                    .antMatchers("/level2/**").hasRole("vip2")
                    .antMatchers("/level3/**").hasRole("vip3");
            // 没有权限会默认跳到登入页面,需要开启登入的页面
            http.formLogin().loginPage("/toLogin");
            //注销,注销成功了跳到首页
            http.logout().logoutSuccessUrl("/");
            //开启记住我功能
            http.rememberMe();
            //防止网站工具(在get传输是通过明文传输的因此可能受到攻击):get,post
            http.csrf().disable();//关闭csrf功能
        }
    
        /*
        * 认证:
        *   内存认证
        *   数据库认证
        * 使用内存认证时:要设置密码编码,对密码进行加密(为了防止通过反编译拿到数据密码)
        * 在Spring Secutiry 中提供了很多加密方法
        * */
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //内存认证(模仿数据库),通过.passwordEncoder(new BCryptPasswordEncoder())加密
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("sheep").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                    .and()
                    .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                    .and()
                    .withUser("root2").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
        }
    }
    
  12. 测试

posted @ 2021-05-20 17:07  一程山水一年华^_^  阅读(192)  评论(0编辑  收藏  举报
TOP 底部 /*显示代码块行号*/