I open sourced the API scaffold v1.6.0 update based on the rapid development of SpringBoot Web within the team

What is rest-api-spring-boot-starter

rest-api-spring-boot-starter is suitable for the rapid construction of SpringBoot Web API, allowing developers to quickly build a unified and standardized business RestFull API without worrying about some tediousness. Duplicate work, but focus on business.

motivation

Common functions of Web API need to be rewritten every time. Or copy the previous project code. So I encapsulated such astater

Extract the modules and necessary functions that must be rewritten for each project of SpringBoot Web API .
And it expands all the tool libraries I use in my work. Free hands to improve development efficiency

recommended version

  • SpringBoot
SpringBoot 2.7.x

new version update

Currently the latest version 1.6.2 supports the following functions:

  • Support one-click configuration to customize RestFull API uniform format return

  • Support RestFull API error internationalization

  • Support global exception handling, global parameter verification processing

  • Encapsulation of business error assertion tools, following the principle of returning errors first

  • Encapsulate Redis key, value operation tool class. Unified key management spring cache cache implementation

  • RestTemplate encapsulates POST, GET request tool

  • Log integration. Customize the log path, classify according to the log level, support compression and file size segmentation. display by time

  • The tool library integrates lombok, hutool, commons-lang3, and guava. No need to import them individually

  • Integrated mybatisPlus one-click code generation

  • Log records, service monitoring, support log link query. custom data source

  • OpenApi3 document integration supports one-click configuration. Support for multiple documents and auto-configuration

  • Generate JWT standard Token and authority authentication

  • Interface current limit, IP city echo

  • HttpUserAgent request device tool package

  • RequestUtil parameter parsing and encapsulation tool

  • GitHub address

  • gitee address

Web JWT Token permission support

JWT Web Token

You can easily customize and generate yourself JWT Web Token. And based on JWTuserJwtToken

Through which userJwtTokenyou can easily generate authentication based on user loginToken

@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);
}

Parsing and tokenobtaining user information

@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);
}

Customize Token secret key and signature configuration

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

Custom signature authentication and dynamic key authorization need to implement UserSigninterface configuration UserJwtConfigconfiguration classes to inject custom signaturesbean

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

When AuthKey returns, nullit will use the secret key you configured in the properties file. None will use the default

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

Authentication

Based on JWT Web Tokenalso help you encapsulate the authorization login authentication. You just need to enable it in the property file configuration.

jwt:
 authorization:
    has-authorization: true
    includes-url: /user    # 需要认证请求 多个用逗号隔开
    excludes-url: /login,/register/**      # 配置无需认证的

Global helps you automatically handle Tokenexpired exceptions. TokenAnd error exceptions, you only need to configure your own in heard

{
    
    
    "success": false,
    "code": "401",
    "msg": "未授权 ",
    "requestId": "9a3ytEtOX0UuojSaA2LD",
    "timestamp": "2023-07-17 17:08:05",
    "data": null
}

If you need to customize your own authentication and authorization logic, LoginAuthorizationjust implement the interface
and inject the corresponding bean in UserJwtConfigthe configuration classLoginAuthorization

like:

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

Inject the bean in the configuration class

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

Three-party authority authentication framework

Based on JWT Web Token can also be easily integrated Shiroor is. Spring Securityother third authority frameworks

Of course, in subsequent versions, I will separate permission authentication into a complete lightweight permission framework project. For example:
through annotations @hasPerm, @hasRole, @hasAnyPerm, @hasAnyRoles
easy to achieve relatively complex authority authentication.

follow-up update

General business

When we focus on project development, there will always be some relatively public and independent third-party business modules.
Such as: 三方登录, 三方支付, 消息推送, 资源上传
I will continue to integrate in the future. General business ecology. Realize the real liberation of productivity. Free combination.

Have any programming questions.

Pay attention to the official account, the programmer will continue to output high-quality content at three o'clock , hoping to bring you some inspiration and help

Guess you like

Origin blog.csdn.net/u011738045/article/details/131836213