当前位置 博文首页 > 文章内容

    SpringSecurity

    作者: 栏目:未分类 时间:2020-07-12 9:00:46

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    Spring Security(安全)

    不是功能性需求

    设计之初考虑

    框架:shiro、Spring Security,功能类似

    认证,授权

    • 功能权限
    • 访问权限
    • 菜单权限
    • ...拦截器,过滤器:大量源生代码

    MVC - SPRING - BOOT - 框架思想

    导入thymeleaf依赖

    		<dependency>
    			<groupId>org.thymeleaf</groupId>
    			<artifactId>thymeleaf-spring5</artifactId>
    			<version>3.0.11.RELEASE</version>
    			<scope>compile</scope>
    		</dependency>
    		<dependency>
    			<groupId>org.thymeleaf.extras</groupId>
    			<artifactId>thymeleaf-extras-java8time</artifactId>
    			<version>3.0.4.RELEASE</version>
    			<scope>compile</scope>
    		</dependency>
    

    com.peng.controller.RouterController.java 搭建环境

    package com.peng.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 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;
        }
    }
    

    谁都能看见的界面,明显不合理

    AOP:切面编程

    整合 Spring Security

    记住几个类:

    • WebSecurityConfigurerAdapter: 自定义Security策略
    • AuthenticationManagerBuilder: 自定义认证策略
    • @EnableWebSecurity: 开启WebSecurity模式 ,@Enablexxxx 开启某个功能

    Spring Security的两个主要目标是“认证"和"授权”(访问控制)
    “认证”(Authentication)
    "授权”(Authorization)
    这个概念是通用的,而不是只在Spring Security中存在。

    导入依赖

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

    com.peng.config.SecurityConfig.java 横向添加认证和授权

    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;
    
    //AOP : 拦截器!
    @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 !
            http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login"); //走定制的登录页
    
            //防止网站攻击 get post
            http.csrf().disable(); //关闭csrf功能
    
            //注销,跳回首页
            http.logout().logoutSuccessUrl("/");
    
            //开启记住我功能 cookie 默认保存两周
            http.rememberMe();
        }
    
        //认证
        //密码编码:PasswordEncoder
        //在Spring Security 5.0+ 新增了很多的加密方法
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
            //这些数据正常应该从数据库中读取
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("peng").password(new BCryptPasswordEncoder().encode("123")).roles("vip2","vip3")
                    .and().withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3")
                    .and().withUser("guest").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");
    
            /*数据库中读取
            auth.jdbcAuthentication()
                    .dataSource(datadataSource)
                    .withDefaultSchema()
                    .withUser(users.username("peng").password("123").roles("vip2"))
                    ...........;
                    */
        }
    }
    

    thymeleaf 里控制安全,先导包

    		<!--security-thymeleaf整合包-->
    		<dependency>
    			<groupId>org.thymeleaf.extras</groupId>
    			<artifactId>thymeleaf-extras-springsecurity4</artifactId>
    			<version>3.0.4.RELEASE</version>
    		</dependency>
    

    导入命名空间

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

    动态显示 登陆 和 注销

    <!--登录注销-->
    <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>
    

    动态显示菜单

    <div class="column" sec:authorize="hasRole('vip1')">
        <div ............/></div>
    <div class="column" sec:authorize="hasRole('vip2')">
    	<div ............/></div>
    <div class="column" sec:authorize="hasRole('vip3')">
        <div ............/></div>