您好,登錄后才能下訂單哦!
本文源碼:GitHub·點這里 || GitEE·點這里
Apache Shiro是一個強大且易用的Java安全框架,執行身份驗證、授權、密碼和會話管理。作為一款安全框架Shiro的設計相當巧妙。Shiro的應用不依賴任何容器,它不僅可以在JavaEE下使用,還可以應用在JavaSE環境中。
1)Subject:認證主體
代表當前系統的使用者,就是用戶,在Shiro的認證中,認證主體通常就是userName和passWord,或者其他用戶相關的唯一標識。
2)SecurityManager:安全管理器
Shiro架構中最核心的組件,通過它可以協調其他組件完成用戶認證和授權。實際上,SecurityManager就是Shiro框架的控制器。
3)Realm:域對象
定義了訪問數據的方式,用來連接不同的數據源,如:關系數據庫,配置文件等等。
Shiro自己不維護用戶和權限,通過Subject用戶主體和Realm域對象的注入,完成用戶的認證和授權。
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
@Configuration
public class ShiroConfig {
/**
* Session Manager:會話管理
* 即用戶登錄后就是一次會話,在沒有退出之前,它的所有信息都在會話中;
* 會話可以是普通JavaSE環境的,也可以是如Web環境的;
*/
@Bean("sessionManager")
public SessionManager sessionManager(){
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
//設置session過期時間
sessionManager.setGlobalSessionTimeout(60 * 60 * 1000);
sessionManager.setSessionValidationSchedulerEnabled(true);
// 去掉shiro登錄時url里的JSESSIONID
sessionManager.setSessionIdUrlRewritingEnabled(false);
return sessionManager;
}
/**
* SecurityManager:安全管理器
*/
@Bean("securityManager")
public SecurityManager securityManager(UserRealm userRealm, SessionManager sessionManager) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setSessionManager(sessionManager);
securityManager.setRealm(userRealm);
return securityManager;
}
/**
* ShiroFilter是整個Shiro的入口點,用于攔截需要安全控制的請求進行處理
*/
@Bean("shiroFilter")
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
shiroFilter.setSecurityManager(securityManager);
shiroFilter.setLoginUrl("/userLogin");
shiroFilter.setUnauthorizedUrl("/");
Map<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/userLogin", "anon");
shiroFilter.setFilterChainDefinitionMap(filterMap);
return shiroFilter;
}
/**
* 管理Shiro中一些bean的生命周期
*/
@Bean("lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
/**
* 掃描上下文,尋找所有的Advistor(通知器)
* 將這些Advisor應用到所有符合切入點的Bean中。
*/
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
proxyCreator.setProxyTargetClass(true);
return proxyCreator;
}
/**
* 匹配所有加了 Shiro 認證注解的方法
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
}
@Component
public class UserRealm extends AuthorizingRealm {
@Resource
private SysUserMapper sysUserMapper ;
@Resource
private SysMenuMapper sysMenuMapper ;
/**
* 授權(驗證權限時調用)
* 獲取用戶權限集合
*/
@Override
public AuthorizationInfo doGetAuthorizationInfo
(PrincipalCollection principals) {
SysUserEntity user = (SysUserEntity)principals.getPrimaryPrincipal();
if(user == null) {
throw new UnknownAccountException("賬號不存在");
}
List<String> permsList;
//默認用戶擁有最高權限
List<SysMenuEntity> menuList = sysMenuMapper.selectList();
permsList = new ArrayList<>(menuList.size());
for(SysMenuEntity menu : menuList){
permsList.add(menu.getPerms());
}
//用戶權限列表
Set<String> permsSet = new HashSet<>();
for(String perms : permsList){
if(StringUtils.isEmpty(perms)){
continue;
}
permsSet.addAll(Arrays.asList(perms.trim().split(",")));
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setStringPermissions(permsSet);
return info;
}
/**
* 認證(登錄時調用)
* 驗證用戶登錄
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken authToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken)authToken;
//查詢用戶信息
SysUserEntity user = sysUserMapper.selectOne(token.getUsername());
//賬號不存在
if(user == null) {
throw new UnknownAccountException("賬號或密碼不正確");
}
//賬號鎖定
if(user.getStatus() == 0){
throw new LockedAccountException("賬號已被鎖定,請聯系管理員");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo
(user, user.getPassword(),
ByteSource.Util.bytes(user.getSalt()),
getName());
return info;
}
@Override
public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
shaCredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);
shaCredentialsMatcher.setHashIterations(ShiroUtils.hashIterations);
super.setCredentialsMatcher(shaCredentialsMatcher);
}
}
public class ShiroUtils {
/** 加密算法 */
public final static String hashAlgorithmName = "SHA-256";
/** 循環次數 */
public final static int hashIterations = 16;
public static String sha256(String password, String salt) {
return new SimpleHash(hashAlgorithmName, password, salt, hashIterations).toString();
}
// 獲取一個測試賬號 admin
public static void main(String[] args) {
// 3743a4c09a17e6f2829febd09ca54e627810001cf255ddcae9dabd288a949c4a
System.out.println(sha256("admin","123")) ;
}
/**
* 獲取會話
*/
public static Session getSession() {
return SecurityUtils.getSubject().getSession();
}
/**
* Subject:主體,代表了當前“用戶”
*/
public static Subject getSubject() {
return SecurityUtils.getSubject();
}
public static SysUserEntity getUserEntity() {
return (SysUserEntity)SecurityUtils.getSubject().getPrincipal();
}
public static Long getUserId() {
return getUserEntity().getUserId();
}
public static void setSessionAttribute(Object key, Object value) {
getSession().setAttribute(key, value);
}
public static Object getSessionAttribute(Object key) {
return getSession().getAttribute(key);
}
public static boolean isLogin() {
return SecurityUtils.getSubject().getPrincipal() != null;
}
public static void logout() {
SecurityUtils.getSubject().logout();
}
}
@RestControllerAdvice
public class ShiroException {
@ExceptionHandler(AuthorizationException.class)
public String authorizationException (){
return "抱歉您沒有權限訪問該內容!";
}
@ExceptionHandler(Exception.class)
public String handleException(Exception e){
return "系統異常!";
}
}
@RestController
public class ShiroController {
private static Logger LOGGER = LoggerFactory.getLogger(ShiroController.class) ;
@Resource
private SysMenuMapper sysMenuMapper ;
/**
* 登錄測試
* http://localhost:7011/userLogin?userName=admin&passWord=admin
*/
@RequestMapping("/userLogin")
public void userLogin (
@RequestParam(value = "userName") String userName,
@RequestParam(value = "passWord") String passWord){
try{
Subject subject = ShiroUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord);
subject.login(token);
LOGGER.info("登錄成功");
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 服務器每次重啟請求該接口之前必須先請求上面登錄接口
* http://localhost:7011/menu/list 獲取所有菜單列表
* 權限要求:sys:user:shiro
*/
@RequestMapping("/menu/list")
@RequiresPermissions("sys:user:shiro")
public List list(){
return sysMenuMapper.selectList() ;
}
/**
* 用戶沒有該權限,無法訪問
* 權限要求:ccc:ddd:bbb
*/
@RequestMapping("/menu/list2")
@RequiresPermissions("ccc:ddd:bbb")
public List list2(){
return sysMenuMapper.selectList() ;
}
/**
* 退出測試,退出后沒有任何權限
*/
@RequestMapping("/userLogOut")
public String logout (){
ShiroUtils.logout();
return "success" ;
}
}
1)、登錄后取得權限
http://localhost:7011/userLogin?userName=admin&passWord=admin
2)、訪問有權限接口
http://localhost:7011/menu/list
3)、訪問無權限接口
http://localhost:7011/menu/list2
4)、退出登錄
http://localhost:7011/userLogOut
GitHub地址:知了一笑
https://github.com/cicadasmile/middle-ware-parent
碼云地址:知了一笑
https://gitee.com/cicadasmile/middle-ware-parent
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。