過了4個月才寫第二篇,相當之懶。項目里需要做一個短信驗證碼的登錄,這里使用了shiro。
1.首先是subject:與服務器交互的主體就是subject(用戶),獲得subject的方式
Subject subject = SecurityUtils.getSubject();
可以在項目的任何地方使用。
2.UsernamePasswordToken(令牌),用來驗證用戶名、密碼的登錄方式,如果需要其他方式認證登錄,可以自定義token,繼承UsernamePasswordToken類,自定義realm進行實現。
3.realm:繼承AuthorizingRealm,實質上就是與數據庫的連接,里面實現2個方法
/**
* 為當限前登錄的用戶授予角色和權限
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
/**
* 驗證當前登錄的用戶
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
return null;
}
上面是角色和權限的驗證,下面是token的驗證,即登錄驗證。
4.調用的方法:
//登錄
subject.login(token);
5.邏輯:⑴接收前端jsp或html傳來的手機號和短信驗證碼,放到token中
String mobile = request.getParameter("mobile");
String code = request.getParameter("code");
UsernamePasswordToken token = new UsernamePasswordToken(mobile, code);
⑵調用登錄方法:subject.login(token);
⑶realm里用當前手機號去查找用戶表里是否有當前手機號的用戶,沒找到或驗證碼不對則手動拋出異常
6.登錄接口
/** * 用戶登錄 * */ @RequestMapping("login") @ResponseBody public String test(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model){ //這句是用來與前端h5進行調試時用的,調試時會有一個ajax跨域的問題 // response.setHeader("Access-Control-Allow-Origin", "*"); String mobile = request.getParameter("mobile"); String code = request.getParameter("code"); ActivityVO activityVO = new ActivityVO(); JsonMapper jsonMapper = new JsonMapper(); //主體,當前狀態為沒有認證的狀態“未認證” Subject subject = SecurityUtils.getSubject(); //創建令牌,將手機號和驗證碼丟進去 UsernamePasswordToken token = new UsernamePasswordToken(mobile, code); //設置rememberMe為true token.setRememberMe(true); UserUser user; try { //登錄 subject.login(token); //登錄成功,則認證成功,rememberMe和這個認證的狀態是互斥的 if (subject.isAuthenticated()){ //獲得session Session subjectSession = subject.getSession(); //去數據里查找當前用戶 user = icUserUserService.findUserUserByMobile(mobile); //將用戶存於session中 subjectSession.setAttribute(CustomActConstans.userSession,user); } activityVO.setCode(1); activityVO.setMsg("登錄成功!"); return jsonMapper.toJson(activityVO); } catch (UnknownAccountException ex) {// 用戶名沒有找到。 activityVO.setCode(-1); activityVO.setMsg("賬號不存在!"); return jsonMapper.toJson(activityVO); } catch (IncorrectCredentialsException ex) {// 用戶名密碼不匹配。 activityVO.setCode(-2); activityVO.setMsg("驗證碼錯誤!"); return jsonMapper.toJson(activityVO); } catch (AuthenticationException e) {//其他異常 activityVO.setCode(-3); activityVO.setMsg("未知錯誤,請刷新頁面重新登錄!"); return jsonMapper.toJson(activityVO); } }
7.realm認證
/** * 為當限前登錄的用戶授予角色和權限 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { return null; } /** * 驗證當前登錄的用戶 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //接收輸入的用戶名 String mobile = (String) token.getPrincipal(); //查看UsernamePasswordToken可知,getCredentials()方法的返回值是char []類型的,所以不能直接轉化成string。 char [] ch = (char[]) token.getCredentials(); //接收輸入的密碼或驗證碼 String password = new String(ch); UserUser user; user = icUserUserService.findUserUserByMobile(mobile) ; if (user != null) { //用戶不為空則到緩存中去取驗證碼,獲取驗證碼后我將驗證碼存入了ehcache緩存,過期時間3分鍾 String cacheCode = (String) CacheUtils.get("codeCache", key); //判斷驗證碼是否正確 if (!cacheCode.equals(password)) { throw new IncorrectCredentialsException(); } AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(mobile, password,null,getName()); return authcInfo; }else { return null; } }
8.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"
default-lazy-init="true">
<description>Shiro security Manager</description>
<!-- 自定義Realm類所在的位置 -->
<bean id="myRealm" class="cn.xxx.xxx.xxx.xxx.ShiroRealm"/>
<!-- 安全管理器 與自定義realm關聯-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"/>
<property name="cacheManager" ref="shiroEhcacheManager"/>
</bean>
<!-- Shiro過濾器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,這個屬性是必須的 -->
<property name="securityManager" ref="securityManager"/>
<!-- 身份認證失敗,則跳轉到登錄頁面的配置 -->
<property name="loginUrl" value="/index.html"/>
<!-- 權限認證失敗,則跳轉到指定頁面 -->
<property name="unauthorizedUrl" value="/unauthorized.jsp"/>
<!-- Shiro連接約束配置,即過濾鏈的定義 -->
<property name="filterChainDefinitions">
<value>
<!--所有接口都不需要認證-->
/*=anon
</value>
</property>
</bean>
<!-- 用戶授權信息Cache, 采用EhCache -->
<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache/ehcache-shiro.xml"/>
</bean>
<!-- 保證實現了Shiro內部lifecycle函數的bean執行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- 開啟Shiro注解 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
</beans>
9.ehcache-shiro.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="shiroCache">
<!--maxElementsInMemory 緩存最大個數。 -->
<defaultCache
maxElementsInMemory="10000"
eternal="true"
timeToIdleSeconds="20"
timeToLiveSeconds="20"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
</ehcache>
10.登錄后設置rememberMe為true,即為讓客戶端瀏覽器記住當前subject的登錄狀態,可以訪問一些user用戶的接口,在下面這個地方配置
<property name="filterChainDefinitions">
<value>
<!--所有接口都不需要認證-->
/*=user
</value>
</property>
rememberMe實際上是通過cookie將subject的信息保存於瀏覽器當中,可以在xml中配置rememberMeCookie的保存策略,它只是表示當前subject曾經來過,並不表示登錄狀態,
subject.isAuthenticated()為true時,才表示當前用戶為登錄狀態
在某些需要authc認證的接口,rememberMe是不能訪問的。項目只是做了一個簡單的登錄,並沒有涉及到角色和權限那一塊,
web.xml中filter配置
<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>
有不對的地方,還望批評指正,感謝!!!
原文鏈接:https://blog.csdn.net/MODjie/article/details/79229658