Spring Boot + Security + Mybatis 简单权限控制(入门 + 记录篇)

本文介绍了使用SpringBoot结合SpringSecurity实现权限管理的过程。包括配置文件的编写、登录验证及权限控制的具体实现。并分享了一些实用的博客资源和作者的demo项目。

Spring Boot Security 权限

这两天研究了一下权限管理框架。。
查阅资料的过程中,JAVA中常用的安全框架有Shiro和Spring Security。Shiro比Spring Security学习起来更加简单,功能够用。而这两天的学习中,就我自己的体会而言,学习Spring Security还是有一定难度的。虽然它的扩展性非常的好,我们可以重载它默认的类,重写方法,达到我们要的结果。
本来这篇文章是准备记录一下搭建一个权限系统的完整过程的,但因为能力有限,对security了解还不是很透彻,这里就只贴出我查阅资料过程中,觉得写得好的一些博客,和一些自己的观点和看法。也方便日后自己查阅。


安全框架Shiro和Spring Security比较

点我


权限 + 认证框架组合

Spring Boot + Spring Security + JWT
Spring Boot + Spring Security + Oauth2


好的博客教程

基于springboot的security机制(自定义登录页面+基于内存身份认证+基于mybatis身份认证)

spring security的原理及教程

Spring Boot中使用 Spring Security 构建权限系统

写得很好,就是文章风格太乱

Mybatis的注解应用之关系映射

用户权限管理spring security

最后还是贴上我自己的demo

Git地址:https://github.com/xiangjiangcheng/spring-boot-demo1.git

目录截图:
这里写图片描述

demo中只是简单实现了用户登录才能访问对应资源 + 简单的权限控制,并没有结合数据库实现权限管理。大致的流程如下图所示:
这里写图片描述

这里说的简单权限控制指的是:
当你访问一个controller的时候,会被拦截,提示登录。登录成功后,判断该用户是否有权访问该controller。
实现方式是在配置文件手动配置,这种方式很不灵活。网上说在方法上面加注解,来控制权限,亦是如此。维护起来很麻烦。
具体代码查看demo中BrowerSecurityConfig.java 配置文件

/**
  * 重写该方法,设定用户访问权限
  * 用户身份可以访问 订单相关API
  * */
  @Override
  protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests()
              .antMatchers("/orders/**").hasAnyRole("USER", "ADMIN")    //用户权限,管理员权限
              .antMatchers("/user/**").hasRole("ADMIN")    //管理员权限
              .anyRequest().authenticated() //任何请求,登录后可以访问
              .and()
              .formLogin()
              .loginPage("/login")    //跳转登录页面的控制器,该地址要保证和表单提交的地址一致!
              .successHandler(new AuthenticationSuccessHandler() {
                  // 通过SecurityContextHolder获取目前登录的用户信息,然后将其放到session中(不建议如此处理)然后将页面重定向到首页中。
                  @Override
                  public void onAuthenticationSuccess(HttpServletRequest arg0, HttpServletResponse arg1, Authentication arg2)
                          throws IOException, ServletException {
                      Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                      if (principal != null && principal instanceof UserDetails) {
                          UserDetails user = (UserDetails) principal;
                          System.out.println("loginUser:"+user.getUsername());
                          //维护在session中
                          arg0.getSession().setAttribute("userDetail", user);
                          arg1.sendRedirect("/home");
                      }
                  }
              })
              //失败处理
              .failureHandler(new AuthenticationFailureHandler() {

                  @Override
                  public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException)
                          throws IOException, ServletException {
                      System.out.println("error:"+authenticationException.getMessage());
                      response.sendRedirect("/login");
                  }
              })
              .permitAll()
              .and()
              .logout()
              .permitAll()  //注销行为任意访问
              .and()
              .csrf().disable();        //暂时禁用CSRF,否则无法提交表单
  }
实现Restful接口 不拦截

BrowerSecurityConfig.java 配置文件对应地方加入如下代码

 // 对于获取token的rest api要允许匿名访问
 .antMatchers("/auth/**").permitAll()
 .antMatchers("/druid/**").permitAll()
 .antMatchers(HttpMethod.GET, "/entries/**", "/articles/**").permitAll()
 // 除上面外的所有请求全部需要鉴权认证
 .anyRequest().authenticated();
注意

1.配置文件里面配置了每个controller对应的权限时,如

.antMatchers("/orders/**").hasAnyRole("USER", "ADMIN")    //用户权限
.antMatchers("/user/**").hasRole("ADMIN")    //管理员权限

那么数据库里面,对应的值必须是ROLE_USERROLE_ADMIN
这里写图片描述
2.开发过程中,可以开启secutity的debug模式,代码如下

// 使用debug模式
@EnableWebSecurity(debug = true)
// @EnableWebSecurity

这样,就能看到每次请求的详细信息,以及都经过哪些拦截器拦截!
这里写图片描述

小结

在我看来,web开发过程中,只要涉及到用户登录,再有权限分配这些功能,那么一套完整的权限管理系统已经是必不可少的了。

以往传统的权限系统,都是自己写一些拦截器,简单的实现了权限管理。说简单一点就是,写一个全局的拦截器,请求来之后,判断session中是否存在该用户,若session中没有该用户信息,则该资源不让访问,跳转到登录页面!

如果是使用权限框架,最重要的还是阅读文档和实践。只有了解了它的一些基础的原理,才能举一反三。

可以使用打断点的模式,了解框架到底是怎么在工作的,这能更快的了解他的工作流程。

很多关于Security的博客都写得不是很清楚。所谓的不清楚,也就是当我把一篇博客看完了后,我竟然没有一点思绪,还是不晓得从哪里入手。。。估计是我个人能力问题。

后面有时间再慢慢研究下使用框架实现权限和认证~~

### 集成Spring SecurityMyBatisSpring Boot #### 1. 添加依赖项 为了在Spring Boot应用中集成Spring Security以及MyBatis,需先调整项目的`pom.xml`文件以加入必要的依赖库。这包括但不限于: - `spring-boot-starter-security`: 提供了Spring Security的核心功能。 - `mybatis-spring-boot-starter`: 实现了MyBatisSpring Boot之间的无缝对接。 ```xml <dependencies> <!-- Spring Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- MyBatis Starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> ... </dependencies> ``` 此部分操作确保了所需工具包被正确加载到项目环境中[^4]。 #### 2. 启用并配置Spring Security 通过创建一个继承自`WebSecurityConfigurerAdapter`的类,并重写其方法来自定义安全策略。此外,还可以利用`@EnableWebSecurity`注解来激活Spring Security的功能。 ```java import org.springframework.context.annotation.Configuration; 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; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") // 只允许具有管理员权限的人访问/admin路径下的资源 .anyRequest().authenticated() // 所有其他请求都需要经过身份验证 .and() .formLogin(); // 使用表单登录方式 } } ``` 上述代码片段展示了如何设置基本的身份验证机制及角色级别的访问控制规则[^1]。 #### 3. 数据源配置与实体映射 接下来,在`application.yml`或`.properties`文件内指定数据库连接参数;与此同时,借助MyBatis提供的接口编程模型——即Mapper接口模式——完成持久层的设计工作。 ```yaml # application.yml spring: datasource: url: jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC username: root password: secret driver-class-name: com.mysql.cj.jdbc.Driver mybatis: mapper-locations: classpath:mapper/*.xml ``` 对于具体的业务逻辑处理,则可通过编写相应的DAO(Data Access Object)接口及其对应的XML映射文档来进行描述。例如,针对之前提到过的`auth`表格结构,可以设计如下所示的服务端点[^5]。 ```java // Auth.java - Entity Class @Table(name="auth") @Data @NoArgsConstructor @AllArgsConstructor public class Auth implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer ids; private String username; private String password; private String aut; // Role information } // IAuthDao.java - Mapper Interface @Repository public interface IAuthDao { List<Auth> findAll(); Optional<Auth> findByUsername(String username); int save(Auth auth); boolean existsByUsername(String username); } ``` 以上步骤共同构成了一个完整的解决方案框架,使得开发者能够在Spring Boot环境下便捷地运用Spring Security保障系统的安全性的同时,也能够高效管理数据存储与检索任务[^3]。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值