详解springboot springsecuroty中的注销和权限控制问题

目录
  • 1账户注销
    • 1.1在SecurityConfig中加入开启注销功能的代码
    • 1.2在index.html添加注销的按钮
    • 1.3启动项目测试
  • 2权限控制
    • 2.1导入springsecurity和thymeleaf的整合依赖
    • 2.2springboot版本降级
    • 2.3引入约束
    • 2.4修改页面代码
    • 2.5重启程序测试

上篇文章给大家介绍了springboot对接第三方微信授权及获取用户的头像和昵称等等

1 账户注销

1.1 在SecurityConfig中加入开启注销功能的代码

src/main/java/com/lv/config/SecurityConfig.java

package com.lv.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;
//AOP : 拦截器!
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //授权
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //首页所有人都可以访问,功能页只有对应的有权限的人才能访问
        //请求授权的规则~(链式编程)
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //没有权限默认会跳转到登录页,需要开启登录页面
        http.formLogin();
        //注销,开启了注销功能,跳到首页
        http.logout().logoutSuccessUrl("/");
        //防止跨站工具, get,post
        http.csrf().disable();//关闭csrf功能,注销失败可能的原因
    }
    //认证,springboot 2.1.x 可以直接使用
    //密码编码:PasswordEncoder
    //在Spring Security 5.0+ 新增了很多加密方法~
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这些数据正常应该从数据库中读
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("lv").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}

1.2 在index.html 添加注销的按钮

src/main/resources/templates/index.html

<!--登录注销-->
<div class="right menu">
    <div>
        <a class="item" th:href="@{/toLogin}">
            <i class="address card icon"></i>登录
        </a>
    </div>
    <div>
        <a class="item" th:href="@{/logout}">
            <i class="sign-out icon"></i>注销
        </a>
    </div>
</div>

1.3 启动项目测试

访问登录页面,登录 guest 账户,该账户可以访问 level1的页面

登录成功后,点击 level1的链接,成功跳转到 level 页面,然后点击注销按钮

弹回到首页,再次点击点击 level1 页面

跳转到了登录页面

说明账户注销成功

2 权限控制

2.1 导入springsecurity和thymeleaf的整合依赖

pom.xml

<!-- springSecurity和thymeleaf整合包 -->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>3.0.2.RELEASE</version>
</dependency>

2.2 springboot版本降级

pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.9.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

必须将springboot的版本降到2.0.9以下,否则 sec:authorize="isAuthenticated()" 不会生效.版本降低后,需要手动导入junit依赖,否则测试类会报错

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>RELEASE</version>
    <scope>test</scope>
</dependency>

2.3 引入约束

在index.html的头文件中添加springsecurity和thymeleaf的整合约束

src/main/resources/templates/index.html

<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">

2.4 修改页面代码

主要修改两部分,一部分是登录状态下显示用户名,和注销按钮,未登录显示登录按钮 通过 sec:authorize="isAuthenticated()" 实现.另一部分是根据登录用户的权限显示不同的页面菜单,通过 sec:authorize="hasRole('vip1')" 实现.

src/main/resources/templates/index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<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>
                    </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 by 秦疆</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>

2.5 重启程序测试

未登录页面

登录 lv 用户的页面

登录 geust 用户的页面

登录 root 用户的页面

页面显示都不同,权限控制成功实现

到此这篇关于springboot-springsecuroty 注销和权限控制的文章就介绍到这了,更多相关springboot注销和权限控制内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 解决springboot+shiro+thymeleaf页面级元素的权限控制问题

    目录 springboot+shiro+thymeleaf页面级元素的权限控制 一直报这个异常 下面贴一下关于shiro用到的包 shiro整合thymeleaf常见权限控制标签使用 springboot+shiro+thymeleaf页面级元素的权限控制 我用的springboot2.1版本. 学习了很多大神的总结,基本上都是一样的,shiro权限框架,前端验证是为jsp设计的,其中的tag只能用于jsp系列的模板引擎. 使用了thymeleaf作为前端模板引擎,使用HTML文件,没法引入sh

  • Java Spring Security认证与授权及注销和权限控制篇综合解析

    Spring Security简介: Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,它可以实现强大的Web安全控制,对于安全控制,我们只需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理! 记住几个类: WebSecurityConfigurerAdapter:自定义Security策略 AuthenticationManagerBuilder:自定义认证策略

  • Springboot+Spring Security实现前后端分离登录认证及权限控制的示例代码

    目录 前言 本文主要的功能 一.准备工作 1.统一错误码枚举 2.统一json返回体 3.返回体构造工具 4.pom 5.配置文件 二.数据库表设计 初始化表数据语句 三.Spring Security核心配置:WebSecurityConfig 四.用户登录认证逻辑:UserDetailsService 1.创建自定义UserDetailsService 2.准备service和dao层方法 五.用户密码加密 六.屏蔽Spring Security默认重定向登录页面以实现前后端分离功能 1.实

  • SpringBoot--- SpringSecurity进行注销权限控制的配置方法

    环境 IDEA :2020.1 Maven:3.5.6 SpringBoot: 2.0.9 (与此前整合的版本2.3.3 不同,版本适配问题,为配合使用降级) 1.注销 这里也有一个前提问题需要注意,我们登录操作都是在开启防跨域攻击的环境下进行的. 毫无疑问,注销也是在这样的情况下进行的. 登录时我们提交表单,采用 POST 方法传输,通过使用 Thymeleaf 在 form 表单添加 th:action 元素,Thymeleaf 会自动为我们添加 _csrf 元素. 同样注销操作也是要带有

  • SpringBoot如何整合Springsecurity实现数据库登录及权限控制

    目录 第一步 第二步是封装一个自定义的类 第三步, 我们需要判断密码啦 总结 我们今天使用SpringBoot来整合SpringSecurity,来吧,不多BB 首先呢,是一个SpringBoot 项目,连接数据库,这里我使用的是mybaties.mysql, 下面是数据库的表 DROP TABLE IF EXISTS `xy_role`; CREATE TABLE `xy_role` ( `xyr_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键i

  • 详解springboot springsecuroty中的注销和权限控制问题

    目录 1账户注销 1.1在SecurityConfig中加入开启注销功能的代码 1.2在index.html添加注销的按钮 1.3启动项目测试 2权限控制 2.1导入springsecurity和thymeleaf的整合依赖 2.2springboot版本降级 2.3引入约束 2.4修改页面代码 2.5重启程序测试 承接:springboot-springsecuroty:用户认证和授权 1 账户注销 1.1 在SecurityConfig中加入开启注销功能的代码 src/main/java/c

  • 详解springboot springsecuroty中的注销和权限控制问题

    目录 1账户注销 1.1在SecurityConfig中加入开启注销功能的代码 1.2在index.html添加注销的按钮 1.3启动项目测试 2权限控制 2.1导入springsecurity和thymeleaf的整合依赖 2.2springboot版本降级 2.3引入约束 2.4修改页面代码 2.5重启程序测试 上篇文章给大家介绍了springboot对接第三方微信授权及获取用户的头像和昵称等等 1 账户注销 1.1 在SecurityConfig中加入开启注销功能的代码 src/main/

  • 详解Spring Security 中的四种权限控制方式

    Spring Security 中对于权限控制默认已经提供了很多了,但是,一个优秀的框架必须具备良好的扩展性,恰好,Spring Security 的扩展性就非常棒,我们既可以使用 Spring Security 提供的方式做授权,也可以自定义授权逻辑.一句话,你想怎么玩都可以! 今天松哥来和大家介绍一下 Spring Security 中四种常见的权限控制方式. 表达式控制 URL 路径权限 表达式控制方法权限 使用过滤注解 动态权限 四种方式,我们分别来看.  1.表达式控制 URL 路径权

  • 详解Springboot应用中设置Cookie的SameSite属性

    Cookie除了key和value以外有几个属性. httpOnly 是否允许js读取cookie secure 是否仅仅在https的链接下,才提交cookie domain cookie提交的域 path cookie提交的path maxAge cookie存活时间 sameSite 同站策略,枚举值:Strict Lax None 其他的都很熟悉了,最后一个是 Chrome 51 开始,浏览器的 Cookie 新增加了一个 SameSite 属性,用来防止 CSRF 攻击和用户追踪. 关

  • 详解springboot整合ehcache实现缓存机制

    EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. ehcache提供了多种缓存策略,主要分为内存和磁盘两级,所以无需担心容量问题. spring-boot是一个快速的集成框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. 由于spring-boot无需任何样板化的配置文件,所以spring-boot集成一些其他框架时会有略微的

  • 详解SpringBoot中的参数校验(项目实战)

    Java后端发工作中经常会对前端传递过来的参数做一些校验,在业务中还要抛出异常或者不断的返回异常时的校验信息,充满了if-else这种校验代码,在代码中相当冗长.例如说,用户注册时,会校验手机格式的正确性,用户名的长度等等.虽说前端也可以做参数校验,但是为了保证我们API接口的可靠性,以保证最终数据入库的正确性,后端进行参数校验不可忽视. Hibernate Validator 提供了一种统一方便的方式,让我们快速的实现参数校验. Hibernate Validator 使用注解,实现声明式校验

  • 详解SpringBoot中Controller接收对象列表实现

    如果Spring Boot中对应的Controller要接收一个对象,该对象中又存放了一个List列表,那么页面该如何传递相关应的参数信息呢. 本篇文章给大家一个简单的示例,提供一种实现方式. 实体类 首先看实体类的结构(注意使用了Lombok): @Data public class Rules { private List<Rule> rules; } 对应Rule实体类代码如下: @Data public class Rule { /** * 类名 */ private String c

  • 详解SpringBoot中的tomcat优化和修改

    项目背景 在做项目的时候,把SpringBoot的项目打包成安装包了,在客户上面安装运行,一切都是那么的完美,可是发生了意外,对方突然说导出导入的文件都不行了.我急急忙忙的查看日志,发现报了一个错误 java.io.IOException: The temporary upload location [C:\Windows\Temp\tomcat.1351070438015228346.8884\work\Tomcat\localhost\ROOT] is not valid at org.ap

  • 详解SpringBoot上传图片到阿里云的OSS对象存储中

    启动idea创建一个SpringBoot项目 将上面的步骤完成之后,点击下一步创建项目 创建完成之后修改pom.xml文件,添加阿里云oss依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional&g

  • 详解SpringBoot中添加@ResponseBody注解会发生什么

    SpringBoot版本2.2.4.RELEASE. [1]SpringBoot接收到请求 ① springboot接收到一个请求返回json格式的列表,方法参数为JSONObject 格式,使用了注解@RequestBody 为什么这里要说明返回格式.方法参数.参数注解?因为方法参数与参数注解会影响你使用不同的参数解析器与后置处理器!通常使用WebDataBinder进行参数数据绑定结果也不同. 将要调用的目标方法如下: @ApiOperation(value="分页查询") @Re

随机推荐