標籤:實現 util 序列 寫法 password over ase pre 自己的
最近在使用shiro緩衝使用者的身份資訊的時候,報了simpleByteSource不能序列化,跟進源碼一看,原來這個類沒有實現序列化的介面,但是我在緩衝身份資訊的實現又要用到這個類,解決方案:重寫一個類,模仿著SimpleByteSoure這個類,寫個自己的類。並且實現序列化介面即可·。
1 package com.dzf.shiro; 2 3 import org.apache.shiro.codec.Base64; 4 import org.apache.shiro.codec.CodecSupport; 5 import org.apache.shiro.codec.Hex; 6 import org.apache.shiro.util.ByteSource; 7 8 import java.io.Serializable; 9 import java.util.Arrays;10 11 /**12 * <p>13 * 為瞭解決redis序列化的問題,SimpleByteSource沒有實現序列化介面14 * 在傳入simpleAuthenticationInfo()的時候,緩衝使用者資訊會出現序列化異常15 * </p>16 * @author dingzf17 * @date 2018/3/718 * @time 21:5419 */20 public class ShiroByteSource implements ByteSource, Serializable {21 private static final long serialVersionUID = -6814382603612799610L;22 private volatile byte[] bytes;23 private String cachedHex;24 private String cachedBase64;25 26 public ShiroByteSource() {27 28 }29 30 public ShiroByteSource(String string) {31 this.bytes = CodecSupport.toBytes(string);32 }33 34 public void setBytes(byte[] bytes) {35 this.bytes = bytes;36 }37 38 @Override39 public byte[] getBytes() {40 return this.bytes;41 }42 43 @Override44 public String toHex() {45 if ( this.cachedHex == null ) {46 this.cachedHex = Hex.encodeToString(getBytes());47 }48 return this.cachedHex;49 }50 51 @Override52 public String toBase64() {53 if ( this.cachedBase64 == null ) {54 this.cachedBase64 = Base64.encodeToString(getBytes());55 }56 return this.cachedBase64;57 }58 59 @Override60 public boolean isEmpty() {61 return this.bytes == null || this.bytes.length == 0;62 }63 64 @Override65 public String toString() {66 return toBase64();67 }68 69 @Override70 public int hashCode() {71 if (this.bytes == null || this.bytes.length == 0) {72 return 0;73 }74 return Arrays.hashCode(this.bytes);75 }76 77 @Override78 public boolean equals(Object o) {79 if (o == this) {80 return true;81 }82 if (o instanceof ByteSource) {83 ByteSource bs = (ByteSource) o;84 return Arrays.equals(getBytes(), bs.getBytes());85 }86 return false;87 }88 89 public static ByteSource of(String string) {90 return new ShiroByteSource(string);91 }92 }
在自己的實現的realm裡面調用如下:
1 SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), new ShiroByteSource(user.getSalt()), getName());
以前的寫法是:
1 SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), new SimpleByteSource(user.getSalt()), getName());
然後就可以解決問題了。
使用shiro緩衝使用者身份資訊的時候報:java.io.NotSerializableException: org.apache.shiro.util.SimpleByteSource