package org.linlinjava.litemall.admin.shiro;

import com.alibaba.druid.util.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable; public class AdminWebSessionManager extends DefaultWebSessionManager { public static final String LOGIN_TOKEN_KEY = "X-Litemall-Admin-Token";
private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request"; @Override
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
String id = WebUtils.toHttp(request).getHeader(LOGIN_TOKEN_KEY);
if (!StringUtils.isEmpty(id)) {
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
return id;
} else {
return super.getSessionId(request, response);
}
}
}
package org.linlinjava.litemall.admin.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.service.LitemallAdminService;
import org.linlinjava.litemall.db.service.LitemallPermissionService;
import org.linlinjava.litemall.db.service.LitemallRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import java.util.List;
import java.util.Set; public class AdminAuthorizingRealm extends AuthorizingRealm { @Autowired
private LitemallAdminService adminService;
@Autowired
private LitemallRoleService roleService;
@Autowired
private LitemallPermissionService permissionService; @Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
if (principals == null) {
throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
} LitemallAdmin admin = (LitemallAdmin) getAvailablePrincipal(principals);
Integer[] roleIds = admin.getRoleIds();
Set<String> roles = roleService.queryByIds(roleIds);
Set<String> permissions = permissionService.queryByRoleIds(roleIds);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setRoles(roles);
info.setStringPermissions(permissions);
return info;
} @Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token;
String username = upToken.getUsername();
String password = new String(upToken.getPassword()); if (StringUtils.isEmpty(username)) {
throw new AccountException("用户名不能为空");
}
if (StringUtils.isEmpty(password)) {
throw new AccountException("密码不能为空");
} List<LitemallAdmin> adminList = adminService.findAdmin(username);
Assert.state(adminList.size() < 2, "同一个用户名存在两个账户");
if (adminList.size() == 0) {
throw new UnknownAccountException("找不到用户(" + username + ")的帐号信息");
}
LitemallAdmin admin = adminList.get(0); BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
if (!encoder.matches(password, admin.getPassword())) {
throw new UnknownAccountException("找不到用户(" + username + ")的帐号信息");
} return new SimpleAuthenticationInfo(admin, password, getName());
} }
package org.linlinjava.litemall.admin.config;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.linlinjava.litemall.admin.shiro.AdminAuthorizingRealm;
import org.linlinjava.litemall.admin.shiro.AdminWebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn; import java.util.LinkedHashMap;
import java.util.Map; @Configuration
public class ShiroConfig { @Bean
public Realm realm() {
return new AdminAuthorizingRealm();
} @Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
filterChainDefinitionMap.put("/admin/auth/login", "anon");
filterChainDefinitionMap.put("/admin/auth/401", "anon");
filterChainDefinitionMap.put("/admin/auth/index", "anon");
filterChainDefinitionMap.put("/admin/auth/403", "anon");
filterChainDefinitionMap.put("/admin/index/index", "anon"); filterChainDefinitionMap.put("/admin/**", "authc");
shiroFilterFactoryBean.setLoginUrl("/admin/auth/401");
shiroFilterFactoryBean.setSuccessUrl("/admin/auth/index");
shiroFilterFactoryBean.setUnauthorizedUrl("/admin/auth/403");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
} @Bean
public SessionManager sessionManager() { return new AdminWebSessionManager();
} @Bean
public DefaultWebSecurityManager defaultWebSecurityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm());
securityManager.setSessionManager(sessionManager());
return securityManager;
} @Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor =
new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
} @Bean
@DependsOn("lifecycleBeanPostProcessor")
public static DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
creator.setProxyTargetClass(true);
return creator;
}
}
package org.linlinjava.litemall.admin.config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class ShiroExceptionHandler { private final Log logger = LogFactory.getLog(ShiroExceptionHandler.class); @ExceptionHandler(AuthenticationException.class)
@ResponseBody
public Object unauthenticatedHandler(AuthenticationException e) {
logger.warn(e.getMessage(), e);
return ResponseUtil.unlogin();
} @ExceptionHandler(AuthorizationException.class)
@ResponseBody
public Object unauthorizedHandler(AuthorizationException e) {
logger.warn(e.getMessage(), e);
return ResponseUtil.unauthz();
} }

AdminWebSessionManager AdminAuthorizingRealm ShiroConfig ShiroExceptionHandler的更多相关文章

  1. ShiroConfig配置文件无法通过@Value加载yml变量的解决办法

    /** * 配置Shiro生命周期处理器 * 使用springboot整合shiro时,@value注解无法读取application.yml中的配置 *解决方法:将LifecycleBeanPost ...

  2. 解决自定义Shiro.Realm扩展类不能用注解(@Resource或@Autowire)自动装配的问题

    问题产生原因:加载Realm时其他Spring配置文件(xml)尚未加载,导致注入失败. 解决方法:编写一个设置类把注入工作提前完成. package com.xkt.shiro import org ...

  3. Spring boot 基于Spring MVC的Web应用和REST服务开发

    Spring Boot利用JavaConfig配置模式以及"约定优于配置"理念,极大简化了基于Spring MVC的Web应用和REST服务开发. Servlet: package ...

  4. 【shiro】shiro学习笔记1 - 初识shiro

    [TOC] 认证流程 st=>start: Start e=>end: End op1=>operation: 构造SecurityManager环境 op2=>operati ...

  5. 跟开涛老师学shiro -- INI配置

    之前章节我们已经接触过一些INI配置规则了,如果大家使用过如spring之类的IoC/DI容器的话,Shiro提供的INI配置也是非常类似的,即可以理解为是一个IoC/DI容器,但是区别在于它从一个根 ...

  6. 将 Shiro 作为一个许可为基础的应用程序 五:password加密/解密Spring应用

    考虑系统password的安全,眼下大多数系统都不会把password以明文的形式存放到数据库中. 一把会採取下面几种方式对password进行处理 password的存储 "编码" ...

  7. springboot(十四):springboot整合shiro-登录认证和权限管理

    这篇文章我们来学习如何使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公司都会涉及到这方面的需求.在Java领域一般有Spring Security ...

  8. springboot+shiro

    作者:纯洁的微笑 出处:http://www.ityouknow.com/ 这篇文章我们来学习如何使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公 ...

  9. shiro权限控制的简单实现

    权限控制常用的有shiro.spring security,两者相比较,各有优缺点,此篇文章以shiro为例,实现系统的权限控制. 一.数据库的设计 简单的五张表,用户.角色.权限及关联表: CREA ...

随机推荐

  1. Neo4j--节点的增删查改基本用法

    注 node-name 和  label-name node-name 有点句柄的味道. 从面向对象来理解,label-name相当于一个类,node-name相当于这个类的对象. 类比关系型数据库的 ...

  2. composer命令卡慢,使用国内源

    执行composer install.update 和require的时候,遇到卡住不动的情况,可以切换到国内阿里云的源 composer config -g repo.packagist compo ...

  3. 磁盘报No space left on device,但是 df -h 查看磁盘空间没满

    df -h Filesystem Size Used Avail Use% Mounted on /dev/mapper/dev01-root 75G 58G 14G 82% / udev 2.0G ...

  4. redis(一)----配置及安装

    1. redis下载         根据自己操作系统平台下载适合的文件包: https://github.com/MSOpenTech/redis 2. redis安装         (1)解压, ...

  5. JAVA 算法练习(二)

    和上次一样,虽说用 java 语言,但有 c 的基础一样可以看懂哦. 机器人走方格问题Ⅰ 题目概述 有一个XxY的网格,一个机器人只能走格点且只能向右或向下走,要从左上角走到右下角.请设计一个算法,计 ...

  6. 吴裕雄--天生自然ShellX学习笔记:Shell test 命令

    Shell中的 test 命令用于检查某个条件是否成立,它可以进行数值.字符和文件三个方面的测试. 实例演示: num1=100 num2=100 if test $[num1] -eq $[num2 ...

  7. Anaconda 安装 TensorFlow ImportError:DLL加载失败,错误代码为-1073741795

    错误再现 环境: 使用Anaconda 中 conda 4.6.2, Python 3.7版本 Windows 7 操作系统 CPU: Intel i5 原始安装过程 直接在CMD中,安装链接 中的方 ...

  8. ZJNU 2212 - Turn-based game

    Mr.Lee每隔1/x s攻击一次,cpu每隔1/y s攻击一次 因为时间与答案无关,最后只看boss受到了多少次攻击 所以可以在每个人的频率上同时乘以xy 即Mr.Lee每隔y s攻击一次,cpu每 ...

  9. 注册服务和发现服务 Eureka

    来自蚂蚁课堂: 注册服务和发现服务 1.原理如图: 注册中心负载均衡: 实践 注册中心 集群:

  10. 了解SSL证书从HTTPS开始 开发者绕不开的“劫”

    微信小程序上线已经有很长一段时间了,而开发者在接入小程序的过程中,会遇到一些问题,例如小程序要求必须通过HTTPS完成服务端通信,开发者需搭建HTTPS服务,进行 SSL 证书申请.部署,完成HTTP ...