1 Star 1 Fork 1

严树成/Markdown 学习笔记

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Spring Security.md 6.18 KB
一键复制 编辑 原始数据 按行查看 历史
RaceK 提交于 5年前 . 添加本地文件

Spring Security

  • 我们在基础的环境上加一些东西的时候,利用的是一个Aop的思想,横切进去的,只要做一个配置类就好了,写好配置类过后就会自动的配置进去
  • 需要记住一下三个类
    • WebSecurityConfigurerAdapter: 自定义Security策略
    • AuthenticationManagerBuilder:自定义认证策略
    • @EnableWebSecurity:开启WebSecurity模式
  • Spring Security 的两个主要目标是 ==认证== 和 ==授权==(访问控制)

环境准备

导入依赖

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

关闭模板引擎缓存

  • 以便随时调试
spring.thymeleaf.cache=false

配置Controller 此处省略

创建Config类 -- 包含了所有操作

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

/**
 * @author Hey
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 授权函数
     * @param http http请求
     * @throws Exception 异常
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人都可以访问,应该是功能也才分权限进入
        //拥有权限才能进入某些页面
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/employee/**").hasRole("employee")
                .antMatchers("/manager/**").hasRole("manager")
                .antMatchers("/customer/**").hasRole("customer");
        /*
        没有权限默认会到登录页面,需要开启登录的页面
          url /login 默认是这个页面,但是可以通过定制指定用自己的页面
          loginPage 指定页面跳转的路径
          loginProcessingUrl  登录处理链接
          如果使用了loginProcessingUrl,前端调用的时候直接调用这个链接即可,通过这个 登录处理链接 去到loginPage
          如果不使用,前端跳转时直接跳转到loginPage即可,可达到一样的效果
          usernameParameter 和 passwordParameter 表示前端页面的组件的name属性中的值,要互相对应才能实现登录操作
         */
        http.formLogin().loginPage("/toLogin")
                .usernameParameter("user")
                .passwordParameter("pwd")
                .loginProcessingUrl("/login");
        //注销功能,开启了注销功能过后,注销了就能直接跳到首页
        http.logout().logoutSuccessUrl("/");
        //防止网站攻击 现在的登录和登出都是get方法  但是要变成post才能安全
        //springboot 默认是开启的,现在要关闭 防止跨站请求伪造
        http.csrf().disable(); //关闭csrf功能 登陆失败存在的原因
        //开启记住我功能 前端的加上remember属性即可 例如 :<input type="checkbox" name="remember"> 记住我 本质上其实就是一个cookie
        http.rememberMe().rememberMeParameter("remember");
        /*
        前端可以通过sec前缀实现获取登录名和登陆角色等数据
        需要先导入thymeleaf和security的整合包
        例 前端调用 <span sec:authentication="name"></span> 获取用户名
        也可以通过sec前缀来识别是否已经登录或分辨角色 以此来实现给登录后才显示内容 以及 给哪些用户显示哪些内容
        例 <div sec:authorize="hasRole('customer')">customer角色才能看到的内容</div>
        例 <div sec:authorize="isAuthenticated">登录了过后显示的内容</div>
         */
    }

    /**
     * 认证,springboot 2.1.x 可以直接使用
     * 密码编码: passwordEncoder
     * spring security 5.0+ 增加了许多新的加密方法
     * @param auth 参数
     * @throws Exception 异常
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这些正常应该从数据库中读 inMemoryAuthentication即在内存中进行认证 jdbcAuthentication即在数据库中认证
        //withUser即 要添加角色的用户
        //需要设置密码的编码模式,spring security不允许密码直接在代码中出现,因此这里使用推荐的加密方式来加密密码 不加密会报错
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("customer").password(new BCryptPasswordEncoder().encode("123456")).roles("customer")
                .and()
                .withUser("manager").password(new BCryptPasswordEncoder().encode("123456")).roles("manager")
                .and()
                .withUser("employee").password(new BCryptPasswordEncoder().encode("123456")).roles("employee");
    }
}

页面根据权限显示内容

  • 导入 依赖
<!-- thymeleaf 和 security 整合包-->
<dependency>
   <groupId>org.thymeleaf.extras</groupId>
   <artifactId>thymeleaf-extras-springsecurity5</artifactId>
   <version>3.0.4.RELEASE</version>
</dependency>
  • 引入命名空间

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

  • 前端使用
<div sec:authorize="isAuthenticated()">
    已经登陆
</div>
<div sec:authorize="!isAuthenticated()">
    未登陆
    <p>
        用户名:<span sec:authentication="name"></span>
        角色:<span sec:authentication="principal.getAuthorities()"></span>
    </p>
</div>
<!-- 菜单根据用户的角色动态的实现 -->
<div sec:authorize="hasRole('vip1')">
    有vip1这个角色就能看见这里
</div>
<div sec:authorize="hasRole('vip2')">
    有vip2这个角色就能看见这里
</div>
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/sacharn/markdown_learning_notes.git
git@gitee.com:sacharn/markdown_learning_notes.git
sacharn
markdown_learning_notes
Markdown 学习笔记
master

搜索帮助