SpringBoot 2.x - SpringSecurity(内存管理版)

Spring中使用的主要有两个安全框架——Shiro与SpringSecurity,本次学习的是SpringSecurity。
首先还是查看官方文档来学习。我们使用的WEB模版是Thymeleaf。

两个概念:

  • 认证(Authentication):建立声明主体的过程。一般也就是指用户登录,表示让系统知道你的存在
  • 授权(Authorization):确定一个主体是否允许在你的应用程序里执行一个运动的过程,也就是赋予你用户能干什么。

1.引入Maven

由于我们本次采用的是Thymeleaf+SpringSecurity。所以我们需要引入thymeleaf-extras-springsecurity,相关使用方法可以查看Github

 <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>

2.配置类

本次采用是在内存中记录用户,大多数要点已经写在注释中,但是有一点值得注意的是,从Spring Security 5.0开始必须要设置加密方式,SpringSecurity提供了以下加密方式。当然最重要的一点,在配置类中不要忘记添加@EnableWebSecurity来开启Security功能。

Security提供的加密方式

/**
 * @author BaoZhou
 * @date 2018/6/21
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        /*匹配所有路径的*/
        http.authorizeRequests().antMatchers("/").permitAll()
                /*level1路径下需要VIP1身份才能访问*/
                .antMatchers("/level1/**").hasRole("VIP1")
                /*level1路径下需要VIP2身份才能访问*/
                .antMatchers("/level2/**").hasRole("VIP2")
                /*level1路径下需要VIP3身份才能访问*/
                .antMatchers("/level3/**").hasRole("VIP3")
                .and()
                /*
                1.formLogin系统会自动配置/login页面用于登录
                2.假如登录失败会重定向到login/error/
                 */
                .formLogin()
                /*
                定制自己的登录界面
                默认username字段提交用户名,可以通过usernameParameter自定义
                默认password字段提交密码,可以用过passwordParameter自定义
                定制了登录页面后
                登录页面地址的POST请求就是登录请求,可以用过loginProcessingUrl自定义
                */
                .loginPage("/userlogin")
                .and()
                /*开启注销功能,访问/logout并清空session*/
                .logout()
                /*注销成功去首页*/
                .logoutSuccessUrl("/")
                .and()
                .exceptionHandling()
                /*设置403错误跳转页面*/
                .accessDeniedHandler(new CustomAccessDeniedHandler())
                .and()
                /*开启记住我功能,登录会添加Cookie,点击注销会删除Cookie*/
                .rememberMe()
                /*设置记住我参数*/
                .rememberMeParameter("remember");
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth
                /*从内存中读取认证*/
                .inMemoryAuthentication()
                /*Spring Security 5.0开始必须要设置加密方式*/
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("user1").password(new BCryptPasswordEncoder().encode("123")).roles("VIP1")
                .and()
                .withUser("user2").password(new BCryptPasswordEncoder().encode("123")).roles("VIP2")
                .and()
                .withUser("user3").password(new BCryptPasswordEncoder().encode("123")).roles("VIP3");
    }
}

3.Web页

主要就是利用sec提供的方法。

  • sec:authorize="isAuthenticated()":是否授权成功
  • sec:authentication="principal.authorities":获取用户身份
  • sec:authentication="name":获取用户名字
  • sec:authorize="hasRole()":判断当前身份

数据页面

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

<head>
    <meta charset="UTF-8">
    <title>登录界面</title>
</head>
<body>
<div sec:authorize="isAuthenticated()">
    <h2 align="center"><span sec:authentication="name"></span>,你好,你是
        <span sec:authentication="principal.authorities"></span></h2>
</div>
<div sec:authorize="!isAuthenticated()">
    <h2 align="center">游客你好<a th:href="@{/userlogin}">请登录</a></h2>
</div>

<div sec:authorize="isAuthenticated()">
    <form th:action="@{/logout}" method="post">
        <input type="submit" value="注销"></form>
</div>


<h3 sec:authorize="isAuthenticated()">VIP专区</h3>
<ul>
    <li sec:authorize="hasRole('VIP1')"><a th:href="@{/level1/1}">VIP1专区</a></li>
    <li sec:authorize="hasRole('VIP2')"><a th:href="@{/level2/2}">VIP2专区</a></li>
    <li sec:authorize="hasRole('VIP3')"><a th:href="@{/level3/3}">VIP3专区</a></li>
</ul>
</body>
</html>

自定义登录界面UserLogin

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
</head>
<body>
<h1 align="center">用户安全登录系统</h1>

<hr>
<div align="center">
    <form th:action="@{/userlogin}" method="post">
        用户名:<input name="username"/><br>
        密码:<input name="password"/><br>
        <input type="checkbox" name="remember">记住我<br/>
        <input type="submit" value="登录">
    </form>
</div>
</body>
</html>

4.Demo GitHub地址

https://github.com/BzCoder/security

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,746评论 19 139
  • jwt简介JWT是一种用于双方之间传递安全信息的简洁的、URL安全的表述性声明规范。JWT作为一个开放的标准( R...
    灰气球阅读 2,771评论 0 21
  • 对于权限的设计可以分为菜单权限和数据权限两个部分菜单权限 关于这个表,我说如下几点: 1.hr表是用户表,存放了用...
    freezml阅读 6,918评论 1 5
  • =========================================================...
    _灯火阑珊处阅读 2,546评论 0 3
  • 文/白衣良人 我不喜欢人潮拥挤 我怕找不到你的身影 我不喜欢太喧闹 我怕听不到你的声音 我不喜欢太艳丽 我怕找不到...
    白衣良人阅读 286评论 0 0

友情链接更多精彩内容