• Spring Security快速入门


    Spring Security

    1.Spring Security介绍

    Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoCDI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

    WebSecurityConfigurerAdapter: 自定义Security策略

    AuthenticationManagerBuilder: 自定义认证策略

    @EnableWebSecurity: 开启WebSecurity模式

    “认证”(Authentication

    “授权”(Authorization

    2.创建工程

    2.1 创建SpringBoot工程勾选web,Security

    项目源码:https://gitee.com/ShiQingning/springsecurity-stuty

    pom.xml

    <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--thymeleaf模板-->
            <dependency>
                <groupId>org.thymeleaf</groupId>
                <artifactId>thymeleaf-spring5</artifactId>
            </dependency>
            <dependency>
                <groupId>org.thymeleaf.extras</groupId>
                <artifactId>thymeleaf-extras-java8time</artifactId>
            </dependency>
            <!--Thymeleaf加SpringSecurity整合包:-->
            <dependency>
                <groupId>org.thymeleaf.extras</groupId>
                <artifactId>thymeleaf-extras-springsecurity5</artifactId>
                <version>3.0.4.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    

    application.properties

    #thymeleaf缓存
    spring.thymeleaf.cache=false
    #...其他略
    

    config包下创建SecurityConfig.java ,添加@EnableWebSecurity注解

    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;
    
    /**
     * description: 自定义Security策略
     * AOP 拦截器
     *
     * @author sqn
     * @version 1.0
     */
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        //链式编程
        //http安全策略
        //授权
        @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").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login").defaultSuccessUrl("/index");
    
            //开启注销功能,跳转回登录页
            http.logout().logoutSuccessUrl("/toLogin");
    
            //关闭防止网站攻击
            http.csrf().disable();
    
            //开启记住密码功能
            http.rememberMe().rememberMeParameter("remember");
        }
    
    
        //认证,springboot 2.1.X可以直接使用
        //密码编码:passwordEncoder
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //这些数据正常从数据库中获得
            //下面是从内存中取得
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
                    .and()
                    .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2")
                    .and()
                    .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
            ;
        }
    
    }
    

    在controller包下创建RouterController

    package com.sqn.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
     * description: 路由跳转页面
     */
    @Controller
    public class RouterController {
    
        /**
         * description: 跳转到index页面
         */
        @RequestMapping({"/", "/index"})
        public String index() {
            return "index";
        }
    
        /**
         * description: 跳转到login页面
         */
        @RequestMapping("/toLogin")
        public String toLogin() {
            return "views/login";
        }
    
        /**
         * description: 跳转到level1页面
         */
        @RequestMapping("/level1/{id}")
        public String level1(@PathVariable("id") int id) {
            return "views/level1/" + id;
        }
    
        /**
         * description: 跳转到level2页面
         */
        @RequestMapping("/level2/{id}")
        public String level2(@PathVariable("id") int id) {
            return "views/level2/" + id;
        }
    
        /**
         * description: 跳转到level3页面
         */
        @RequestMapping("/level3/{id}")
        public String level3(@PathVariable("id") int id) {
            return "views/level3/" + id;
        }
    
    }
    

    在页面引入命名空间:

    xmlns:th="http://www.thymeleaf.org" xmlns:sec=http://www.thymeleaf.org/extras/spring-security
    

    index.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec=http://www.thymeleaf.org/extras/spring-security>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <title>首页</title>
        <!--semantic-ui-->
        <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
        <link th:href="@{/qinjiang/css/qinstyle.css}" rel="stylesheet">
    </head>
    <body>
    
    <!--主容器-->
    <div class="ui container">
    
        <div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
            <div class="ui secondary menu">
                <a class="item" th:href="@{/index}">首页</a>
    
                <!--登录注销-->
                <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> ;
                            vip等级:<span sec:authentication="principal.authorities"></span>
                        </a>
                    </div>
                    <div sec:authorize="isAuthenticated()">
                        <a class="item" th:href="@{/logout}">
                            <i class="sign-out icon"></i> 注销
                        </a>
                    </div>
                </div>
            </div>
        </div>
    
        <div class="ui segment" style="text-align: center">
            <h3>Spring Security Study</h3>
        </div>
    
        <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>
    
    </div>
    
    <script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
    <script th:src="@{/qinjiang/js/semantic.min.js}"></script>
    
    </body>
    </html>
    

    最终效果:

  • 相关阅读:
    AC日记——Little Elephant and Numbers codeforces 221b
    AC日记——Little Elephant and Function codeforces 221a
    AC日记——Mice and Holes codeforces 797f
    AC日记——Sliding Window poj 2823
    Poj 2976 Dropping tests(01分数规划 牛顿迭代)
    Bzoj 1968: [Ahoi2005]COMMON 约数研究
    洛谷 P2424 约数和
    Hdu Can you find it?(二分答案)
    SPOJ GSS1
    Bzoj 2243: [SDOI2011]染色(树链剖分+线段树)
  • 原文地址:https://www.cnblogs.com/qingningshi/p/14831261.html
Copyright © 2020-2023  润新知