Preface
This article introduces the main methods of login and authentication mechanisms under Spring and the main processes of token authentication, and introduces the implementation method of setting different token expiration times in spring and APP. It is mainly based on the SpringBoot+springSecurity+JWT framework.
1. Application scenarios
The cross-platform operation of the same system is based on user habits. The length of time used by web and app users is often different. Too long a unified period can easily cause waste of server resources, and too short a unified period will cause the user to log in to expire before the operation is completed. Therefore, to make it easier for users to use, setting the token expiration time on a platform can improve the user experience.
2. Login method and token authentication
To set the token expiration time by platform, you must first understand the main methods and token generation of SpringSecurity login process.
1. Login process
Login --> Verify username, password, verification code --> Redis stores login user information --> Generate token(JWT) --> Return token
// Show only key statements
@PostMapping("/login") public AjaxResult login(@RequestBody LoginBody loginBody) { AjaxResult ajax = (); // Generate tokens String token = ((), (), (), (),(), ()); (, token); return ajax; }
public String login(String username, String aes_password, String code, String uuid, String clientPubKey, String platForm) { // Verify username and passwordauthentication = (new UsernamePasswordAuthenticationToken(username, password)); LoginUser loginUser = (LoginUser) (); // Generate tokens(platForm); return (loginUser); }
2、JWT
JWT is a token-based authentication and authorization mechanism that can be used to create tokens.
Token = Head+info+sign
Head: Coding method
Info: User information, including username and other custom information
Sign: Signature
As shown below:
Map<String, Object> claims = new HashMap<>(); (Constants.LOGIN_USER_KEY, token); (Constants.JWT_USERID, ()); (Constants.JWT_USERNAME, ()); private String createToken(Map<String, Object> claims) { String token = () .setClaims(claims) .signWith(SignatureAlgorithm.HS512, secret).compact(); return token; }
3. Token authentication
The token returned after login is stored in the front-end cache, placed in the request header every time it is requested, the token is parsed when passing through the interceptor, and the verifyToken method checks whether the token is valid or expired, and the redreshToken extends the expiration time (this time is active).
// Verification
public void verifyToken(LoginUser loginUser) { long expireTime = (); long currentTime = (); if(().equals("pc")){ if (expireTime - currentTime <= MILLIS_MINUTE_TEN_PC) { refreshToken(loginUser); } }else if(().equals("app")) { if (expireTime - currentTime <= MILLIS_MINUTE_TEN_APP) { refreshToken(loginUser); } } }
// Update expiration time
public void refreshToken(LoginUser loginUser) { if(().equals("pc")){ expireTime = pcExpireTime; }else if(().equals("app")){ expireTime = appExpireTime; } (()); (() + expireTime * MILLIS_MINUTE); //Cach loginUser according to uuid String userKey = getTokenKey(()); (userKey, loginUser, expireTime, ); }
Implementation method
1. Configuration file
The expiration time of the PC end is 59min, and the app end is 3 days
# token configurationtoken: # Token custom identifier header: Authorization # Token key secret: abcdefghijklmnopqrstuvwxyz # Token validity period (default 59 minutes; 3 days on the APP side) expireTime: defaultExpireTime: 59 pcExpireTime: 59 appExpireTime: 4320
2. Login information entity class
Add platform information
src/main/java/com/common/core/domain/model/
src/main/java/com/common/core/domain/model/
public class LoginBody { // ****Other omitted /** * Login platform: Mobile terminal ='app', PC terminal ='pc' */ private String platForm; public String getPlatForm() { return platForm; } public void setPlatForm(String platForm) { = platForm; } }
3. Login method
(1) Login controller layer method
Method parameters and platform information for generating tokens
src/main/java/com/web/controller/system/
@PostMapping("/login") public AjaxResult login(@RequestBody LoginBody loginBody) { AjaxResult ajax = (); // Generate tokens String token = ((), (), (), (),(), ()); (, token); return ajax; }
(2) Login information verification and token generation
src/main/java/com/inspur/framework/web/service/
// Based on SpringSecurity's verification method, modify the returned login user information and can be manually set after returning.
public String login(String username, String aes_password, String code, String uuid, String clientPubKey, String platForm) { // Show only important key sentences // Verify username and password authentication = (new UsernamePasswordAuthenticationToken(username, password)); // Return to login information LoginUser loginUser = (LoginUser) (); // Generate tokens(platForm); return (loginUser); }
private String createToken(Map<String, Object> claims) { String token = () .setClaims(claims) .signWith(SignatureAlgorithm.HS512, secret).compact(); return token; }
(3) Token verification authentication and update
src/main/java/com/inspur/common/service/
// Each time the user requests, the token information is stored in the request header and intercepted by the interceptor.
@Component public class TokenService { // The token validity period (default 30 minutes) @Value("${}") private int expireTime; @Value("${}") private int pcExpireTime; @Value("${}") private int appExpireTime; //pc-Refresh the token expiration time when 20 minutes awayprivate static final Long MILLIS_MINUTE_TEN_PC = 20 * 60 * 1000L; //App end - refresh the token expiration time when 1 day awayprivate static final Long MILLIS_MINUTE_TEN_APP = 24 * 60 * 60 * 1000L; public void verifyToken(LoginUser loginUser) { long expireTime = (); long currentTime = (); if(().equals("pc")){ if (expireTime - currentTime <= MILLIS_MINUTE_TEN_PC) { refreshToken(loginUser); } }else if(().equals("app")) { if (expireTime - currentTime <= MILLIS_MINUTE_TEN_APP) { refreshToken(loginUser); } } }
public void refreshToken(LoginUser loginUser) { if(().equals("pc")){ expireTime = pcExpireTime; }else if(().equals("app")){ expireTime = appExpireTime; } (()); (() + expireTime * MILLIS_MINUTE); //Cach loginUser according to uuid String userKey = getTokenKey(()); (userKey, loginUser, expireTime, ); } }
4. Front-end transmission platform information
(1) Web end (based on Vue)
Log in to deliver platform information: platForm='pc'
src/store/modules/
// Log inLogin({commit}, userInfo) { const username = () const password = const code = const uuid = const platForm = 'pc' return new Promise((resolve, reject) => { getPublicKey(username).then(res => { if ( === 200) { let result = encryptData(, password); let aes_password = ; login(username, aes_password, code, uuid,,platForm).then(res => { setToken() commit('SET_TOKEN', ) resolve() }).catch(error => { reject(error) }) } }) }) },
src/api/
export function login(username, password, code, uuid,clientPubKey) { const platForm = 'pc' const data = { username, password, code, uuid, clientPubKey, platForm } return request({ url: '/login', method: 'post', data: data }) }
(2) App end (based on uniapp)
api/
// Login methodexport function login(username, password, code, uuid) { let platForm = 'app' const data = { username, password, code, uuid, platForm } return request({ 'url': '/appLogin', headers: { isToken: false }, 'method': 'post', 'data': data }) }
Summarize
This is the article about the settings of the token expiration time platform (web and app) under Spring. For more related contents of the token expiration time platform settings, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!