Spring-Security

目录

认证模式

实现Basic认证

from 表单模式

配置权限策略

如何修改403权限不足页面

如何修改fromlog页面 

动态权限控制

Rbac权限表设计

认证模式

实现Basic认证

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

maven依赖:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.1.RELEASE</version>
</parent>
<dependencies>
    <!--  springboot 整合web组件-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
</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();
    }

当添加上面配置使用时访问接口报错

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

from 表单模式

如何实现:

From 表单模式 适合于传统模式项目 前端和后端都是我们java开发人员自己实现,Vue+SpringBoot
 protected void configure(HttpSecurity http) throws Exception {
    /**
     * 拦截 http 安全认证模式 设置为httpBasic模式
     */
    //http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();
    http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().formLogin();
}

配置权限策略

在企业管理系统平台中,会拆分成n多个不同的账号,每个账号对应不同的接口访问权限,
比如 
账号peiyu 所有接口都可以访问;
peiyu_userName账户 只能访问/userName接口;
peiyu_userId账户 只能访问/userId接口;

 主要修改配置类

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    /**
     * 新增一个账户peiyu 密码也是为peiyu 可以允许访问所有的请求
     */
    //auth.inMemoryAuthentication().withUser("peiyu").password("peiyu").authorities("/");
    /**
     * 使用权限进行访问
     */
    auth.inMemoryAuthentication().withUser("peiyu").password("peiyu").authorities("userName","userId");
    auth.inMemoryAuthentication().withUser("peiyu_name").password("peiyu_name").authorities("userName");
    auth.inMemoryAuthentication().withUser("peiyu_id").password("peiyu_id").authorities("userId");
}

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

    /**
     * 将接口 /userName 的权限名称定义为 userName
     * 将接口 /userId 的权限名称定义为 userId
     */
    http.authorizeRequests().antMatchers("/user/userName").hasAnyAuthority("userName")
            .antMatchers("/user/userId").hasAnyAuthority("userId")
            .antMatchers("/**").fullyAuthenticated().and().formLogin();
}

如何修改403权限不足页面

创建一个配置类

package com.tit.springsecurity.config;

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;

/**
 * @author peiyu
 * @version 1.0
 */
@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;
    }
}

再创建一个 Controller  进行统一的错误返回 

package com.tit.springsecurity.config;

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

/**
 * 统一的错误返回页面
 * @author peiyu
 * @version 1.0
 */
@RestController
public class ErrorController {
    @RequestMapping("/error/403")   //只返403错误
    public String error() {
        return "您当前访问的接口权限不足!";
    }
}

如何修改fromlog页面 

先添加依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>


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

替换的页面: login.ftl

 配置类修改  

动态权限控制

Rbac权限表设计

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

实现:

1.创建数据库

2.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>

3.配置文件

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 

4.mapper接口

 查询权限表以及查询角色所对权限 

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

使用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;
    }
}

6.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() {
         //对密码进行MD5加密
            @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();
    }
}

7.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"));

   }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值