Actual project configuration

Posted by danwatt on Sat, 29 Jan 2022 02:06:13 +0100

application.properties file

Configuration dependency:

Build project environment: code generator

Query function

mapper is an interface interface. You need to add a configuration class before it can be managed by springboot

Delete function

Making a file is the generated entity class entity

Pass value through path

Test tool: swagger

Integrate swagger

Integrate swagger for interface test: 1 Generate online interface document 2 Convenient interface test

Create common modules and integrate swagger so that all modules can be used

Dependency import:



Create sub modules under common

In the module service base, create the configuration class and package of swagger

com.atguigu.servicebase.config, create the class SwaggerConfig

Specific use

In service_edu import service_base dependency

Unified return results

json data format

Unified return result class

Private methods can only be used by others and cannot be modified

Add the same result under the pom file of the service

Multi condition query

exception handling

@Date generate get and set methods

@AllArgsConstructor generate parametric construction method

@Construction method of generating parameterless from noargsconstructor

@The exception handler captures the annotation of the exception

Unified exception handling

Special (specified) exception handling

Custom exception handling

journal

1. Configure log level

The behavior of the Logger is divided into levels: OFF, FATAL, ERROR, WARN, INFO, DEBUG and ALL. By default, the log level printed by springboot from the console is only INFO or above. The log level can be configured

#Configure log level
logging.level.root=WARN 

log4j and logback logging tools

mybatis log configuration

mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

JWT

What is Jwt (Json Web Token) is a JSON based open standard (RFC 7519) implemented to transfer statements in network application environment. The Token is designed to be compact and secure, especially suitable for single sign on (SSO) scenarios of distributed sites,

The life of JWT is generally used to transfer the authenticated user identity information between identity authentication providers and service providers, so as to obtain resources from the resource server. Some additional declaration information necessary for other business logic can also be added. The token can also be directly used for authentication or encrypted

JWT usually consists of three parts: header, payload and signature

It is generally used for user authentication (wechat applet with front and rear ends separated)  app (Development)

Traditional session authentication

The http protocol itself is a stateless protocol, which means that if the user provides the user name and password to our application for user authentication, the user will have to authenticate the user again in the next request, because according to the http protocol, we can't know which user sent the request, Therefore, in order for our application to identify which user sent the request, we can only store a user login information in the server. This login information will be passed to the browser when responding and told to save it as a cookie so that it can be sent to our application when the request is sent next time, so that our application can identify which user the request comes from, This is the traditional session based authentication.

Session disadvantages

Session based authentication makes it difficult to expand the application itself. With the increase of different client users, independent servers can no longer carry more users. At this time, the problem of session based authentication application will be exposed

Authentication mechanism based on token

The authentication mechanism based on token is similar to http protocol and is stateless. It does not need to retain the user's authentication information or session information at the server. This means that the application based on token authentication mechanism does not need to consider which server the user logs in, which provides convenience for the expansion of the application.

technological process:

  • The user uses the user name and password to request the server
  • The server authenticates the user's information
  • The server sends a token to the user through authentication
  • The client stores the token and attaches the token value to each request
  • The server verifies the token value and returns data

How does JWT work

  1. The application (or client) wants to authorize the server to request authorization. For example, if the authorization code process is used, it is / oauth/authorize

  2. When the authorization is granted, the authorization server returns an access token to the application

  3. Applications use access token to access protected resources (such as API)

maven dependency

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
     <version>3.2.0</version>
</dependency>
<dependency>
     <groupId>io.jsonwebtoken</groupId>
     <artifactId>jjwt</artifactId>
     <version>0.7.0</version>
</dependency>

Jwt tool class

public class JwtUtils {
    /**
     * Issue JWT
     * 
     * @param id
     * @param subject   JSON data can be as little as possible
     * @param ttlMillis
     * @return String
     *
     */
    public static String createJWT(String id, String subject, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder().setId(id).setSubject(subject) // theme
                .setIssuer("user") // Issuer
                .setIssuedAt(now) // Time filed 
                .signWith(signatureAlgorithm, secretKey); // Signature algorithm and key
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate); // Expiration time
        }
        return builder.compact();
    }

    /**
     * Verify JWT
     * 
     * @param jwtStr
     * @return
     */
    public static CheckResult validateJWT(String jwtStr) {
        CheckResult checkResult = new CheckResult();
        Claims claims = null;
        try {
            claims = parseJWT(jwtStr);
            checkResult.setSuccess(true);
            checkResult.setClaims(claims);
        } catch (ExpiredJwtException e) {
            checkResult.setErrCode(SystemConstant.JWT_ERRCODE_EXPIRE);
            checkResult.setSuccess(false);
        } catch (SignatureException e) {
            checkResult.setErrCode(SystemConstant.JWT_ERRCODE_FAIL);
            checkResult.setSuccess(false);
        } catch (Exception e) {
            checkResult.setErrCode(SystemConstant.JWT_ERRCODE_FAIL);
            checkResult.setSuccess(false);
        }
        return checkResult;
    }

    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.decode(SystemConstant.JWT_SECERT);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 
     * Parse JWT string
     * 
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
    }
}

Code example

public class LoginController {
    @Autowired
    UserRepository userRepository;
    

    @RequestMapping(value="login",method = RequestMethod.POST)
    public ReturnVo login(String username, String password,HttpServletResponse
            response) {
        User user =  userRepository.findByUsername(username);
        if(user!=null){
            if(user.getPassword().equals(password)){
                //Return the token to the client -- > the client saves it to a cookie -- > the client attaches a cookie parameter to each request
                String JWT = JwtUtils.createJWT("1", username, SystemConstant.JWT_TTL);
                return ReturnVo.ok(JWT);
            }else{
                return ReturnVo.error();
            }
        }else{
            return ReturnVo.error();
        }
    }


    @RequestMapping(value="description",method = RequestMethod.POST)
    public ReturnVo description(String username) {
        User user =  userRepository.findByUsername(username);
        return ReturnVo.ok(user.getDescription());
    }
}

Integrate Shiro+jwt and share sessions

Considering that clustering and load balancing may be required later, session sharing is required. For Shiro's cache and session information, we generally consider using redis to store these data, so we need to integrate not only Shiro but also redis. In the open source project, we found a stat that can quickly integrate Shiro redis. It is simple to configure and recommended to use

For the stock price of front-end and back-end separation projects, token or jwt is generally used as the cross domain authentication solution. Therefore, in the process of integrating shiro, jwt authentication process needs to be introduced

Front end technology - vscode installation and use

How to use vscade

MD5 encryption code

Integrating redis. In the open source project, we found a stater that can quickly integrate Shiro redis. The configuration is simple and recommended

For the stock price of front-end and back-end separation projects, token or jwt is generally used as the cross domain authentication solution. Therefore, in the process of integrating shiro, jwt authentication process needs to be introduced

[external chain picture transferring... (img-a903Gd4R-1624082269163)]

Front end technology - vscode installation and use

[external chain picture transferring... (img-1dTdn7Uj-1624082269164)]

How to use vscade

[external chain picture transferring... (img-SgZvj6AG-1624082269164)]

[external chain picture transferring... (img-RTKV0r6V-1624082269164)]

MD5 encryption code

Topics: Java Spring Spring Boot