共计 28267 个字符,预计需要花费 71 分钟才能阅读完成。
SpringBoot + Vue 搭建前后端拆散的博客我的项目零碎
一:简略介绍
性能纲要
博客我的项目零碎的根本增删改查
学习目标
搭建前后端拆散我的项目的骨架
二:Java 后端接口开发
1、前言
- 从零开始搭建一个我的项目骨架,最好抉择适合、相熟的技术,并且在将来易拓展,适宜微服务化体系等。所以个别以 SpringBoot 作为咱们的框架根底。
- 而后数据层,咱们罕用的是 Mybatis,易上手,不便保护。然而单表操作比拟艰难,特地是增加字段或缩小字段的时候,比拟繁琐,所以这里我举荐应用 Mybatis Plus,为简化开发而生,只需简略配置,即可疾速进行 CRUD 操作,从而节俭大量工夫。
- 作为一个我的项目骨架,权限也是咱们不能疏忽的,Shiro 配置简略,应用也简略,所以应用 Shiro 作为咱们的的权限。
- 思考到我的项目可能须要部署多台,这时候咱们的会话等信息须要共享,Redis 是当初支流的缓存中间件,也适宜咱们的我的项目。
- 因为前后端拆散,所以咱们应用 Jwt 作为咱们用户身份凭证。
2、技术栈
- SpringBoot
- Mybatis Plus
- Shiro
- Lombok
- Redis
- Hibernate Validatior
- Jwt
3、新建 SpringBoot 我的项目
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.pony</groupId>
<artifactId>springboot_blog</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_blog</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- 我的项目的热加载重启插件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 化代码的工具 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--mybatis plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!--mybatis plus 代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<!--freemarker-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.yml
# DataSource Config
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot_blog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai
username: root
password: password
mybatis-plus:
mapper-locations: classpath*:/mapper/**Mapper.xml
开启 mapper 接口扫描,增加分页插件
package com.pony.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author malf
* @description 通过 @MapperScan 注解指定要变成实现类的接口所在的包,而后包上面的所有接口在编译之后都会生成相应的实现类。* PaginationInterceptor 是一个分页插件。* @date 2021/5/22
* @project springboot_blog
*/
@Configuration
@EnableTransactionManagement
@MapperScan("com.pony.mapper")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
}
代码生成(间接依据数据库表信息生成 entity、service、mapper 等接口和实现类)
-
创立 Mysql 数据库表
CREATE TABLE `pony_user` (`id` bigint(20) NOT NULL AUTO_INCREMENT, `username` varchar(64) DEFAULT NULL, `avatar` varchar(255) DEFAULT NULL, `email` varchar(64) DEFAULT NULL, `password` varchar(64) DEFAULT NULL, `status` int(5) NOT NULL, `created` datetime DEFAULT NULL, `last_login` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `UK_USERNAME` (`username`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `pony_blog` (`id` bigint(20) NOT NULL AUTO_INCREMENT, `user_id` bigint(20) NOT NULL, `title` varchar(255) NOT NULL, `description` varchar(255) NOT NULL, `content` longtext, `created` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP, `status` tinyint(4) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4; INSERT INTO `springboot_blog`.`pony_user` (`id`, `username`, `avatar`, `email`, `password`, `status`, `created`, `last_login`) VALUES ('1', 'pony', 'https://image-1300566513.cos.ap-guangzhou.myqcloud.com/upload/images/5a9f48118166308daba8b6da7e466aab.jpg', NULL, '96e79218965eb72c92a549dd5a330112', '0', '2021-05-20 10:44:01', NULL);
-
代码生成器:CodeGenerator
package com.pony; import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * @author malf * @description 执行 main 办法,在控制台输出模块表名回车主动生成对应我的项目目录 * @date 2021/5/22 * @project springboot_blog */ public class CodeGenerator { /** * 读取控制台内容 */ public static String scanner(String tip) {Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("请输出" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) {String ipt = scanner.next(); if (StringUtils.isNotEmpty(ipt)) {return ipt;} } throw new MybatisPlusException("请输出正确的" + tip + "!"); } public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("pony"); gc.setOpen(false); // gc.setSwagger2(true); 实体属性 Swagger2 注解 gc.setServiceName("%sService"); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/springboot_blog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("password"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName(null); pc.setParent("com.pony"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() {} }; // 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 velocity // String templatePath = "/templates/mapper.xml.vm"; // 自定义输入配置 List<FileOutConfig> focList = new ArrayList<>(); // 自定义配置会被优先输入 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输入文件名,如果 Entity 设置了前后缀,此处留神 xml 的名称会跟着发生变化 return projectPath + "/src/main/resources/mapper/" + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;} }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); strategy.setInclude(scanner("表名,多个英文逗号宰割").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix("pony_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute();} }
- 执行 main 办法,输出 pony_user, pony_blog 后回车即可,代码目录构造如下:
-
测试以后步骤正确及数据库连贯失常
package com.pony.controller; import com.pony.service.UserService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * <p> * 前端控制器 * </p> * * @author pony * @since 2021-05-22 */ @RestController @RequestMapping("/user") public class UserController { @Resource UserService userService; @GetMapping("/{id}") public Object test(@PathVariable("id") Long id) {return userService.getById(id); } }
-
运行我的项目,拜访地址
http://localhost:8080/user/1
4、对立后果封装
package com.pony.common; import lombok.Data; import java.io.Serializable; /** * @author malf * @description 用于异步对立返回的后果封装。* @date 2021/5/22 * @project springboot_blog */ @Data public class Result implements Serializable { private String code; // 是否胜利 private String message; // 后果音讯 private Object data; // 后果数据 public static Result success(Object data) {Result result = new Result(); result.setCode("0"); result.setData(data); result.setMessage("操作胜利"); return result; } public static Result success(String message, Object data) {Result result = new Result(); result.setCode("0"); result.setData(data); result.setMessage(message); return result; } public static Result fail(String message) {Result result = new Result(); result.setCode("-1"); result.setData(null); result.setMessage(message); return result; } public static Result fail(String message, Object data) {Result result = new Result(); result.setCode("-1"); result.setData(data); result.setMessage(message); return result; } }
5、整合 Shiro + Jwt,并会话共享
思考到前面可能须要做集群、负载平衡等,所以就须要会话共享,而 Shiro 的缓存和会话信息,咱们个别思考应用 Redis 来存储数据,所以,咱们不仅须要整合 Shiro,也须要整合 Redis。
引入 shiro-redis 和 jwt 依赖,为了简化开发,同时引入 hutool 工具包。
<dependency> <groupId>org.crazycake</groupId> <artifactId>shiro-redis-spring-boot-starter</artifactId> <version>3.2.1</version> </dependency> <!-- hutool 工具类 --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.3.3</version> </dependency> <!-- jwt --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency>
编写 Shiro 配置类
-
第一步:生成和校验 jwt 的工具类,其中有些 jwt 相干的密钥信息是从我的项目配置文件中配置的
package com.pony.util; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.Date; /** * @author malf * @description * @date 2021/5/22 * @project springboot_blog */ @Slf4j @Data @Component @ConfigurationProperties(prefix = "pony.jwt") public class JwtUtils { private String secret; private long expire; private String header; /** * 生成 jwt token */ public String generateToken(long userId) {Date nowDate = new Date(); // 过期工夫 Date expireDate = new Date(nowDate.getTime() + expire * 1000); return Jwts.builder() .setHeaderParam("typ", "JWT") .setSubject(userId + "") .setIssuedAt(nowDate) .setExpiration(expireDate) .signWith(SignatureAlgorithm.HS512, secret) .compact();} public Claims getClaimByToken(String token) { try {return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();} catch (Exception e) {log.debug("validate is token error", e); return null; } } /** * token 是否过期 * * @return true:过期 */ public boolean isTokenExpired(Date expiration) {return expiration.before(new Date()); } }
-
第二步:自定义一个 JwtToken,来实现 shiro 的 supports 办法
package com.pony.shiro; import org.apache.shiro.authc.AuthenticationToken; /** * @author malf * @description shiro 默认 supports 的是 UsernamePasswordToken,咱们当初采纳了 jwt 的形式,* 所以这里自定义一个 JwtToken,来实现 shiro 的 supports 办法。* @date 2021/5/22 * @project springboot_blog */ public class JwtToken implements AuthenticationToken { private String token; public JwtToken(String token) {this.token = token;} @Override public Object getPrincipal() {return token;} @Override public Object getCredentials() {return token;} }
-
第三步:登录胜利之后返回的一个用户信息的载体
package com.pony.shiro; import lombok.Data; import java.io.Serializable; /** * @author malf * @description 登录胜利之后返回的一个用户信息的载体 * @date 2021/5/22 * @project springboot_blog */ @Data public class AccountProfile implements Serializable { private Long id; private String username; private String avatar; }
-
第四步:shiro 进行登录或者权限校验的逻辑所在
package com.pony.shiro; import cn.hutool.core.bean.BeanUtil; import com.pony.entity.User; import com.pony.service.UserService; import com.pony.util.JwtUtils; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.stereotype.Component; import javax.annotation.Resource; /** * @author malf * @description shiro 进行登录或者权限校验的逻辑所在 * @date 2021/5/22 * @project springboot_blog */ @Slf4j @Component public class AccountRealm extends AuthorizingRealm { @Resource JwtUtils jwtUtils; @Resource UserService userService; @Override public boolean supports(AuthenticationToken token) {return token instanceof JwtToken;} @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {return null;} @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {JwtToken jwt = (JwtToken) token; log.info("jwt----------------->{}", jwt); String userId = jwtUtils.getClaimByToken((String) jwt.getPrincipal()).getSubject(); User user = userService.getById(Long.parseLong(userId)); if (user == null) {throw new UnknownAccountException("账户不存在!"); } if (user.getStatus() == -1) {throw new LockedAccountException("账户已被锁定!"); } AccountProfile profile = new AccountProfile(); BeanUtil.copyProperties(user, profile); log.info("profile----------------->{}", profile.toString()); return new SimpleAuthenticationInfo(profile, jwt.getCredentials(), getName()); } }
- supports:为了让 realm 反对 jwt 的凭证校验
- doGetAuthorizationInfo:权限校验
- doGetAuthenticationInfo:登录认证校验,通过 jwt 获取到用户信息,判断用户的状态,最初异样就抛出对应的异样信息,否者封装成 SimpleAuthenticationInfo 返回给 shiro。
-
第五步:定义 jwt 的过滤器 JwtFilter
package com.pony.shiro; import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.pony.common.Result; import com.pony.util.JwtUtils; import io.jsonwebtoken.Claims; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.ExpiredCredentialsException; import org.apache.shiro.web.filter.authc.AuthenticatingFilter; import org.apache.shiro.web.util.WebUtils; import org.springframework.web.bind.annotation.RequestMethod; import javax.annotation.Resource; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author malf * @description 定义 jwt 的过滤器 JwtFilter。* @date 2021/5/22 * @project springboot_blog */ @Component public class JwtFilter extends AuthenticatingFilter { @Resource JwtUtils jwtUtils; @Override protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception { // 获取 token HttpServletRequest request = (HttpServletRequest) servletRequest; String jwt = request.getHeader("Authorization"); if (StringUtils.isEmpty(jwt)) {return null;} return new JwtToken(jwt); } @Override protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {HttpServletRequest request = (HttpServletRequest) servletRequest; String token = request.getHeader("Authorization"); if (StringUtils.isEmpty(token)) {return true;} else { // 判断是否已过期 Claims claim = jwtUtils.getClaimByToken(token); if (claim == null || jwtUtils.isTokenExpired(claim.getExpiration())) {throw new ExpiredCredentialsException("token 已生效,请从新登录!"); } } // 执行主动登录 return executeLogin(servletRequest, servletResponse); } @Override protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {HttpServletResponse httpResponse = (HttpServletResponse) response; try { // 解决登录失败的异样 Throwable throwable = e.getCause() == null ? e : e.getCause(); Result r = Result.fail(throwable.getMessage()); String json = JSONUtil.toJsonStr(r); httpResponse.getWriter().print(json); } catch (IOException e1) { } return false; } /** * 对跨域提供反对 */ @Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {HttpServletRequest httpServletRequest = WebUtils.toHttp(request); HttpServletResponse httpServletResponse = WebUtils.toHttp(response); httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin")); httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE"); httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers")); // 跨域时会首先发送一个 OPTIONS 申请,这里咱们给 OPTIONS 申请间接返回失常状态 if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value()); return false; } return super.preHandle(request, response); } }
- createToken:实现登录,咱们须要生成咱们自定义反对的 JwtToken
- onAccessDenied:拦挡校验,当头部没有 Authorization 时候,咱们间接通过,不须要主动登录;当带有的时候,首先咱们校验 jwt 的有效性,没问题咱们就间接执行 executeLogin 办法实现主动登录
- onLoginFailure:登录异样时候进入的办法,咱们间接把异样信息封装而后抛出
- preHandle:拦截器的前置拦挡,因为是前后端剖析我的项目,我的项目中除了须要跨域全局配置之外,在拦截器中也须要提供跨域反对。这样,拦截器才不会在进入 Controller 之前就被限度了
-
第六步:Shiro 配置类
package com.pony.config; import com.pony.shiro.AccountRealm; import com.pony.shiro.JwtFilter; import org.apache.shiro.mgt.DefaultSessionStorageEvaluator; import org.apache.shiro.mgt.DefaultSubjectDAO; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.session.mgt.SessionManager; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition; import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.crazycake.shiro.RedisCacheManager; import org.crazycake.shiro.RedisSessionDAO; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.annotation.Resource; import javax.servlet.Filter; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * @author malf * @description shiro 启用注解拦挡控制器 * @date 2021/5/22 * @project springboot_blog */ @Configuration public class ShiroConfig { @Resource JwtFilter jwtFilter; @Bean public SessionManager sessionManager(RedisSessionDAO redisSessionDAO) {DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); sessionManager.setSessionDAO(redisSessionDAO); return sessionManager; } @Bean public DefaultWebSecurityManager securityManager(AccountRealm accountRealm, SessionManager sessionManager, RedisCacheManager redisCacheManager) {DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(accountRealm); securityManager.setSessionManager(sessionManager); securityManager.setCacheManager(redisCacheManager); /* * 敞开 shiro 自带的 session,详情见文档 */ DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO(); DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator(); defaultSessionStorageEvaluator.setSessionStorageEnabled(false); subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator); securityManager.setSubjectDAO(subjectDAO); return securityManager; } @Bean public ShiroFilterChainDefinition shiroFilterChainDefinition() {DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition(); Map<String, String> filterMap = new LinkedHashMap<>(); filterMap.put("/**", "jwt"); // 次要通过注解形式校验权限 chainDefinition.addPathDefinitions(filterMap); return chainDefinition; } @Bean("shiroFilterFactoryBean") public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager, ShiroFilterChainDefinition shiroFilterChainDefinition) {ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean(); shiroFilter.setSecurityManager(securityManager); Map<String, Filter> filters = new HashMap<>(); filters.put("jwt", jwtFilter); shiroFilter.setFilters(filters); Map<String, String> filterMap = shiroFilterChainDefinition.getFilterChainMap(); shiroFilter.setFilterChainDefinitionMap(filterMap); return shiroFilter; } // 开启注解代理(默认如同曾经开启,能够不要)@Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } @Bean public static DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator(); return creator; } }
- 引入 RedisSessionDAO 和 RedisCacheManager,为了解决 shiro 的权限数据和会话信息能保留到 redis 中,实现会话共享。
- 重写了 SessionManager 和 DefaultWebSecurityManager,同时在 DefaultWebSecurityManager 中为了敞开 shiro 自带的 session 形式,咱们须要设置为 false,这样用户就不再能通过 session 形式登录 shiro。前面将采纳 jwt 凭证登录。
- 在 ShiroFilterChainDefinition 中,咱们不再通过编码模式拦挡 Controller 拜访门路,而是所有的路由都须要通过 JwtFilter 这个过滤器,而后判断申请头中是否含有 jwt 的信息,有就登录,没有就跳过。跳过之后,有 Controller 中的 shiro 注解进行再次拦挡,比方 @RequiresAuthentication,这样管制权限拜访。
-
第七步:配置文件
shiro-redis: enabled: true redis-manager: host: 127.0.0.1:6379 pony: jwt: # 加密秘钥 secret: f4e2e52034348f86b67cde581c0f9eb5 # token 无效时长,7 天,单位秒 expire: 604800 header: token
-
第八步:热部署配置(如果增加了 devtools 依赖)
resources/META-INF/spring-devtools.propertiesrestart.include.shiro-redis=/shiro-[\\w-\\.]+jar
目前为止,shiro 就曾经实现整合进来了,并且应用了 jwt 进行身份校验。
6、异样解决
package com.pony;
import com.pony.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.io.IOException;
/**
* @author malf
* @description 全局异样解决
* @ControllerAdvice 示意定义全局控制器异样解决,@ExceptionHandler 示意针对性异样解决,可对每种异样针对性解决。* @date 2021/5/22
* @project springboot_blog
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
// 捕获 shiro 的异样
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(ShiroException.class)
public Result handle401(ShiroException e) {return Result.fail("401", e.getMessage(), null);
}
/**
* 解决 Assert 的异样
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = IllegalArgumentException.class)
public Result handler(IllegalArgumentException e) throws IOException {log.error("Assert 异样:-------------->{}", e.getMessage());
return Result.fail(e.getMessage());
}
/**
* 校验谬误异样解决
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public Result handler(MethodArgumentNotValidException e) throws IOException {log.error("运行时异样:-------------->", e);
BindingResult bindingResult = e.getBindingResult();
ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
return Result.fail(objectError.getDefaultMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = RuntimeException.class)
public Result handler(RuntimeException e) throws IOException {log.error("运行时异样:-------------->", e);
return Result.fail(e.getMessage());
}
}
- ShiroException:shiro 抛出的异样,比方没有权限,用户登录异样
- IllegalArgumentException:解决 Assert 的异样
- MethodArgumentNotValidException:解决实体校验的异样
-
RuntimeException:捕获其余异样
7、实体校验
1、表单数据提交的时候,前端的校验能够应用一些相似于 jQuery Validate 等 js 插件实现,而后端能够应用 Hibernate validatior 来做校验。
@NotBlank(message = "昵称不能为空") private String username; private String avatar; @NotBlank(message = "邮箱不能为空") @Email(message = "邮箱格局不正确") private String email;
2、@Validated 注解校验实体
/** * 测试实体校验 * @param user * @return */ @PostMapping("/save") public Object testUser(@Validated @RequestBody User user) {return user.toString(); }
8、跨域问题
package com.pony.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author malf * @description 全局跨域解决 * @date 2021/5/22 * @project springboot_blog */ @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**") .allowedOriginPatterns("*") .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") .allowCredentials(true) .maxAge(3600) .allowedHeaders("*"); } }
9、登录接口开发
-
登录账号密码实体
package com.pony.common; import lombok.Data; import javax.validation.constraints.NotBlank; /** * @author malf * @description * @date 2021/5/22 * @project springboot_blog */ @Data public class LoginDto {@NotBlank(message = "昵称不能为空") private String username; @NotBlank(message = "明码不能为空") private String password; }
-
登录退出入口
package com.pony.controller; import cn.hutool.core.lang.Assert; import cn.hutool.core.map.MapUtil; import cn.hutool.crypto.SecureUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.pony.common.LoginDto; import com.pony.common.Result; import com.pony.entity.User; import com.pony.service.UserService; import com.pony.util.JwtUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authz.annotation.RequiresAuthentication; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; /** * @author malf * @description 登录接口 * 承受账号密码,而后把用户的 id 生成 jwt,返回给前段,为了后续的 jwt 的延期,把 jwt 放在 header 上 * @date 2021/5/22 * @project springboot_blog */ public class AccountController { @Resource JwtUtils jwtUtils; @Resource UserService userService; /** * 默认账号密码:pony / 111111 */ @CrossOrigin @PostMapping("/login") public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername())); Assert.notNull(user, "用户不存在"); if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {return Result.fail("明码谬误!"); } String jwt = jwtUtils.generateToken(user.getId()); response.setHeader("Authorization", jwt); response.setHeader("Access-Control-Expose-Headers", "Authorization"); // 用户能够另一个接口 return Result.success(MapUtil.builder() .put("id", user.getId()) .put("username", user.getUsername()) .put("avatar", user.getAvatar()) .put("email", user.getEmail()) .map()); } // 退出 @GetMapping("/logout") @RequiresAuthentication public Result logout() {SecurityUtils.getSubject().logout(); return Result.success(null); } }
登录接口测试
10、博客接口开发
-
ShiroUtils
package com.pony.util; import com.pony.shiro.AccountProfile; import org.apache.shiro.SecurityUtils; /** * @author malf * @description * @date 2021/5/22 * @project springboot_blog */ public class ShiroUtils {public static AccountProfile getProfile() {return (AccountProfile) SecurityUtils.getSubject().getPrincipal(); } }
-
博客操作入口
package com.pony.controller; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.lang.Assert; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.pony.common.Result; import com.pony.entity.Blog; import com.pony.service.BlogService; import com.pony.util.ShiroUtils; import org.apache.shiro.authz.annotation.RequiresAuthentication; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.time.LocalDateTime; /** * <p> * 前端控制器 * </p> * * @author pony * @since 2021-05-22 */ @RestController public class BlogController { @Resource BlogService blogService; @GetMapping("/blogs") public Result blogs(Integer currentPage) {if (currentPage == null || currentPage < 1) currentPage = 1; Page page = new Page(currentPage, 5); IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created")); return Result.success(pageData); } @GetMapping("/blog/{id}") public Result detail(@PathVariable(name = "id") Long id) {Blog blog = blogService.getById(id); Assert.notNull(blog, "该博客已删除!"); return Result.success(blog); } @RequiresAuthentication @PostMapping("/blog/edit") public Result edit(@Validated @RequestBody Blog blog) {System.out.println(blog.toString()); Blog temp = null; if (blog.getId() != null) {temp = blogService.getById(blog.getId()); Assert.isTrue(temp.getUserId() == ShiroUtils.getProfile().getId(), "没有权限编辑"); } else {temp = new Blog(); temp.setUserId(ShiroUtils.getProfile().getId()); temp.setCreated(LocalDateTime.now()); temp.setStatus(0); } BeanUtil.copyProperties(blog, temp, "id", "userId", "created", "status"); blogService.saveOrUpdate(temp); return Result.success("操作胜利", null); } }
-
接口测试
目前为止,后端接口的开发根本实现。源码参考
springboot_blog
正文完