点击上方蓝色字体,选择“标☆公众号”
优质文章,第一时间送达
作者 | huisheng_qaq
来源 | http://002ii.cn/lRPkLr
本篇文章给大家带来的是
SpringBoot 整合 SpringSecurity 以及 Mybatis-Plus 详解
Apache Shiro是一个强大且易用的Java安全框架,能够非常清晰的处理身份验证、授权、管理会话以及密码加密。
利用其易于理解的API,可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。
Shiro 主要分为两个部分就是认证和授权,就是查询数据库做相应的判断,Shiro是一个框架,其中的内容需要自己的去构建,前后是自己的,中间是Shiro帮我们去搭建和配置好的。
org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-starter-web com.baomidou mybatis-plus-boot-starter 3.0.5 com.h2database h2 runtime mysql mysql-connector-java org.springframework.boot spring-boot-devtools runtime true org.springframework.boot spring-boot-configuration-processor true org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.springframework.security spring-security-test test
6、application.properties配置文件
#端口号配置server.port=8081#登录时可以使用的账号密码#spring.security.user.name=zhenghuisheng#spring.security.user.password=123456#数据库连接基本参数spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/security?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8spring.datasource.username=rootspring.datasource.password=zhs03171812#日志输出,使用默认的控制台输出mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
package com.zhenghuisheng.demo.pojo;import com.baomidou.mybatisplus.annotation.IdType;import com.baomidou.mybatisplus.annotation.TableId;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import java.io.Serializable;@Data@NoArgsConstructor@AllArgsConstructorpublic class Users implements Serializable { //设置为自增 @TableId(type = IdType.AUTO) private Integer id; private String username; private String password;}
package com.zhenghuisheng.demo.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.zhenghuisheng.demo.pojo.Users;import org.springframework.stereotype.Repository;@Repositorypublic interface UserMapper extends BaseMapper {}
//增加扫描的配置文件@MapperScan("com.zhenghuisheng.demo.mapper")该注解开启之后可以通过注解实现用户的权限登录@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnable = true,prePostEnable = true)
package com.zhenghuisheng.demo;import com.zhenghuisheng.demo.mapper.UserMapper;import com.zhenghuisheng.demo.pojo.Users;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;@SpringBootTestclass DemoApplicationTests { @Autowired private UserMapper usermapper; @Test void contextLoads() { } @Test public void userInsert(){ Users users = new Users(); users.setUsername("admin"); users.setPassword("123456"); usermapper.insert(users); System.out.println(users + "输出成功"); }}
package com.zhenghuisheng.demo.controller;import org.springframework.security.access.annotation.Secured;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/test")public class HelloSecurity { @GetMapping("/login") public String Hello(){ return "hello world"; } @RequestMapping("/index") public String toLogin(){ return "登录成功"; } //使用注解测试用户权限 @GetMapping("/secured") @Secured({"ROLE_admins","ROLE_manager"}) public String secured(){ return "secured login successful"; }}
package com.zhenghuisheng.demo.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;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.WebSecurityConfigurerAdapter;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;import javax.sql.DataSource;@Configurationpublic class SecurityTest extends WebSecurityConfigurerAdapter { @Autowired //UserDetailsService:用于查询数据库名和数据库密码的过程 private UserDetailsService userDetailService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder()); } @Bean PasswordEncoder passwordEncoder(){ //返回一个具体的实现类 return new BCryptPasswordEncoder(); }}
login.html:登录界面
登录界面 姓名: 密码: 自动登录
success.html:登录成功后跳转的页面,并在界面中有一个退出文件,可以在一下的config中设置退出的路径以及退出后跳转的路径,原理和session的删除一致,只不过内部帮我们优化了
Title
登录成功
退出
unauth.html:403没有权限问时的页面,当用户登录成功却没有权限时,即会跳转到该路径
Title
没有权限访问
//自定义用户的操作,如登录页面等 @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() .loginPage("/login.html") //设置登录页面 .loginProcessingUrl("/user/login") //登录访问路径 .defaultSuccessUrl("/success.html").permitAll() //登录成功后的跳转路径 .and().authorizeRequests() .antMatchers("/","/test/login","/user/login").permitAll() //设置哪些路径可以访问,不需要认证 .antMatchers("/test/login").hasAuthority("admins") //授权,只有当用户为admins的时候,才能访问该路径 .anyRequest().authenticated() //所有请求都能访问// .and().rememberMe().tokenRepository(persistentTokenRepository()) //记住我,并设置操作数据库的对象// .tokenValiditySeconds(60) //有效时长// .userDetailsService(userDetailService) .and().csrf().disable(); //关闭crsf防护 //配置没有权限访问跳转的自定义页面 http.exceptionHandling().accessDeniedPage("/unauth.html"); //配置退出 http.logout().logoutUrl("/logout") //退出 .logoutSuccessUrl("/test/login") // 退出成功所返回的路径 .permitAll(); }
.antMatchers("/test/login").hasAuthority("admins") //授权,
只有当用户为admins的时候,才能访问该路径,这就相当于增加了一道令牌token。而在数据库中,每个用户都有每个用户的职位,如经理,管理员,员工等
List list = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admins");
在这个"ROLE_admins"参数即为员工的职责,如果员工的职责与增加令牌token中能通过的角色一直时,则该员工可以访问该路径,否则不行,即实现了授权机制
而如果在使用hasRole方法和hasAnyRole方法时,看上面的图片就知道了,这个源码是有多无聊,自动在角色前面增加了一个 “ROLE_”。当然如果使用hasAnyAuthority方法和hasAuthority方法就不需要了。
这里是因为使用的注解开发了,在controller中使用了@Secured,当然也能使用@PreAuthorize和@PostAuthorize了!
运行后直接输入:http://localhost:8081/login.html
在进行注解测试,看能否测试成功,这里发现也能成功!
最后退出测试,即删除session
http.logout().logoutUrl("/logout") //退出 .logoutSuccessUrl("/test/login") // 退出成功所返回的路径 .permitAll();
点击退出之后
感谢各位阅读 我们的 SpringBoot整合SpringSecurity以及Mybatis-Plus详解 的介绍结束 希望大家有耐心的进行阅读~ 如果觉得我的文章对你还算有提高 可以关注一下我的公众号! 每天都有干货推送~