zoukankan      html  css  js  c++  java
  • SpringBoot-SpringSecurity

    SpringSecurity

    1. 简介

    SpringSecurity是SpringBoot默认的底层安全模块的技术选型

    重要的类(SpringSecurity的核心)

    • WebSecurityConfigureAdapter: 自定义Security策略
    • AuthenticationManagerBuilder: 自定义认证策略
    • @EnableWebSecurity: 开启WebSecurity模式

    两个核心目标是"认证"和"授权" (访问控制)

    认证 ====> Authentication

    授权 ====> Authorization

    利用了AOP

    2. 访问控制

    1. 导入依赖

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

    包含了AOP织入

    2. 固定结构搭建

    注解, 继承, 重写

    package com.wang.config;
    
    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;
    
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            super.configure(http);
        }
    }
    

    3. 用户认证和授权

    package com.wang.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;
    import org.springframework.security.crypto.password.PasswordEncoder;
    
    @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");
    
            //没有权限, 默认回到登录页面(/login), 需要开启登录的页面
            /*
                The most basic configuration defaults to automatically generating a login page at
                the URL "/login", redirecting to "/login?error" for authentication failure.
             */
            http.formLogin();
        }
    
        //认证
        //密码编码:  PassWordEncoding
        //在SpringSecurity 5.0+ 新增了很多的加密方式
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
            //此处的数据是从内存中读的, 而正常情况下应该从数据库中读
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("wang").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");
        }
    }
    

    注意

    • .passwordEncoder(new BCryptPasswordEncoder())一定要写, SpringSecurity5要求密码硬编码提高安全性
    • .password(new BCryptPasswordEncoder().encode("123456")) 对密码进行编码
    • .and() 添加多个用户
    • 默认的登录页面: /login

    3. 注销及权限控制

    1. 注销

    //链式编程
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问, 功能页只有对应有权限的人才能访问
        //请求授权的规则
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
    
        //没有权限, 默认回到登录页面(/login), 需要开启登录的页面
        /*
            The most basic configuration defaults to automatically generating a login page at
            the URL "/login", redirecting to "/login?error" for authentication failure.
         */
        http.formLogin();
    
        //注销, 开启了注销功能, 跳到首页
        /*
            The default is that accessing the URL
         "/logout" will log the user out by invalidating the HTTP Session, cleaning up any
         {@link #rememberMe()} authentication that was configured, clearing the
         {@link SecurityContextHolder}, and then redirect to "/login?success".
         */
        http.logout().deleteCookies("remove").invalidateHttpSession(true).logoutSuccessUrl("/");
        //get 明文, a标签, 不安全      post 表单, 安全
        //SpringSecurity默认开启了防止csrf攻击的设置, 使用disable可以将其关闭
        http.csrf().disable();
    }
    

    2. 整合thymeleaf和SpringSecurity

    导入依赖

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

    html添加提示

    <html lang="en" xmlns:th="http://www.thymeleaf.org"
          xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
    

    登录注销的控制

    <!--登录注销-->
    <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" th:href="@{/logout}">
                <i class="sign-out icon"></i> 注销
            </a>
        </div>
        <div sec:authorize="isAuthenticated()">
            <a class="item">
                用户名: <span sec:authentication="principal.username"></span>
                角色: <span sec:authentication="principal.authorities"></span>
            </a>
        </div>
    
    </div>
    

    使用 sec: 标签

    3. 根据权限实现动态菜单

    <!--根据用户的角色动态实现菜单-->
    <div>
        <br>
        <div class="ui three column stackable grid">
            <!--如果有对应的权限, 则显示-->
            <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>
        </div>
    </div>
    

    利用sec:authorize="hasRole('')"对div 块是否显示做权限判断, 注意, hasRole方法中用单引号

    4. controller利用RestFul实现URL的复用

    package com.wang.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"})
        public String index() {
            return "index";
        }
    
        @RequestMapping("/toLogin")
        public String toLogin() {
            return "views/login";
        }
    
        //实现路径的复用 (利用前端传来的数据实现不同的跳转, 返回值拼接字符串)
        @RequestMapping("/level1/{id}")
        public String toLevel1(@PathVariable("id") int id) {
            return "views/level1/" + id;
        }
    
        //实现路径的复用 (利用前端传来的数据实现不同的跳转, 返回值拼接字符串)
        @RequestMapping("/level2/{id}")
        public String toLevel2(@PathVariable("id") int id) {
            return "views/level2/" + id;
        }
    
        //实现路径的复用 (利用前端传来的数据实现不同的跳转, 返回值拼接字符串)
        @RequestMapping("/level3/{id}")
        public String toLevel3(@PathVariable("id") int id) {
            return "views/level3/" + id;
        }
    }
    

    前端代码 a th:href="@{/level1/1}" 在thymeleaf中自动使用为RestFul风格, 在controller中用/{XXX} 以及@PathVariable("XXX")取到就可以用了!

    4. 自定义login以及RememberMe

    1. 自定义login

    在授权的代码中, loginProcessingUrl放的URL和前端表单提交的URL一致

    //自定义登录页面
    http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");
    
    <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>
    </form>
    

    2. 自定义RememberMe

    <div class="field">
        <input type="checkbox" name="rememberMe">记住我
    </div>
    
    //开启记住我功能   cookie 默认保存两周   自定义rememberMe对应的前端的name属性
    http.rememberMe().rememberMeParameter("rememberMe");
    

    在后端中的rememberMeParameter方法的参数要与前端的name一致

  • 相关阅读:
    第一次结对作业
    第一次博客作业
    个人总结
    第三次个人作业
    第二次结对作业
    第一次结对作业
    第一次个人编程作业
    第一次博客作业
    第三次个人作业——用例图设计
    第二次结对作业
  • 原文地址:https://www.cnblogs.com/wang-sky/p/13722845.html
Copyright © 2011-2022 走看看