整合内容包括
- 自定義realm,實作認證和授權
- 自定義加密,實作密碼加密驗證
- 自定義Cachemanager、Cache,實作Shiro的cache管理,存儲在redis中
- 自定義SessionManager、SessionDao、SessionIdCookie,實作Shiro的session管理,存儲在redsi中
- 自定義RememberMeManager、RemeberMeCookie,實作Shiro記住我的功能
添加maven依賴
<!-- spring整合shiro -->
<!-- maven會自動添加shiro-core,shiro-web依賴 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- redis相關 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!-- 使用@Slf4j注解 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
Shiro配置
package com.ahut.config;
import com.ahut.shiro.MyRealm;
import com.ahut.shiro.RedisShiroCacheManager;
import com.ahut.shiro.RedisShiroSessionDao;
import com.ahut.utils.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
/**
* @author cheng
* @className: ShiroConfig
* @description: shiro配置
* @dateTime 2018/4/18 15:38
*/
@Configuration
@Slf4j
public class ShiroConfig {
}
Shiro工具類
package com.ahut.utils;
import com.ahut.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author cheng
* @className: ShiroUtil
* @description: 管理shiro session的工具類
* @dateTime 2018/4/19 10:15
*/
public class ShiroUtil {
/**
* 日志管理
*/
private static Logger log = LoggerFactory.getLogger(ShiroUtil.class);
/**
* 目前使用者
*/
private static final String CURRENT_USER = "CURRENT_USER";
/**
* shiro加密算法
*/
public static final String HASH_ALGORITHM_NAME = "md5";
/**
* 散列次數
*/
public static final int HASH_ITERATIONS = ;
/**
* 全局session過期時間
*/
public static final int GLOBAL_SESSION_TIMEOUT = ;
/**
* 自定義shiro session的cookie名稱
*/
public static final String SESSIONID_COOKIE_NAME = "SHIRO_SESSION_ID";
/**
* 自定義remeber me的cookie名稱
*/
public static final String REMEBER_ME_COOKIE_NAME = "REMEBER_ME";
/**
* shiro session字首
*/
public static final String SHIRO_SESSION_PREFIX = "shiro_session:";
/**
* shiro cache字首
*/
public static final String SHIRO_CACHE_PREFIX = "shiro_cache:";
/**
* shiro session過期時間-秒
*/
public static final int EXPIRE_SECONDS = ;
/**
* @description: 私有化構造函數
* @author cheng
* @dateTime 2018/4/19 10:15
*/
private ShiroUtil() {
}
/**
* @description: 擷取session
* @author cheng
* @dateTime 2018/4/19 10:38
*/
public static Session getSession() {
Session session = null;
try {
Subject currentUser = SecurityUtils.getSubject();
session = currentUser.getSession();
} catch (Exception e) {
log.warn("擷取shiro目前使用者的session時發生了異常", e);
throw e;
}
return session;
}
/**
* @description: 将資料放到shiro session中
* @author cheng
* @dateTime 2018/4/19 10:45
*/
public static void setAttribute(Object key, Object value) {
try {
Session session = getSession();
session.setAttribute(key, value);
} catch (Exception e) {
log.warn("将一些資料放到Shiro Session中時發生了異常", e);
throw e;
}
}
/**
* @description: 擷取shiro session中的資料
* @author cheng
* @dateTime 2018/4/19 10:48
*/
public static Object getAttribute(Object key) {
Object value = null;
try {
Session session = getSession();
value = session.getAttribute(key);
} catch (Exception e) {
log.warn("擷取shiro session中的資料時發生了異常", e);
throw e;
}
return value;
}
/**
* @description: 删除shiro session中的資料
* @author cheng
* @dateTime 2018/4/19 10:51
*/
public static void removeAttribute(Object key) {
try {
Session session = getSession();
session.removeAttribute(key);
} catch (Exception e) {
log.warn("删除shiro session中的資料時發生了異常", e);
throw e;
}
}
/**
* @description: 設定目前使用者
* @author cheng
* @dateTime 2018/4/19 10:59
*/
public static void setCurrentUser(Object user) {
setAttribute(CURRENT_USER, user);
}
/**
* @description: 擷取目前使用者
* @author cheng
* @dateTime 2018/4/19 10:59
*/
public static User getCurrentUser() {
User user = (User) getAttribute(CURRENT_USER);
return user;
}
/**
* @description:删除目前使用者
* @author cheng
* @dateTime 2018/4/19 10:59
*/
public static void removeCurrentUser() {
removeAttribute(CURRENT_USER);
}
/**
* @description: 加密密碼
* @author cheng
* @dateTime 2018/4/23 15:01
*/
public static String encrypt(String password, String salt) {
Md5Hash md5Hash = new Md5Hash(password, salt, HASH_ITERATIONS);
return md5Hash.toString();
}
}
配置redis,請看我的這篇部落格:springboot整合redis
redis工具類
package com.ahut.utils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.Set;
/**
* @author cheng
* @className: RedisUtil
* @description: redis操作工具類
* @dateTime 2018/4/23 16:12
*/
// 因為工具類中的JedisPool 使用了spring注入,是以該工具類也要加入IOC容器
@Component
public class RedisUtil {
/**
* jedisPool
*/
private static JedisPool jedisPool;
/**
* @description: 靜态字段, 通過set注入jedispool
* @author cheng
* @dateTime 2018/4/24 9:45
*/
@Autowired
public void setJedisPool(JedisPool jedisPool) {
RedisUtil.jedisPool = jedisPool;
}
/**
* @description: 私有化構造函數
* @author cheng
* @dateTime 2018/4/23 16:12
*/
private RedisUtil() {
}
/**
* @description: 擷取jedis
* @author cheng
* @dateTime 2018/4/24 9:47
*/
public static Jedis getJedis() {
return jedisPool.getResource();
}
/**
* @description: 儲存到redis
* @author cheng
* @dateTime 2018/4/24 10:04
*/
public static void set(byte[] key, byte[] value) {
Jedis jedis = getJedis();
try {
jedis.set(key, value);
} finally {
jedis.close();
}
}
/**
* @description: 從redis中擷取
* @author cheng
* @dateTime 2018/4/24 10:11
*/
public static byte[] get(byte[] key) {
Jedis jedis = getJedis();
try {
return jedis.get(key);
} finally {
jedis.close();
}
}
/**
* @description: 從redis中删除
* @author cheng
* @dateTime 2018/4/24 10:17
*/
public static void del(byte[] key) {
Jedis jedis = getJedis();
try {
jedis.del(key);
} finally {
jedis.close();
}
}
/**
* @description: 依據字首删除key
* @author cheng
* @dateTime 2018/4/24 16:48
*/
public static void delByPrefix(String keyPrefix) {
keyPrefix = keyPrefix + "*";
Jedis jedis = getJedis();
try {
Set<byte[]> keyByteArraySet = jedis.keys(keyPrefix.getBytes());
for (byte[] keyByteArray : keyByteArraySet) {
jedis.del(keyByteArray);
}
} finally {
jedis.close();
}
}
/**
* @description: 設定redis過期時間
* @author cheng
* @dateTime 2018/4/24 10:21
*/
public static void expire(byte[] key, int seconds) {
Jedis jedis = getJedis();
try {
jedis.expire(key, seconds);
} finally {
jedis.close();
}
}
/**
* @description: 從redis中擷取指定字首的key
* @author cheng
* @dateTime 2018/4/24 10:25
*/
public static Set<byte[]> keys(String shiroSessionPrefix) {
shiroSessionPrefix = shiroSessionPrefix + "*";
Jedis jedis = getJedis();
try {
return jedis.keys(shiroSessionPrefix.getBytes());
} finally {
jedis.close();
}
}
}
自定義Realm
package com.ahut.shiro;
import com.ahut.common.ApiResponse;
import com.ahut.entity.User;
import com.ahut.enums.UserStatusEnum;
import com.ahut.service.UserService;
import com.ahut.utils.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author cheng
* @className: MyRealm
* @description: 自定義realm
* @dateTime 2018/4/18 15:40
*/
@Slf4j
public class MyRealm extends AuthorizingRealm {
/**
* 使用者業務邏輯,因為使用的spring的自動裝配,
* 是以MyRealm 也要添加到IOC容器中,不然會出現userService為null
*/
@Autowired
private UserService userService;
/**
* @description: 用于認證
* @author cheng
* @dateTime 2018/4/18 15:42
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken newToken = (UsernamePasswordToken) token;
// 擷取使用者賬号
String userAccount = newToken.getUsername();
log.info("使用者{}請求認證", userAccount);
// 依據使用者賬号查找使用者
ApiResponse apiResponse = userService.selectByUserAccount(userAccount);
// 賬号不存在
if (ApiResponse.FAIL_TYPE.equals(apiResponse.getType())) {
throw new UnknownAccountException();
}
List<User> userList = (List<User>) apiResponse.getData();
User user = userList.get();
// 擷取使用者狀态
int userStatus = user.getUserStatus();
// 擷取使用者密碼
String userPassword = user.getUserPassword();
// 賬号鎖定
if (userStatus == UserStatusEnum.LOCKED_ACCOUNT.getCode()) {
throw new LockedAccountException();
}
// 賬号禁用
if (userStatus == UserStatusEnum.DISABLED_ACCOUNT.getCode()) {
throw new DisabledAccountException();
}
// 鹽
String salt = user.getId();
// 儲存目前使用者資訊到shiro session中
ShiroUtil.setCurrentUser(user);
// 與UsernamePasswordToken(userAccount, userPassword)進行比較
// 如果沒有配置Shiro加密,會直接進行比較
// 如果配置了Shiro的加密,會先對UsernamePasswordToken(userAccount, userPassword)中的密碼進行加密,
// 再和SimpleAuthenticationInfo(userAccount, userPassword, ByteSource.Util.bytes(salt), this.getName())中的密碼進行比較
return new SimpleAuthenticationInfo(userAccount, userPassword, ByteSource.Util.bytes(salt), this.getName());
}
/**
* @description: 用于授權
* @author cheng
* @dateTime 2018/4/18 15:42
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 擷取使用者賬号
// String userAccount = (String) principals.getPrimaryPrincipal();
// 依據使用者賬号在資料庫中查找權限資訊
log.info("使用者請求授權");
// 角色
List<String> roles = new ArrayList<>();
roles.add("admin");
roles.add("user");
// 權限
List<String> permissions = new ArrayList<>();
permissions.add("admin:select");
permissions.add("admin:delete");
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addStringPermissions(permissions);
simpleAuthorizationInfo.addRoles(roles);
return simpleAuthorizationInfo;
}
}
在ShiroConfig 中添加配置
/**
* @description:自定義realm
* @author cheng
* @dateTime 2018/4/18 15:44
*/
@Bean
public MyRealm createMyRealm() {
MyRealm myRealm = new MyRealm();
log.info("自定義realm");
return myRealm;
}
自定義加密
儲存使用者時
使用者密碼 -> 加密 -> 儲存到資料庫
加密方法
/**
* 散列次數
*/
public static final int HASH_ITERATIONS = ;
/**
* @description: 加密密碼
* @author cheng
* @dateTime 2018/4/23 15:01
*/
public static String encrypt(String password, String salt) {
Md5Hash md5Hash = new Md5Hash(password, salt, HASH_ITERATIONS);
return md5Hash.toString();
}
使用者認證時
使用者密碼 -> 加密 -> 認證
修改ShiroConfig中自定義Realm配置
/**
* @description:自定義realm
* @author cheng
* @dateTime 2018/4/18 15:44
*/
@Bean
public MyRealm createMyRealm() {
// 加密相關
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
// 雜湊演算法
hashedCredentialsMatcher.setHashAlgorithmName(ShiroUtil.HASH_ALGORITHM_NAME);
// 散列次數
hashedCredentialsMatcher.setHashIterations(ShiroUtil.HASH_ITERATIONS);
MyRealm myRealm = new MyRealm();
myRealm.setCredentialsMatcher(hashedCredentialsMatcher);
log.info("自定義realm");
return myRealm;
}
自定義緩存管理
自定義Cache
package com.ahut.shiro;
import com.ahut.utils.RedisUtil;
import com.ahut.utils.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.util.SerializationUtils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
/**
* @author cheng
* @className: RedisShiroCache
* @description: redis管理shiro緩存
* @dateTime 2018/4/24 16:04
*/
@Slf4j
public class RedisShiroCache<K, V> implements Cache<K, V> {
/**
* @description: 擷取加工後的key的位元組數組
* @author cheng
* @dateTime 2018/4/24 9:57
*/
private byte[] getKey(Object key) {
return (ShiroUtil.SHIRO_CACHE_PREFIX + key).getBytes();
}
/**
* @description: 從緩存中擷取資料
* @author cheng
* @dateTime 2018/4/24 16:09
*/
@Override
public Object get(Object key) throws CacheException {
if (key == null) {
return null;
}
// 序列化鍵
byte[] keyByteArray = getKey(key);
// 從redis中擷取資料
byte[] valueByteArray = RedisUtil.get(keyByteArray);
log.info("從緩存中擷取資料");
// 傳回對應的資料
return valueByteArray == null ? null : SerializationUtils.deserialize(valueByteArray);
}
/**
* @description: 儲存shiro緩存到redis
* @author cheng
* @dateTime 2018/4/24 16:13
*/
@Override
public Object put(Object key, Object value) throws CacheException {
if (key == null || value == null) {
return null;
}
// 序列化
byte[] keyByteArray = getKey(key);
byte[] valueByteArray = SerializationUtils.serialize((Serializable) value);
RedisUtil.set(keyByteArray, valueByteArray);
log.info("儲存shiro緩存到redis");
// 傳回儲存的值
return SerializationUtils.deserialize(valueByteArray);
}
/**
* @description: 從redis中删除
* @author cheng
* @dateTime 2018/4/24 16:19
*/
@Override
public Object remove(Object key) throws CacheException {
if (key == null) {
return null;
}
// 序列化
byte[] keyByteArray = getKey(key);
byte[] valueByteArray = RedisUtil.get(keyByteArray);
// 删除
RedisUtil.del(keyByteArray);
log.info("從redis中删除");
// 傳回删除的資料
return SerializationUtils.deserialize(valueByteArray);
}
/**
* @description: 清空所有的緩存
* @author cheng
* @dateTime 2018/4/24 16:25
*/
@Override
public void clear() throws CacheException {
log.info("清空所有的緩存");
RedisUtil.delByPrefix(ShiroUtil.SHIRO_CACHE_PREFIX);
}
/**
* @description: 緩存個數
* @author cheng
* @dateTime 2018/4/24 16:56
*/
@Override
public int size() {
Set<byte[]> keyByteArraySet = RedisUtil.keys(ShiroUtil.SHIRO_CACHE_PREFIX);
log.info("擷取緩存個數");
return keyByteArraySet.size();
}
/**
* @description: 擷取所有的key
* @author cheng
* @dateTime 2018/4/24 16:59
*/
@Override
public Set keys() {
Set<byte[]> keyByteArraySet = RedisUtil.keys(ShiroUtil.SHIRO_CACHE_PREFIX);
log.info("擷取緩存所有的key");
return keyByteArraySet;
}
/**
* @description: 擷取所有的value
* @author cheng
* @dateTime 2018/4/24 16:59
*/
@Override
public Collection values() {
Set keySet = this.keys();
List<Object> valueList = new ArrayList<>();
for (Object key : keySet) {
byte[] keyByteArray = SerializationUtils.serialize(key);
byte[] valueByteArray = RedisUtil.get(keyByteArray);
valueList.add(SerializationUtils.deserialize(valueByteArray));
}
log.info("擷取緩存所有的value");
return valueList;
}
}
自定義CacheManager
package com.ahut.shiro;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
/**
* @author cheng
* @className: RedisShiroCacheManager
* @description: redis shiro 緩存管理器
* @dateTime 2018/4/24 15:58
*/
public class RedisShiroCacheManager implements CacheManager {
/**
* @description:
* @author cheng
* @dateTime 2018/4/24 16:05
*/
@Override
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
return new RedisShiroCache<K, V>();
}
}
在ShiroConfig中添加配置
/**
* @description: 自定義緩存管理器
* @author cheng
* @dateTime 2018/4/24 15:59
*/
public RedisShiroCacheManager createCacheManager() {
RedisShiroCacheManager redisShiroCacheManager = new RedisShiroCacheManager();
log.info("自定義CacheManager");
return redisShiroCacheManager;
}
自定義會話管理
自定義sessionDao
package com.ahut.shiro;
import com.ahut.utils.RedisUtil;
import com.ahut.utils.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.util.SerializationUtils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
/**
* @author cheng
* @className: RedisShiroSessionDao
* @description: 使用redis管理shiro session
* @dateTime 2018/4/24 9:26
*/
@Slf4j
public class RedisShiroSessionDao extends EnterpriseCacheSessionDAO {
/**
* @description: 擷取加工後的key的位元組數組
* @author cheng
* @dateTime 2018/4/24 9:57
*/
private byte[] getKey(String key) {
return (ShiroUtil.SHIRO_SESSION_PREFIX + key).getBytes();
}
/**
* @description: 更新會話;如更新會話最後通路時間/停止會話/設定逾時時間/設定移除屬性等會調用
* @author cheng
* @dateTime 2018/4/24 9:32
*/
@Override
public void doUpdate(Session session) {
// 判斷session
if (session != null && session.getId() != null) {
byte[] key = getKey(session.getId().toString());
// 序列化session
byte[] value = SerializationUtils.serialize(session);
// 把session資訊存儲到redis中
RedisUtil.set(key, value);
log.info("更新session:{}", session);
}
}
/**
* @description: 删除會話;當會話過期/會話停止(如使用者退出時)會調用
* @author cheng
* @dateTime 2018/4/24 9:31
*/
@Override
protected void doDelete(Session session) {
// 判斷session
if (session != null && session.getId() != null) {
byte[] key = getKey(session.getId().toString());
// 從redis中删除session
RedisUtil.del(key);
log.info("删除session:{}", session);
}
}
/**
* @description: 如DefaultSessionManager在建立完session後會調用該方法;
* 如儲存到關系資料庫/檔案系統/NoSQL資料庫;即可以實作會話的持久化;
* 傳回會話ID;主要此處傳回的ID.equals(session.getId());
* @author cheng
* @dateTime 2018/4/24 9:32
*/
@Override
public Serializable doCreate(Session session) {
// 判斷session
if (session != null) {
// 擷取sessionId
Serializable sessionId = super.doCreate(session);
byte[] key = getKey(sessionId.toString());
// 序列化session
byte[] value = SerializationUtils.serialize(session);
// 把session資訊存儲到redis中
RedisUtil.set(key, value);
// 設定過期時間
RedisUtil.expire(key, ShiroUtil.EXPIRE_SECONDS);
log.info("建立session:{}", session);
return sessionId;
}
return null;
}
/**
* @description: 根據會話ID擷取會話
* @author cheng
* @dateTime 2018/4/24 9:32
*/
@Override
public Session doReadSession(Serializable sessionId) {
if (sessionId != null) {
byte[] key = getKey(sessionId.toString());
byte[] value = RedisUtil.get(key);
// 反序列化session
Session session = (Session) SerializationUtils.deserialize(value);
log.info("擷取session:{}", session);
return session;
}
return null;
}
/**
* @description: 擷取目前所有活躍使用者,如果使用者量多此方法影響性能
* @author cheng
* @dateTime 2018/4/24 9:32
*/
@Override
public Collection<Session> getActiveSessions() {
List<Session> sessionList = new ArrayList<>();
// 從redis從查詢
Set<byte[]> keyByteArraySet = RedisUtil.keys(ShiroUtil.SHIRO_SESSION_PREFIX);
for (byte[] keyByteArray : keyByteArraySet) {
// 反序列化
Session session = (Session) SerializationUtils.deserialize(keyByteArray);
sessionList.add(session);
}
return sessionList;
}
}
在ShiroConfig中配置SessionDao
/**
* @description: 自定義sessionDao
* @author cheng
* @dateTime 2018/4/24 10:47
*/
public RedisShiroSessionDao createRedisShiroSessionDao() {
RedisShiroSessionDao sessionDao = new RedisShiroSessionDao();
// 設定緩存管理器
sessionDao.setCacheManager(createCacheManager());
log.info("自定義sessionDao");
return sessionDao;
}
在ShiroConfig中自定義Shiro session cookie資訊
/**
* @description: 自定義shiro session cookie
* @author cheng
* @dateTime 2018/4/24 11:09
*/
public SimpleCookie createSessionIdCookie() {
SimpleCookie simpleCookie = new SimpleCookie(ShiroUtil.SESSIONID_COOKIE_NAME);
// 保證該系統不會受到跨域的腳本操作攻擊
simpleCookie.setHttpOnly(true);
// 定義Cookie的過期時間,機關為秒,如果設定為-1表示浏覽器關閉,則Cookie消失
simpleCookie.setMaxAge(-);
log.info("自定義SessionIdCookie");
return simpleCookie;
}
在ShiroConfig中配置SessionManager
/**
* @description: 自定義sessionManager
* @author cheng
* @dateTime 2018/4/24 10:37
*/
public SessionManager createMySessionManager() {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
// 自定義sessionDao
sessionManager.setSessionDAO(createRedisShiroSessionDao());
// session的失效時長,機關是毫秒
sessionManager.setGlobalSessionTimeout(ShiroUtil.GLOBAL_SESSION_TIMEOUT);
// 删除失效的session
sessionManager.setDeleteInvalidSessions(true);
// 所有的session一定要将id設定到Cookie之中,需要提供有Cookie的操作模版
sessionManager.setSessionIdCookie(createSessionIdCookie());
// 定義sessionIdCookie模版可以進行操作的啟用
sessionManager.setSessionIdCookieEnabled(true);
log.info("配置sessionManager");
return sessionManager;
}
自定義記住我
在ShiroConfig中自定義記住我cookie
/**
* @description: 記住我cookie
* @author cheng
* @dateTime 2018/4/24 15:39
*/
public SimpleCookie createRemeberMeCookie() {
SimpleCookie simpleCookie = new SimpleCookie(ShiroUtil.REMEBER_ME_COOKIE_NAME);
// 保證該系統不會受到跨域的腳本操作攻擊
simpleCookie.setHttpOnly(true);
// 定義Cookie的過期時間,機關為秒,如果設定為-1表示浏覽器關閉,則Cookie消失
simpleCookie.setMaxAge();
log.info("自定義RemeberMeCookie");
return simpleCookie;
}
在ShiroConfig中配置RememberMeManager
/**
* @description: 自定義記住我
* @author cheng
* @dateTime 2018/4/24 15:35
*/
public CookieRememberMeManager createRememberMeManager() {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
// 設定記住我的cookie
cookieRememberMeManager.setCookie(createRemeberMeCookie());
log.info("配置RemeberMeManager");
return cookieRememberMeManager;
}
登入時,使用記住我
package com.ahut.serviceImpl;
import com.ahut.common.ApiResponse;
import com.ahut.entity.User;
import com.ahut.service.LoginService;
import com.ahut.service.UserService;
import com.ahut.utils.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
/**
* @author cheng
* @className: LoginServiceImpl
* @description:
* @dateTime 2018/4/19 9:21
*/
@Service
@Transactional
@Slf4j
public class LoginServiceImpl implements LoginService {
/**
* 使用者業務邏輯
*/
@Autowired
private UserService userService;
/**
* @description: 登入
* @author cheng
* @dateTime 2018/4/19 9:21
*/
@Override
public ApiResponse login(String userAccount, String userPassword) {
// 擷取目前使用者
Subject subject = SecurityUtils.getSubject();
// 自己建立令牌
UsernamePasswordToken token = new UsernamePasswordToken(userAccount, userPassword);
// 目前登入使用者資訊
User user = null;
// 提示資訊
String msg = null;
try {
// 記住我
token.setRememberMe(true);
subject.login(token);
// 使用者認證成功,擷取目前使用者
user = ShiroUtil.getCurrentUser();
// 完成認證的後續操作
// 修改使用者資訊
user.setLastLoginTime(new Date());
userService.updateUser(user);
msg = "使用者登入成功";
return ApiResponse.createSuccessResponse(msg, user);
} catch (UnknownAccountException e) {
msg = "使用者賬号不存在";
log.warn(msg, e);
} catch (LockedAccountException e) {
msg = "使用者賬号被鎖定";
log.warn(msg, e);
} catch (DisabledAccountException e) {
msg = "使用者賬号被禁用";
log.warn(msg, e);
} catch (IncorrectCredentialsException e) {
msg = "使用者密碼錯誤";
log.warn(msg, e);
}
// 使用者認證失敗,删除目前使用者
ShiroUtil.removeCurrentUser();
return ApiResponse.createFailResponse(msg);
}
}
完整的ShiroConfig配置
package com.ahut.config;
import com.ahut.shiro.MyRealm;
import com.ahut.shiro.RedisShiroCacheManager;
import com.ahut.shiro.RedisShiroSessionDao;
import com.ahut.utils.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
/**
* @author cheng
* @className: ShiroConfig
* @description: shiro配置
* @dateTime 2018/4/18 15:38
*/
@Configuration
@Slf4j
public class ShiroConfig {
/**
* @description:自定義realm
* @author cheng
* @dateTime 2018/4/18 15:44
*/
@Bean
public MyRealm createMyRealm() {
// 加密相關
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
// 雜湊演算法
hashedCredentialsMatcher.setHashAlgorithmName(ShiroUtil.HASH_ALGORITHM_NAME);
// 散列次數
hashedCredentialsMatcher.setHashIterations(ShiroUtil.HASH_ITERATIONS);
MyRealm myRealm = new MyRealm();
myRealm.setCredentialsMatcher(hashedCredentialsMatcher);
log.info("自定義realm");
return myRealm;
}
/**
* @description: 自定義sessionDao
* @author cheng
* @dateTime 2018/4/24 10:47
*/
public RedisShiroSessionDao createRedisShiroSessionDao() {
RedisShiroSessionDao sessionDao = new RedisShiroSessionDao();
// 設定緩存管理器
sessionDao.setCacheManager(createCacheManager());
log.info("自定義sessionDao");
return sessionDao;
}
/**
* @description: 自定義shiro session cookie
* @author cheng
* @dateTime 2018/4/24 11:09
*/
public SimpleCookie createSessionIdCookie() {
SimpleCookie simpleCookie = new SimpleCookie(ShiroUtil.SESSIONID_COOKIE_NAME);
// 保證該系統不會受到跨域的腳本操作攻擊
simpleCookie.setHttpOnly(true);
// 定義Cookie的過期時間,機關為秒,如果設定為-1表示浏覽器關閉,則Cookie消失
simpleCookie.setMaxAge(-);
log.info("自定義SessionIdCookie");
return simpleCookie;
}
/**
* @description: 自定義sessionManager
* @author cheng
* @dateTime 2018/4/24 10:37
*/
public SessionManager createMySessionManager() {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
// 自定義sessionDao
sessionManager.setSessionDAO(createRedisShiroSessionDao());
// session的失效時長,機關是毫秒
sessionManager.setGlobalSessionTimeout(ShiroUtil.GLOBAL_SESSION_TIMEOUT);
// 删除失效的session
sessionManager.setDeleteInvalidSessions(true);
// 所有的session一定要将id設定到Cookie之中,需要提供有Cookie的操作模版
sessionManager.setSessionIdCookie(createSessionIdCookie());
// 定義sessionIdCookie模版可以進行操作的啟用
sessionManager.setSessionIdCookieEnabled(true);
log.info("配置sessionManager");
return sessionManager;
}
/**
* @description: 記住我cookie
* @author cheng
* @dateTime 2018/4/24 15:39
*/
public SimpleCookie createRemeberMeCookie() {
SimpleCookie simpleCookie = new SimpleCookie(ShiroUtil.REMEBER_ME_COOKIE_NAME);
// 保證該系統不會受到跨域的腳本操作攻擊
simpleCookie.setHttpOnly(true);
// 定義Cookie的過期時間,機關為秒,如果設定為-1表示浏覽器關閉,則Cookie消失
simpleCookie.setMaxAge();
log.info("自定義RemeberMeCookie");
return simpleCookie;
}
/**
* @description: 自定義記住我
* @author cheng
* @dateTime 2018/4/24 15:35
*/
public CookieRememberMeManager createRememberMeManager() {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
// 設定記住我的cookie
cookieRememberMeManager.setCookie(createRemeberMeCookie());
log.info("配置RemeberMeManager");
return cookieRememberMeManager;
}
/**
* @description: 自定義緩存管理器
* @author cheng
* @dateTime 2018/4/24 15:59
*/
public RedisShiroCacheManager createCacheManager() {
RedisShiroCacheManager redisShiroCacheManager = new RedisShiroCacheManager();
log.info("自定義CacheManager");
return redisShiroCacheManager;
}
/**
* @description: 注意方法傳回值SecurityManager為org.apache.shiro.mgt.SecurityManager, 不要導錯包
* @author cheng
* @dateTime 2018/4/18 15:48
*/
public SecurityManager createSecurityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 自定義realm
securityManager.setRealm(createMyRealm());
// 自定義sessionManager
securityManager.setSessionManager(createMySessionManager());
// 自定義rememberMeManager
securityManager.setRememberMeManager(createRememberMeManager());
// 自定義cacheManager
securityManager.setCacheManager(createCacheManager());
log.info("配置rsecurityManager");
return securityManager;
}
/**
* @description: shiro web過濾器
* @author cheng
* @dateTime 2018/4/18 15:50
*/
@Bean
public ShiroFilterFactoryBean createShiroFilter() {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(createSecurityManager());
// 如果不設定預設會自動尋找Web工程根目錄下的"/login.jsp"頁面
shiroFilterFactoryBean.setLoginUrl("/v1/toLoginPage");
// 過濾器
Map<String, String> filterChainDefinitionMap = new HashMap<>();
// 配置不會被過濾的連結 順序判斷
// 過慮器鍊定義,從上向下順序執行,一般将/**放在最下邊
// 使用者注冊匿名通路
filterChainDefinitionMap.put("/v1/users/", "anon");
// 管理者登入頁面
filterChainDefinitionMap.put("/v1/toLoginPage", "anon");
// 管理者登入
filterChainDefinitionMap.put("/v1/login", "anon");
// 對靜态資源設定匿名通路
// anon:所有url都都可以匿名通路
filterChainDefinitionMap.put("/static/**", "anon");
// authc:所有url都必須認證通過才可以通路
filterChainDefinitionMap.put("/**", "anon");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
}