Share a simple java login permission implementation process, copy and use
I implemented it here with an interceptor, using redis and springboot2. Don't talk nonsense, let's go to the code
Define the authentication level enumeration:
public enum AuthorityType {<!-- --> // do not verify no check, // only verify login Check Longin, // Both login and permissions are verified CheckLevel0, //user level is 0 permission CheckLevel1, //user level is 1 permission CheckLevel2, //User level is 2 permissions }
Define the interface:
@Documented @Target(ElementType. METHOD) @Retention(RetentionPolicy. RUNTIME) public @interface Authority {<!-- --> // default authentication AuthorityType value() default AuthorityType. Nocheck; }
Define the interceptor:
//login permission verification interceptor @Slf4j @Aspect @Component public class AuthorityAnnotationInterceptor extends HandlerInterceptorAdapter {<!-- --> //redis injection @Autowired private StringRedisTemplate redisTemplate; //User business layer interface @Autowired private IWjUserService wjUserService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<!-- --> if (handler instanceof HandlerMethod) {<!-- --> HandlerMethod hm = (HandlerMethod) handler; Class<?> clazz = hm. getBeanType(); Method m = hm. getMethod(); try {<!-- --> if (clazz != null & amp; & amp; m != null) {<!-- --> boolean isClzAnnotation = clazz.isAnnotationPresent(Authority.class); boolean isMethodAnnotation = m.isAnnotationPresent(Authority.class); Authority authority = null; // If this annotation exists in both the method and the class declaration, the setting in the method will override the setting in the class. //The @Authority annotation on the method has a higher priority than the class if (isMethodAnnotation) {<!-- --> authority = m. getAnnotation(Authority. class); } else if (isClzAnnotation) {<!-- --> authority = clazz. getAnnotation(Authority. class); } response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); if (authority != null) {<!-- --> if (AuthorityType. Nocheck == authority. value()) {<!-- --> // mark as non-verification, release return true; } else{<!-- --> //Verify login //encrytestr is an identifier generated for user login, which is encrypted by userId and userToken. After login, encrytestr is stored in redis. After login, encrytestr is returned to the front end, and the front end puts it into the request header as a public parameter //Get the encrytestr in the request header String encrytestr = request.getHeader("encrytestr");//Get encrytestr if(StringUtils.isBlank(encrytestr)){<!-- --> response.getWriter().write(JSON.toJSONString(new AjaxResult(StatusCode.ERROR_CODE_40000,"token expired, please log in again"))); return false; } //Find out whether encrytestr exists from redis String userString = redisTemplate.opsForValue().get("ulogin" + encrytestr); System.out.println(userString); if(StringUtils.isBlank(userString)){<!-- --> response.getWriter().write(JSON.toJSONString(new AjaxResult(StatusCode.ERROR_CODE_40000,"token expired, please log in again"))); return false; } \t\t\t\t\t\t\t //Decrypt encrytestr to get token and userid Map<String, String> map = CommenUtils.decryptUserIdAndTokenByStr(encrytestr); String token = map. get("token"); String userId = map. get("userId"); if(StringUtils.isBlank(token)||StringUtils.isBlank(userId)){<!-- --> response.getWriter().write(JSON.toJSONString(new AjaxResult(StatusCode.ERROR_CODE_40000,"token error"))); return false; } \t\t\t\t\t\t\t \t\t\t\t\t\t\t WjUser wju = this.wjUserService.getById(userId); if (wju == null) {<!-- --> response.getWriter().write(JSON.toJSONString(new AjaxResult(StatusCode.ERROR_CODE_40000,"token error"))); return false; } //Verify whether the user token has expired if (!wju.getToken().equals(token)) {<!-- --> response.getWriter().write(JSON.toJSONString(new AjaxResult(StatusCode.ERROR_CODE_40000,"token expired, please log in again"))); return false; } if (AuthorityType. CheckLongin == authority. value()) {<!-- --> // Do not verify permissions, verify whether to log in // TODO: return true; }else{<!-- --> // verify user level if (AuthorityType. CheckLevel0 == authority. value()) {<!-- --> // Do not verify permissions, verify whether to log in // TODO: if(wju.getLevel()!=0){<!-- --> response.getWriter().write(JSON.toJSONString(new AjaxResult(StatusCode.ERROR_CODE_40000,"Permissions do not match"))); return false; } return true; }else if (AuthorityType. CheckLevel1 == authority. value()) {<!-- --> // Do not verify permissions, verify whether to log in // TODO: if(wju.getLevel()!=1){<!-- --> response.getWriter().write(JSON.toJSONString(new AjaxResult(StatusCode.ERROR_CODE_40000,"Permissions do not match"))); return false; } return true; }else if (AuthorityType. CheckLevel2 == authority. value()) {<!-- --> // Do not verify permissions, verify whether to log in // TODO: if(wju.getLevel()!=2){<!-- --> response.getWriter().write(JSON.toJSONString(new AjaxResult(StatusCode.ERROR_CODE_40000,"Permissions do not match"))); return false; } return true; } else {<!-- --> // Verify login and permissions // TODO: //response.getWriter().write(JSON.toJSONString(new AjaxResult(StatusCode.ERROR_CODE_40000,"Permissions do not match"))); return true; } } } } // Failed to pass the verification, return prompt json /* response.getWriter().write(JSON.toJSONString(new AjaxResult(StatusCode.ERROR_CODE_40000,"permission error")));*/ return true; } } catch (Exception e) {<!-- --> e.printStackTrace(); } } /* response.getWriter().write(JSON.toJSONString(new AjaxResult(StatusCode.ERROR_CODE_40000,"permission error")));*/ return true; } }
Configuration interceptor:
@Configuration public class WebMvcConfiguration implements WebMvcConfigurer {<!-- --> @Autowired AuthorityAnnotationInterceptor authorityAnnotationInterceptor; @Override //Interceptor configuration public void addInterceptors(InterceptorRegistry registry) {<!-- --> registry.addInterceptor(authorityAnnotationInterceptor) //Interceptor registration object .addPathPatterns("/**") //Specify the request to be intercepted .excludePathPatterns("/wjUser/loginUser"); //exclude request } }
After successful login:
String aesKey = "fd980019fc95df40f0ed43731a11219f"; //Generate userToken, encrypt token and userid into encryptStr, store in redis String key = "ulogin"; if(redisTemplate.hasKey(key + getuser.getEncrytestr())){<!-- --> redisTemplate.delete(key + getuser.getEncrytester()); } SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = simpleDateFormat. format(new Date()); String token = CommenUtils.jdkAESEncrypt(aesKey, format + "," + getuser.getUseraccount()); getuser.setToken(token); String encrypt = CommenUtils.encryptGameUserIdAndToken(getuser.getId(), getuser.getToken()); getuser.setEncrytestr(encrypt); getuser.setLastlogintime(new Timestamp(System.currentTimeMillis())); wjUserService.updateById(getuser); getuser.setPassword(""); redisTemplate.opsForValue().set(key + getuser.getEncrytestr(), JSON.toJSONString(getuser),60 * 60 * 24, TimeUnit.SECONDS); return new AjaxResult(getuser,"login successful");
Some codes in the tool class:
@Slf4j public class CommenUtils {<!-- --> public static Map<String,String> decryptUserIdAndTokenByStr(String encryptStr) {<!-- --> String gameAesKey = "Ae980019bc59fd40f0ef34798e11210a"; String decryptStr = CommenUtils.jdkAESDecrypt(gameAesKey, encryptStr); // log.info("The decrypted string of the game token: " + decryptStr); Map<String,String> map = new HashMap<>(); String[] split = decryptStr. split(","); if (split. length != 2){<!-- --> return null; } map.put("userId", split[0]); map.put("token", split[1]); return map; } /* * AES encryption * @prama HexStringkey key * @prama content encrypted content * */ public static String jdkAESEncrypt(String HexStringkey,String content) {<!-- --> try {<!-- --> byte[] byteskey = Hex.decodeHex(HexStringkey.toCharArray()); //Conversion key Key convertSecretKey = new SecretKeySpec(byteskey, "AES"); //encryption Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey); byte[] encryptResult = cipher.doFinal(content.getBytes()); String encryptResultStr = Hex.encodeHexString(encryptResult); log.info("jdk des encrypt:" + encryptResultStr); return encryptResultStr; } catch (Exception e) {<!-- --> // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static String encryptGameUserIdAndToken(String userId,String token) {<!-- --> String gameAesKey = "Ae980019bc59fd40f0ef34798e11210a"; System.out.println("123123"); System.out.println(gameAesKey); System.out.println(userId); System.out.println(token); String encryptStr = CommenUtils.jdkAESEncrypt(gameAesKey, userId + "," + token); return encryptStr; } /* * AES decryption * @prama HexStringkey key * @prama encryptResultStr decrypted content * */ public static String jdkAESDecrypt(String HexStringkey,String encryptResultStr) {<!-- --> try {<!-- --> byte[] byteskey = Hex.decodeHex(HexStringkey.toCharArray()); //Conversion key Key convertSecretKey = new SecretKeySpec(byteskey, "AES"); // decrypt Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, convertSecretKey); byte[] encryptResult = Hex.decodeHex(encryptResultStr.toCharArray()); byte[] decryptResult = cipher.doFinal(encryptResult); String decryptStr = new String(decryptResult); log.info("jdk des decrypt:" + decryptStr); return decryptStr; } catch (Exception e) {<!-- --> // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
When using it, just @Authority(AuthorityType.CheckLevel0) directly on the method
The user id can also be obtained in the controller
String encrytestr = request. getHeader("encrytester"); //token expiration verification Map<String, String> map = CommenUtils.decryptUserIdAndTokenByStr(encrytestr); String userId = map. get("userId"); WjUser wju = this.wjUserService.getById(userId);
The sharing is almost over. If you copy, you need to replace the user with your own. My authority verification here is only divided into levels. You can change it according to your own needs. The code is not very perfect. Do you have any questions? Suggestions can be left in the comments.
thanks for reading