SpringSecurity

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

摘自百度百科:

https://baike.baidu.com/item/spring%20security/8831652?fr=aladdin

image.png

认证模式

1)实现Basic认证

Basic认证是一种较为简单的HTTP认证方式,客户端通过明文(Base64编码格式)传输用户名和密码到服务端进行认证,通常需要配合HTTPS来保证信息传输的安全。

Maven依赖

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.2.1.RELEASE</version>
  5. </parent>
  6. <dependencies>
  7. <!-- springboot 整合web组件-->
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-web</artifactId>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-security</artifactId>
  15. </dependency>
  16. </dependencies>

配置类

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 新增授权账户
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 新增一个账户mayikt 密码也是为mayikt 可以允许访问所有的请求
         */
        auth.inMemoryAuthentication().withUser("mayikt").password("mayikt").authorities("/");
    }

    /**
     * 新增 HttpSecurity配置
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * 拦截 http 安全认证模式 设置为httpBasic模式
         */
        http.authorizeRequests().antMatchers("/**").fullyAuthenticated()
                .and().httpBasic();
    }
    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }
}

访问接口报错

http://127.0.0.1:8080/addMember

image.png

There is no PasswordEncoder mapped for the id “null” 原因:升级为Security5.0以上密码支持多中加密方式,恢复以前模式

/**
 * There is no PasswordEncoder mapped for the id "null"
 * 原因:升级为Security5.0以上密码支持多中加密方式,恢复以前模式
 * @return
 */
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
    return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}

2)from 表单模式

From 表单模式 适合于传统模式项目 前端和后端都是我们java开发人员自己实现,Vue+SpringBoot

protected void configure(HttpSecurity http) throws Exception {
//        /**
//         * 拦截 http 安全认证模式 设置为httpBasic模式
//         */
//        http.authorizeRequests().antMatchers("/**").fullyAuthenticated()
//                .and().httpBasic();
        /**
         * 拦截 http 安全认证模式 设置为formLogin模式
         */
        http.authorizeRequests().antMatchers("/**").fullyAuthenticated()
                .and().formLogin();
    }

image.png

image.png

默认使用cookie存放内容。

3)配置权限策略

在企业管理系统平台中,会拆分成n多个不同的账号,每个账号对应不同的接口访问权限,

比如:

账号mayikt_admin 所有接口都可以访问; mayikt_add账户 只能访问/addMember接口; mayikt_show账户 只能访问/showMember接口; mayikt_del账户 只能访问/delMember接口;

相关config配置

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 新增授权账户
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 新增一个账户mayikt 密码也是为mayikt 可以允许访问所有的请求
         */
//        auth.inMemoryAuthentication().withUser("mayikt").password("mayikt").authorities("mayikt");
        /**
         * 1.新增mayikt_admin mayikt_admin 权限可以访问所有请求
         */
        auth.inMemoryAuthentication().withUser("mayikt_admin").password("mayikt_admin").authorities("addMember", "delMember"
                , "updateMember", "showMember");
        auth.inMemoryAuthentication().withUser("mayikt_admin").password("mayikt_admin").authorities("addMember"
                , "delMember", "updateMember", "showMember");
        auth.inMemoryAuthentication().withUser("mayikt_add").password("mayikt_add").authorities("addMember");
        auth.inMemoryAuthentication().withUser("mayikt_del").password("mayikt_del").authorities("delMember");
        auth.inMemoryAuthentication().withUser("mayikt_update").password("mayikt_update").authorities("updateMember");
        auth.inMemoryAuthentication().withUser("mayikt_show").password("mayikt_show").authorities("showMember");
    }

    /**
     * 新增 HttpSecurity配置
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        /**
//         * 拦截 http 安全认证模式 设置为httpBasic模式
//         */
//        http.authorizeRequests().antMatchers("/**").fullyAuthenticated()
//                .and().httpBasic();
        /**
         * 拦截 http 安全认证模式 设置为formLogin模式
         */
//        http.authorizeRequests().antMatchers("/**").fullyAuthenticated()
//                .and().formLogin();

        http.authorizeRequests().antMatchers("/addMember").hasAnyAuthority("addMember")
                .antMatchers("/delMember").hasAnyAuthority("delMember")
                .antMatchers("/updateMember").hasAnyAuthority("updateMember")
                .antMatchers("/showMember").hasAnyAuthority("showMember").
                antMatchers("/**").fullyAuthenticated()
                .and().formLogin();


    }

    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }
}

image.png

http://127.0.0.1:8080/updateMember

如何修改403权限不足页面

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

/**
 * 自定义SpringBoot 错误异常
 */
@Configuration
public class WebServerAutoConfiguration {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400");
        ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401");
        ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error/403");
        ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
        ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "/error/415");
        ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
        factory.addErrorPages(errorPage400, errorPage401, errorPage403, errorPage404, errorPage415, errorPage500);
        return factory;
    }
}

当出现权限不足的时候就会触发这个接口

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName ErrorController
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
@RestController
public class ErrorController {
    @RequestMapping("/error/403")
    public String error() {
        return "您当前访问的接口权限不足!";
    }
}

如何修改登录页面

package com.mayikt.config;

import org.springframework.context.annotation.Bean;
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;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author 余胜军
 * @ClassName SecurityConfig
 * @qq 644064779
 * @addres www.mayikt.com
 * 微信:yushengjun644
 */
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 新增授权账户
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 新增一个账户mayikt 密码也是为mayikt 可以允许访问所有的请求
         */
//        auth.inMemoryAuthentication().withUser("mayikt").password("mayikt").authorities("mayikt");
        /**
         * 1.新增mayikt_admin mayikt_admin 权限可以访问所有请求
         */
        auth.inMemoryAuthentication().withUser("mayikt_admin").password("mayikt_admin").authorities("addMember", "delMember"
                , "updateMember", "showMember");
        auth.inMemoryAuthentication().withUser("mayikt_admin").password("mayikt_admin").authorities("addMember"
                , "delMember", "updateMember", "showMember");
        auth.inMemoryAuthentication().withUser("mayikt_add").password("mayikt_add").authorities("addMember");
        auth.inMemoryAuthentication().withUser("mayikt_del").password("mayikt_del").authorities("delMember");
        auth.inMemoryAuthentication().withUser("mayikt_update").password("mayikt_update").authorities("updateMember");
        auth.inMemoryAuthentication().withUser("mayikt_show").password("mayikt_show").authorities("showMember");
    }

    /**
     * 新增 HttpSecurity配置
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        /**
//         * 拦截 http 安全认证模式 设置为httpBasic模式
//         */
//        http.authorizeRequests().antMatchers("/**").fullyAuthenticated()
//                .and().httpBasic();
        /**
         * 拦截 http 安全认证模式 设置为formLogin模式
         */
//        http.authorizeRequests().antMatchers("/**").fullyAuthenticated()
//                .and().formLogin();

        http.authorizeRequests().antMatchers("/addMember").hasAnyAuthority("addMember")
                .antMatchers("/delMember").hasAnyAuthority("delMember")
                .antMatchers("/updateMember").hasAnyAuthority("updateMember")
                .antMatchers("/showMember").hasAnyAuthority("showMember")
//                antMatchers("/**").fullyAuthenticated()
//                .and().formLogin();
                //并且关闭csrf 设置跳转到自定义login页面  放开权限
                .antMatchers("/login").permitAll()
                // 设置自定义登录页面
                .antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").and().csrf().disable();


    }

    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }
}

登陆页面

@Controller
public class LoginController {
    @RequestMapping("/login")
    public String login() {
        return "login";
    }
}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
</head>
<body>

<h1>每特教育--权限控制登陆系统</h1>
<form action="/login" method="post">
    <span>用户名称</span><input type="text" name="username"/> <br>
    <span>用户密码</span><input type="password" name="password"/> <br>
    <input type="submit" value="登陆">

</form>

<#if RequestParameters['error']??>
    用户名称或者密码错误
</#if>


</body>
</html>

application.yml

spring:
  freemarker:
    settings:
      classic_compatible: true #处理空值
      datetime_format: yyy-MM-dd HH:mm
      number_format: 0.##
    suffix: .ftl
    template-loader-path:
      - classpath:/templates

Maven依赖

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

4)动态权限控制

RBAC权限表设计

RBAC(基于角色的权限控制)模型的核心是在用户和权限之间引入了角色的概念。取消了用户和权限的直接关联,改为通过用户关联角色、角色关联权限的方法来间接地赋予用户权限(如下图),从而达到用户和权限解耦的目的。

image.png

相关SQL语句

mayikt_rbac.sql

Maven依赖

<!-- springboot 整合mybatis框架 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<!-- alibaba的druid数据库连接池 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.9</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

配置文件

datasource:
  name: test
  url: jdbc:mysql://127.0.0.1:3306/mayikt_rbac
  username: root
  password: root
  # druid 连接池
  type: com.alibaba.druid.pool.DruidDataSource
  driver-class-name: com.mysql.jdbc.Driver

Mapper接口

public interface UserMapper {
    /**
     * 根据用户名称查询
     *
     * @param userName
     * @return
     */
    @Select(" select * from sys_user where username = #{userName}")
    UserEntity findByUsername(@Param("userName") String userName);

    /**
     * 查询用户的权限根据用户查询权限
     *
     * @param userName
     * @return
     */
    @Select(" select permission.* from sys_user user" + " inner join sys_user_role user_role"
            + " on user.id = user_role.user_id inner join "
            + "sys_role_permission role_permission on user_role.role_id = role_permission.role_id "
            + " inner join sys_permission permission on role_permission.perm_id = permission.id where user.username = #{userName};")
    List<PermissionEntity> findPermissionByUsername(@Param("userName") String userName);
}
public interface PermissionMapper {

    @Select(" select * from sys_permission ")
    List<PermissionEntity> findAllPermission();

}

动态根据账户名称查询权限

使用UserDetailsService实现动态查询数据库验证账号

@Component
@Slf4j
public class MemberDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        // 1.根据用户名称查询到user用户
        UserEntity userDetails = userMapper.findByUsername(userName);
        if (userDetails == null) {
            return null;
        }
        // 2.查询该用户对应的权限
        List<PermissionEntity> permissionList = userMapper.findPermissionByUsername(userName);
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        permissionList.forEach((a) -> {
            grantedAuthorities.add(new SimpleGrantedAuthority(a.getPermTag()));
        });
        log.info(">>permissionList:{}<<",permissionList);
        // 设置权限
        userDetails.setAuthorities(grantedAuthorities);
        return userDetails;
    }
}

注意:Users实体类必须实现UserDetails接口

// 用户信息表
@Data
public class UserEntity implements UserDetails {

    private Integer id;
    private String username;
    private String realname;
    private String password;
    private Date createDate;
    private Date lastLoginTime;
    private boolean enabled;
    private boolean accountNonExpired;
    private boolean accountNonLocked;
    private boolean credentialsNonExpired;
    // 用户所有权限
    private List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    public Collection<? extends GrantedAuthority> getAuthorities() {

        return authorities;
    }

}

WebSecurity相关配置

@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MemberDetailsService memberDetailsService;
    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 新增授权账户
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 新增一个账户mayikt 密码也是为mayikt 可以允许访问所有的请求
         */
//        auth.inMemoryAuthentication().withUser("mayikt").password("mayikt").authorities("mayikt");
        /**
         * 1.新增mayikt_admin mayikt_admin 权限可以访问所有请求
         */
//        auth.inMemoryAuthentication().withUser("mayikt_admin").password("mayikt_admin").authorities("addMember"
//                , "delMember", "updateMember", "showMember");
//        auth.inMemoryAuthentication().withUser("mayikt_add").password("mayikt_add").authorities("addMember");
//        auth.inMemoryAuthentication().withUser("mayikt_del").password("mayikt_del").authorities("delMember");
//        auth.inMemoryAuthentication().withUser("mayikt_update").password("mayikt_update").authorities("updateMember");
//        auth.inMemoryAuthentication().withUser("mayikt_show").password("mayikt_show").authorities("showMember");
        auth.userDetailsService(memberDetailsService).passwordEncoder(new PasswordEncoder() {
            @Override
            public String encode(CharSequence rawPassword) {
                return MD5Util.encode((String) rawPassword);
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                String rawPass = MD5Util.encode((String) rawPassword);
                boolean result = rawPass.equals(encodedPassword);
                return result;
            }
        });
    }

    /**
     * 新增 HttpSecurity配置
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        /**
//         * 拦截 http 安全认证模式 设置为httpBasic模式
//         */
//        http.authorizeRequests().antMatchers("/**").fullyAuthenticated()
//                .and().httpBasic();
        /**
         * 拦截 http 安全认证模式 设置为formLogin模式
         */
//        http.authorizeRequests().antMatchers("/**").fullyAuthenticated()
//                .and().formLogin();

//        http.authorizeRequests().antMatchers("/addMember").hasAnyAuthority("addMember")
//                .antMatchers("/delMember").hasAnyAuthority("delMember")
//                .antMatchers("/updateMember").hasAnyAuthority("updateMember")
//                .antMatchers("/showMember").hasAnyAuthority("showMember")
////                antMatchers("/**").fullyAuthenticated()
////                .and().formLogin();
//                //并且关闭csrf 设置跳转到自定义login页面  放开权限
//                .antMatchers("/login").permitAll()
//                // 设置自定义登录页面
//                .antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").and().csrf().disable();

        List<PermissionEntity> allPermission = permissionMapper.findAllPermission();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry
                authorizeRequests = http.authorizeRequests();
        allPermission.forEach((p) -> {
            authorizeRequests.antMatchers(p.getUrl()).hasAnyAuthority(p.getPermTag());
        });
        authorizeRequests.antMatchers("/login").permitAll()
                // 设置自定义登录页面
                .antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").and().csrf().disable();

    }

    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }
}

MD5工具类

public class MD5Util {

   private static final String SALT = "mayikt";

   public static String encode(String password) {
      password = password + SALT;
      MessageDigest md5 = null;
      try {
         md5 = MessageDigest.getInstance("MD5");
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
      char[] charArray = password.toCharArray();
      byte[] byteArray = new byte[charArray.length];

      for (int i = 0; i < charArray.length; i++)
         byteArray[i] = (byte) charArray[i];
      byte[] md5Bytes = md5.digest(byteArray);
      StringBuffer hexValue = new StringBuffer();
      for (int i = 0; i < md5Bytes.length; i++) {
         int val = ((int) md5Bytes[i]) & 0xff;
         if (val < 16) {
            hexValue.append("0");
         }

         hexValue.append(Integer.toHexString(val));
      }
      return hexValue.toString();
   }

   public static void main(String[] args) {
      System.out.println(MD5Util.encode("mayikt"));

   }
}