登錄驗證:
LoginController:(LoginController.java)
@ResponseBody @RequestMapping(value="/login",method=RequestMethod.POST) public ResponseResult login(User user, HttpServletRequest request) { ResponseResult responseResult = new ResponseResult(ResponseResult.FAILURECODE,"登陸失敗"); String loginName = user.getLoginName(); String passWord = user.getPassWord(); String eccodePassWord = MD5Operation.getEncryptedPwd(passWord); /*調用shiro判斷當前用戶是否是系統用戶*/ //得到當前用戶 Subject subject = SecurityUtils.getSubject(); //判斷是否登錄,如果未登錄,則登錄 if (!subject.isAuthenticated()) { //創建用戶名/密碼驗證Token, shiro是將用戶錄入的登錄名和密碼(未加密)封裝到uPasswordToken對象中 UsernamePasswordToken uPasswordToken = new UsernamePasswordToken(loginName,eccodePassWord); //自動調用AuthRealm.doGetAuthenticationInfo try { //執行登錄,如果登錄未成功,則捕獲相應的異常 subject.login(uPasswordToken); responseResult.setMsg("登錄成功"); responseResult.setCode(ResponseResult.SUCCESSCODE); }catch (Exception e) { // 捕獲異常 } } /*寫seesion,保存當前user對象*/ //從shiro中獲取當前用戶 User sUser = (User)subject.getPrincipal(); subject.getSession().setAttribute("sUser", sUser); return responseResult; }
ShiroAuthorizingRealm:自定義Realm(ShiroAuthorizingRealm.java)
public class ShiroAuthorizingRealm extends AuthorizingRealm { private static final Logger logger = Logger.getLogger(ShiroAuthorizingRealm.class); //注入用戶管理對象 @Autowired private UserService userService; public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { // TODO 自動生成的方法存根 return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken uPasswordToken) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) uPasswordToken; String loginName = upToken.getUsername(); String passWord = String.valueOf(upToken.getPassword()); User user = null; try { user = userService.findUserByLoginName(loginName); } catch(Exception ex) { logger.warn("獲取用戶失敗\n" + ex.getMessage()); } if (user == null) { logger.warn("用戶不存在"); throw new UnknownAccountException("用戶不存在"); } else if (!passWord.equals(user.getPassWord())) { logger.warn("密碼錯誤"); throw new UnknownAccountException("密碼錯誤"); } logger.info("用戶【" + loginName + "】登錄成功"); AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user, user.getPassWord(), user.getUserName()); Subject subject1 = SecurityUtils.getSubject(); if (null != subject1) { Session session = subject1.getSession(); if (null != session) { session.setAttribute("currentUser", user); } } return authcInfo; } }
shiro.xml配置文件:(spring-shiro.xml)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 緩存管理器 使用Ehcache實現 --> <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml" /> </bean> <!-- Shiro的Web過濾器 --> <!-- 此bean要被web.xml引用,和web.xml中的filtername同名 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/system/login" /> <property name="unauthorizedUrl" value="/" /> <property name="filterChainDefinitions"> <value> /system/login = anon </value> </property> </bean> <!-- 安全管理器 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="dbRealm" /> <property name="cacheManager" ref="cacheManager"/> </bean> <!-- 自定義realm --> <bean id="dbRealm" class="lee.system.school.shiro.ShiroAuthorizingRealm"> <property name="userService" ref="userService"/> </bean> <bean id="userService" class="lee.system.school.service.impl.UserService" /> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> </beans>
web.xml:(web.xml)
<!-- 加載spring容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml,classpath:spring-mybatis.xml,classpath:spring-shiro.xml</param-value> </context-param> <!-- 設置監聽器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Shiro配置(需要 ContextLoaderListener ) --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
ResponseResult類:(ResponseResult.java)
public class ResponseResult { /** * 返回code:成功 */ public final static int SUCCESSCODE = 1; /** * 返回code:失敗 */ public final static int FAILURECODE = 0; private int code; private String msg; private Object data; public ResponseResult(int code) { this.code = code; } public ResponseResult(int code, String msg) { this.code = code; this.msg = msg; } public ResponseResult(int code, String msg, Object data) { this.code = code; this.msg = msg; this.data = data; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
