rest-api-spring-boot-starter는 무엇입니까
rest-api-spring-boot-starter는 SpringBoot 웹 API의 신속한 구축에 적합하므로 개발자가 지루할 걱정 없이 통합되고 표준화된 비즈니스 RestFull API를 신속하게 구축할 수 있습니다. 중복 작업이지만 비즈니스에 집중하십시오.
동기 부여
Web API의 공통 기능은 매번 다시 작성해야 합니다. 또는 이전 프로젝트 코드를 복사합니다. 그래서 나는 그런 것을 캡슐화했습니다.stater
SpringBoot Web API 의 각 프로젝트에 대해 다시 작성해야 하는 모듈 및 필요한 기능을 추출합니다 .
그리고 작업에 사용하는 모든 도구 라이브러리를 확장합니다. 개발 효율성을 향상시키는 자유로운 손
권장 버전
- 스프링부트
SpringBoot 2.7.x
새 버전 업데이트
현재 최신 버전 1.6.2는 다음 기능을 지원합니다.
-
RestFull API 균일 형식 반환을 사용자 지정하기 위한 원클릭 구성 지원
-
RestFull API 오류 국제화 지원
-
전역 예외 처리, 전역 매개변수 검증 처리 지원
-
오류를 먼저 반환하는 원칙에 따라 비즈니스 오류 주장 도구의 캡슐화
-
Redis 키, 가치 연산 도구 클래스를 캡슐화합니다. 통합 키 관리 스프링 캐시 캐시 구현
-
RestTemplate은 POST, GET 요청 도구를 캡슐화합니다.
-
로그 통합. 로그 경로를 사용자 지정하고, 로그 수준에 따라 분류하고, 압축 및 파일 크기 세분화를 지원합니다. 시간별 표시
-
도구 라이브러리는 lombok, hutool, commons-lang3 및 guava를 통합합니다. 개별적으로 가져올 필요가 없습니다.
-
통합 mybatisPlus 원클릭 코드 생성
-
로그 기록, 서비스 모니터링, 로그 링크 쿼리 지원. 맞춤 데이터 소스
-
OpenApi3 문서 통합은 원클릭 구성을 지원합니다. 여러 문서 및 자동 구성 지원
-
JWT 표준 토큰 및 권한 인증 생성
-
인터페이스 전류 제한, IP 도시 에코
-
HttpUserAgent 요청 장치 도구 패키지
-
RequestUtil 매개변수 구문 분석 및 캡슐화 도구
웹 JWT 토큰 권한 지원
JWT 웹 토큰
당신은 쉽게 사용자 정의하고 자신을 생성할 수 있습니다 JWT Web Token
.그리고 JWT를 기반으로userJwtToken
이를 통해 userJwtToken
사용자 로그인을 기반으로 인증을 쉽게 생성할 수 있습니다.Token
@Autowired
private UserJwtToken userJwtToken;
@GetMapping("/login")
public Result login() {
UserEntry userEntry = new UserEntry();
userEntry.setUserId("2");
userEntry.setUsername("billy");
userEntry.setHobby("eat");
userJwtToken.rememberMe=true;
String token = userJwtToken.createdToken(userEntry.getUserId(), userEntry.getUsername(), userEntry);
return Result.buildSuccess(token);
}
token
사용자 정보 파싱 및 획득
@GetMapping("/user")
public Result getUser() {
String token = "eyJhbGciOiJIUzI1NiIsInppcCI6IkRFRiJ9.eNqqViouTVKyUkrKzMmpVNJRyiwuBvKMgKyskkwoK7WiQMnK0MzC0tTUwsDEWEeptDi1SMmqGkx7pkBVgTh5ibmpSIZl5CclVQL5qYklSrW1AAAAAP__.8nWRs40LbRTIQBhJ8jVaANPcvsmX0zoLR66R-b2Uc4M";
String userName=userJwtToken.getUserName(token);
String userId= userJwtToken.getUserId(token);
UserEntry userEntry=userJwtToken.parseUserToken(token,UserEntry.class);
return Result.buildSuccess(userId);
}
토큰 비밀 키 및 서명 구성 사용자 지정
jwt:
secret: 123456 # 秘钥 建议加密后秘钥如md5 不要使用明文长度大于6位
expiration: 86400 # token 过期时间(单位秒 1天后过期)
token-header: Token #header token 名称
remember-me-expiration: 604800 #记住我 token过期时间(单位秒 7天后过期)
user-sign: true # 是否自定义签名。为true需要实现加密接口。和 配置 jwtCfg注入对应bean
사용자 정의 서명 인증 및 동적 키 권한 부여는 사용자 정의 서명을 주입하기 위해 UserSign
인터페이스 구성 UserJwtConfig
구성 클래스를 구현해야 합니다.bean
package cn.soboys.superaide.config;
import cn.soboys.restapispringbootstarter.authorization.UserSign;
import io.jsonwebtoken.SignatureAlgorithm;
/**
* @author 公众号 程序员三时
* @version 1.0
* @date 2023/7/16 00:20
* @webSite https://github.com/coder-amiao
*/
public class MyUserSign implements UserSign {
@Override
public SignatureAlgorithm sign() {
return SignatureAlgorithm.HS256;
}
@Override
public String AuthKey() {
return null;
}
}
AuthKey가 반환 되면
null
속성 파일에서 구성한 비밀 키를 사용합니다. 없음은 기본값을 사용합니다.
package cn.soboys.superaide.config;
import cn.soboys.restapispringbootstarter.authorization.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/**
* @author 公众号 程序员三时
* @version 1.0
* @date 2023/7/15 09:49
* @webSite https://github.com/coder-amiao
* 用户jwt token生成配置
*/
@Configuration
public class UserJwtConfig {
@Bean
public UserSign MyUserSign() {
return new MyUserSign();
}
@Bean
public UserJwtToken userJwtToken(UserSign MyUserSign) {
UserJwtToken userJwtToken = new UserJwtToken();
userJwtToken.setUserSign(MyUserSign);
return userJwtToken;
}
}
입증
JWT Web Token
또한 인증 로그인 인증을 캡슐화하는 데 도움이 됩니다 . 속성 파일 구성에서 활성화하기만 하면 됩니다.
jwt:
authorization:
has-authorization: true
includes-url: /user # 需要认证请求 多个用逗号隔开
excludes-url: /login,/register/** # 配置无需认证的
Global은 만료된 예외를 자동으로 처리하도록 도와줍니다 Token
. 그리고 오류 예외는 직접 Token
구성하기 만 하면 됩니다.
{
"success": false,
"code": "401",
"msg": "未授权 ",
"requestId": "9a3ytEtOX0UuojSaA2LD",
"timestamp": "2023-07-17 17:08:05",
"data": null
}
자체 인증 및 권한 부여 논리를 사용자 지정해야 하는 경우 LoginAuthorization
인터페이스를 구현
하고 UserJwtConfig
구성 클래스 에 해당 LoginAuthorization
빈을 주입하기만 하면 됩니다.
좋다:
package cn.soboys.superaide.config;
import cn.soboys.restapispringbootstarter.Assert;
import cn.soboys.restapispringbootstarter.HttpStatus;
import cn.soboys.restapispringbootstarter.authorization.LoginAuthorization;
import cn.soboys.restapispringbootstarter.authorization.UserJwtToken;
import org.dromara.hutool.core.text.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author 公众号 程序员三时
* @version 1.0
* @date 2023/7/16 11:00
* @webSite https://github.com/coder-amiao
*/
@Component
public class MyLoginAuthorization implements LoginAuthorization {
@Autowired
private UserJwtToken userJwtToken;
@Override
public Boolean authorization(HttpServletRequest request, HttpServletResponse response, Object handler) {
String token = request.getHeader("Token");
Assert.isFalse(StrUtil.isEmpty(token),HttpStatus.UNAUTHORIZED);
String userId = userJwtToken.getUserId(token); //验证token有效合法性。
//其他数据库 或者业务操作
return true;
}
}
구성 클래스에 빈 삽입
package cn.soboys.superaide.config;
import cn.soboys.restapispringbootstarter.authorization.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/**
* @author 公众号 程序员三时
* @version 1.0
* @date 2023/7/15 09:49
* @webSite https://github.com/coder-amiao
* 用户jwt token生成配置
*/
@Configuration
public class UserJwtConfig {
@Bean
public UserSign MyUserSign() {
return new MyUserSign();
}
@Bean
@Primary
public LoginAuthorization loginAuthorizationSubject() {
return new MyLoginAuthorization();
}
@Bean
public UserJwtToken userJwtToken(UserSign MyUserSign) {
UserJwtToken userJwtToken = new UserJwtToken();
userJwtToken.setUserSign(MyUserSign);
return userJwtToken;
}
}
3자 기관 인증 프레임워크
JWT 기반 웹 토큰도 쉽게 통합할 수 Shiro
있습니다. Spring Security
기타 제3의 권한 프레임워크
물론 후속 버전에서는 권한 인증을 완전한 경량 권한 프레임워크 프로젝트로 분리할 것입니다. 예: 주석 을
통해 비교적 복잡한 권한 인증 을 쉽게 달성할 수 있습니다.@hasPerm
@hasRole
@hasAnyPerm
@hasAnyRoles
후속 업데이트
일반 업무
우리가 프로젝트 개발에 집중할 때 상대적으로 공개적이고 독립적인 타사 비즈니스 모듈이 항상 있을 것입니다.
예: 三方登录
, 三方支付
, 消息推送
, 资源上传
앞으로도 계속 통합하겠습니다. 일반 비즈니스 생태학. 생산성의 진정한 해방을 실현합니다. 자유로운 조합.
프로그래밍 질문이 있습니다.
공식 계정에주의를 기울이십시오. 프로그래머는 3시에 계속해서 고품질 콘텐츠를 출력하여 영감과 도움을 줄 수 있기를 바랍니다.