欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于springboot和redis實(shí)現(xiàn)單點(diǎn)登錄

 更新時間:2019年06月24日 14:37:30   作者:workit123  
這篇文章主要為大家詳細(xì)介紹了基于springboot和redis實(shí)現(xiàn)單點(diǎn)登錄,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了基于springboot和redis實(shí)現(xiàn)單點(diǎn)登錄的具體代碼,供大家參考,具體內(nèi)容如下

1、具體的加密和解密方法

package com.example.demo.util;

import com.google.common.base.Strings;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * Create by zhuenbang on 2018/12/3 11:27
 */
public class AESUtil {
 private static final String defaultKey = "7bf72345-6266-4381-a4d3-988754c5f9d1";
 /** 
 * @Description: 加密
 * @Param: 
 * @returns: java.lang.String 
 * @Author: zhuenbang
 * @Date: 2018/12/3 11:33
 */
 public static String encryptByDefaultKey(String content) throws Exception {
 return encrypt(content, defaultKey);
 }

 
 /** 
 * @Description: 解密 
 * @Param: 
 * @returns: java.lang.String 
 * @Author: zhuenbang
 * @Date: 2018/12/3 11:30
 */
 public static String decryptByDefaultKey(String encryptStr) throws Exception {
 return decrypt(encryptStr, defaultKey);
 }

 /**
 * AES加密為base 64 code
 *
 * @param content 待加密的內(nèi)容
 * @param encryptKey 加密密鑰
 * @return 加密后的base 64 code
 * @throws Exception
 */

 public static String encrypt(String content, String encryptKey) throws Exception {
 return base64Encode(aesEncryptToBytes(content, encryptKey));

 }

 /**
 * AES加密
 *
 * @param content 待加密的內(nèi)容
 * @param encryptKey 加密密鑰
 * @return 加密后的byte[]
 * @throws Exception
 */

 private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {

 KeyGenerator kgen = KeyGenerator.getInstance("AES");

 SecureRandom random;
 if (System.getProperty("os.name").toLowerCase().contains("linux")) {
 random = SecureRandom.getInstance("SHA1PRNG");
 } else {
 random = new SecureRandom();
 }

 random.setSeed(encryptKey.getBytes());
 kgen.init(128, random);

 Cipher cipher = Cipher.getInstance("AES");

 cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));


 return cipher.doFinal(content.getBytes("utf-8"));

 }

 /**
 * base 64 加密
 *
 * @param bytes 待編碼的byte[]
 * @return 編碼后的base 64 code
 */

 private static String base64Encode(byte[] bytes) {

 return new BASE64Encoder().encode(bytes);

 }
 
 /**
 * 將base 64 code AES解密
 *
 * @param encryptStr 待解密的base 64 code
 * @param decryptKey 解密密鑰
 * @return 解密后的string
 * @throws Exception
 */

 public static String decrypt(String encryptStr, String decryptKey) throws Exception {

 return Strings.isNullOrEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);

 }
 
 /**
 * AES解密
 *
 * @param encryptBytes 待解密的byte[]
 * @param decryptKey 解密密鑰
 * @return 解密后的String
 * @throws Exception
 */
 private static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {

 KeyGenerator kgen = KeyGenerator.getInstance("AES");

 SecureRandom random;
 if (System.getProperty("os.name").toLowerCase().contains("linux")) {
 random = SecureRandom.getInstance("SHA1PRNG");
 } else {
 random = new SecureRandom();
 }
 random.setSeed(decryptKey.getBytes());

 kgen.init(128, random);


 Cipher cipher = Cipher.getInstance("AES");

 cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));

 byte[] decryptBytes = cipher.doFinal(encryptBytes);


 return new String(decryptBytes);

 }

 /**
 * base 64 解密
 *
 * @param base64Code 待解碼的base 64 code
 * @return 解碼后的byte[]
 * @throws Exception
 */

 private static byte[] base64Decode(String base64Code) throws Exception {

 return Strings.isNullOrEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);

 }
}

2、這里獲取的token很關(guān)鍵,每次登錄都要生成新的token,token是根據(jù)userId和當(dāng)前時間戳加密的

@Override
 public String getToken(String userId) throws Exception {
 String token = AESUtil.encryptByDefaultKey(Joiner.on("_").join(userId, System.currentTimeMillis()));
 logger.debugv("token= {0}", token);
 redisService.set(UserKey.userAccessKey, userId, token);
 return token;
 }

3、寫一個解密的方法,解密把用戶id拿出來,然后從攔截器里拿出token和當(dāng)前登錄token做對比

 @Override
 public String checkToken(String token) throws Exception {
 String userId = AESUtil.decryptByDefaultKey(token).split("_")[0];
 String currentToken = redisService.get(UserKey.userAccessKey, userId, String.class);
 logger.debugv("currentToken={0}", currentToken);
 if (StringUtils.isEmpty(currentToken)) {
  return null;
 }
 if (!token.equals(currentToken)) {
  return null;
 }
 return userId;
 }

4、攔截器里具體處理,這里采用注解攔截,當(dāng)controller有@Secured攔截器才攔截

 @Autowired
 AuthTokenService authTokenService;
 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

 if (handler instanceof HandlerMethod) {
  HandlerMethod hm = (HandlerMethod) handler;
  Secured secured = hm.getMethodAnnotation(Secured.class);
  if (secured != null) {
  String authToken = request.getHeader(UserConstant.USER_TOKEN);
  if (StringUtils.isEmpty(authToken)) {
   render(response, CodeMsg.REQUEST_ILLEGAL);
   return false;
  }
  String userId = authTokenService.checkToken(authToken);
  if (StringUtils.isEmpty(userId)) {
   render(response, CodeMsg.LOGIN_FAILURE);
   return false;
  }
  }
  return true;
 }
 return true;
 }


private void render(HttpServletResponse response, CodeMsg cm) throws Exception {
 response.setContentType("application/json;charset=UTF-8");
 OutputStream out = response.getOutputStream();
 String str = JSON.toJSONString(Result.error(cm));
 out.write(str.getBytes("UTF-8"));
 out.flush();
 out.close();
 }

5、寫一個測試登錄接口和一個測試單點(diǎn)登錄接口

 /** 
 * @Description: 模擬登錄 
 * @Param: 
 * @returns: com.example.demo.result.Result 
 * @Author: zhuenbang
 * @Date: 2018/12/3 12:05
 */
 @GetMapping("/login")
 public Result login() throws Exception {
 return authTokenService.login();
 }
 
 
 /** 
 * @Description: 模擬單點(diǎn)登錄 @Secured這個方法攔截器會攔截
 * @Param: 
 * @returns: com.example.demo.result.Result 
 * @Author: zhuenbang
 * @Date: 2018/12/3 12:35
 */
 @Secured
 @GetMapping("/testSSO")
 public Result testSSO() {
 return authTokenService.testSSO();
 }

 具體的實(shí)現(xiàn)
 @Override
 public Result login() throws Exception {
 String userId = "123456";
 return Result.success(this.getToken(userId));
 }

 @Override
 public Result testSSO() {
 return Result.success("登錄狀態(tài)正常");
 }

postman 測試

單點(diǎn)登錄測試

再次請求登錄接口,然后不改變token接口如圖

這個方式實(shí)現(xiàn)單點(diǎn)登錄的關(guān)鍵就是根據(jù)userId的加密和解密的實(shí)現(xiàn)。

github地址:demo

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • java?使用readLine()?亂碼的解決

    java?使用readLine()?亂碼的解決

    這篇文章主要介紹了java使用readLine()亂碼的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Spring中的PathVariable注釋解析

    Spring中的PathVariable注釋解析

    這篇文章主要介紹了Spring中的PathVariable注釋用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Dubbo Consumer引用服務(wù)示例代碼詳解

    Dubbo Consumer引用服務(wù)示例代碼詳解

    dubbo中引用遠(yuǎn)程服務(wù)有兩種方式:服務(wù)直連(不經(jīng)過注冊中心)、基于注冊中心引用服務(wù),在實(shí)際線上環(huán)境中我們基本上使用的都是基于注冊中心引用服務(wù)的方式,下面我們就圍繞該方式講解分析
    2023-03-03
  • Spring Boot整合Spring Data JPA過程解析

    Spring Boot整合Spring Data JPA過程解析

    這篇文章主要介紹了Spring Boot整合Spring Data JPA過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-10-10
  • SpringBoot實(shí)現(xiàn)文件的上傳、下載和預(yù)覽功能

    SpringBoot實(shí)現(xiàn)文件的上傳、下載和預(yù)覽功能

    在Spring Boot項(xiàng)目中實(shí)現(xiàn)文件的上傳、下載和預(yù)覽功能,可以通過使用Spring MVC的MultipartFile接口來處理文件上傳,并使用HttpServletResponse或Resource來實(shí)現(xiàn)文件下載和預(yù)覽,下面是如何實(shí)現(xiàn)這些功能的完整示例,需要的朋友可以參考下
    2024-08-08
  • Java并發(fā)之傳統(tǒng)線程同步通信技術(shù)代碼詳解

    Java并發(fā)之傳統(tǒng)線程同步通信技術(shù)代碼詳解

    這篇文章主要介紹了Java并發(fā)之傳統(tǒng)線程同步通信技術(shù)代碼詳解,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下
    2018-02-02
  • mybatis中關(guān)于mapper的使用以及注意事項(xiàng)

    mybatis中關(guān)于mapper的使用以及注意事項(xiàng)

    這篇文章主要介紹了mybatis中關(guān)于mapper的使用以及注意事項(xiàng),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • Java?for循環(huán)倒序輸出的操作代碼

    Java?for循環(huán)倒序輸出的操作代碼

    在Java中,要實(shí)現(xiàn)一個for循環(huán)的倒序輸出,通常我們會使用數(shù)組或集合(如ArrayList)作為數(shù)據(jù)源,然后通過倒序遍歷這個數(shù)組或集合來實(shí)現(xiàn),這篇文章主要介紹了Java?for循環(huán)倒序輸出,需要的朋友可以參考下
    2024-07-07
  • java的多線程用法編程總結(jié)

    java的多線程用法編程總結(jié)

    本文主要講了java中多線程的使用方法、線程同步、線程數(shù)據(jù)傳遞、線程狀態(tài)及相應(yīng)的一些線程函數(shù)用法、概述等。
    2016-10-10
  • 詳解Maven項(xiàng)目Dependencies常見報錯及解決方案

    詳解Maven項(xiàng)目Dependencies常見報錯及解決方案

    這篇文章主要介紹了詳解Maven項(xiàng)目Dependencies常見報錯及解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11

最新評論