過了4個月才寫第二篇,至關之懶。項目裏須要作一個短信驗證碼的登陸,這裏使用了shiro。html
1.首先是subject:與服務器交互的主體就是subject(用戶),得到subject的方式前端
Subject subject = SecurityUtils.getSubject();
能夠在項目的任何地方使用。web
2.UsernamePasswordToken(令牌),用來驗證用戶名、密碼的登陸方式,若是須要其餘方式認證登陸,能夠自定義token,繼承UsernamePasswordToken類,自定義realm進行實現。ajax
3.realm:繼承AuthorizingRealm,實質上就是與數據庫的鏈接,裏面實現2個方法spring
/**
* 爲當限前登陸的用戶授予角色和權限
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
/**
* 驗證當前登陸的用戶
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
return null;
}
上面是角色和權限的驗證,下面是token的驗證,即登陸驗證。數據庫
4.調用的方法:apache
//登陸
subject.login(token);
5.邏輯:⑴接收前端jsp或html傳來的手機號和短信驗證碼,放到token中json
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