本文主要是一下兩篇文章的綜合,感覺都不錯,拿來報訊學習一下
http://blog.csdn.net/qq_33556185/article/details/51579680
http://blog.csdn.net/u013142781/article/details/50629708
詳解登錄認證及授權--Shiro系列(一)
Apache Shiro 是一個強大而靈活的開源安全框架,它乾淨利落地處理身份認證,授權,企業會話管理和加密。Apache Shiro 的首要目標是易於使用和理解。安全有時候是很複雜的,甚至是痛苦的,但它沒有必要這樣。框架應該儘可能掩蓋複雜的地方,露出一個乾淨而直觀的 API,來簡化開發人員在使他們的應用程序安全上的努力。
以下是你可以用 Apache Shiro 所做的事情:
驗證用戶來覈實他們的身份
對用戶執行訪問控制,如:
判斷用戶是否被分配了一個確定的安全角色。
判斷用戶是否被允許做某事。
在任何環境下使用 Session API,即使沒有 Web 或 EJB 容器。
在身份驗證,訪問控制期間或在會話的生命週期,對事件作出反應。
聚集一個或多個用戶安全數據的數據源,並作爲一個單一的複合用戶“視圖”。
啓用單點登錄(SSO)功能。
併發登錄管理(一個賬號多人登錄作踢人操作)。
…
以及更多——全部集成到緊密結合的易於使用的 API 中。
目前Java領域主流的安全框架有SpringSecurity和Shiro,相比於SpringSecurity,Shiro輕量化,簡單容易上手,且不侷限於Java和Spring;SpringSecurity太笨重了,難以上手,且只能在Spring裏用,所以博主極力推薦Shiro。
spring集成shiro要用到shiro-all-1.2.4.jar
jar包下載地址:http://download.csdn.net/detail/qq_33556185/9540257
第一步:配置shiro.xml文件
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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.2.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
- <!-- Shiro Filter 攔截器相關配置 -->
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
- <!-- securityManager -->
- <property name="securityManager" ref="securityManager" />
- <!-- 登錄路徑 -->
- <property name="loginUrl" value="/toLogin" />
- <!-- 用戶訪問無權限的鏈接時跳轉此頁面 -->
- <property name="unauthorizedUrl" value="/unauthorizedUrl.jsp" />
- <!-- 過濾鏈定義 -->
- <property name="filterChainDefinitions">
- <value>
- /loginin=anon
- /toLogin=anon
- /css/**=anon
- /html/**=anon
- /images/**=anon
- /js/**=anon
- /upload/**=anon
- <!-- /userList=roles[admin] -->
- /userList=authc,perms[/userList]
- /toDeleteUser=authc,perms[/toDeleteUser]
- /** = authc
- </value>
- </property>
- </bean>
- <!-- securityManager -->
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <property name="realm" ref="myRealm" />
- </bean>
- <!-- 自定義Realm實現 -->
- <bean id="myRealm" class="com.core.shiro.realm.CustomRealm" />
- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/"/>
- <property name="suffix" value=".jsp"></property>
- </bean>
- </beans>
anno代表不需要授權即可訪問,對於靜態資源,訪問權限都設置爲anno
authc表示需要登錄纔可訪問
/userList=roles[admin]的含義是要訪問/userList需要有admin這個角色,如果沒有此角色訪問此URL會返回無授權頁面
/userList=authc,perms[/userList]的含義是要訪問/userList需要有/userList的權限,要是沒分配此權限訪問此URL會返回無授權頁面
- <bean id="myRealm" class="com.core.shiro.realm.CustomRealm" />
第二步:在web.xml文件里加載shiro.xml,和加載其他配置文件是一樣的,就不多說了
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- classpath*:/spring/spring-common.xml,
- classpath*:/spring/shiro.xml
- </param-value>
- </context-param>
第三步:配置shiroFilter,所有請求都要先進shiro的代理類
- <!--
- DelegatingFilterProxy類是一個代理類,所有的請求都會首先發到這個filter代理
- 然後再按照"filter-name"委派到spring中的這個bean。
- 在Spring中配置的bean的name要和web.xml中的<filter-name>一樣.
- targetFilterLifecycle,是否由spring來管理bean的生命週期,設置爲true有個好處,可以調用spring後續的bean
- -->
- <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>
- package com.core.shiro.realm;
- import java.util.List;
- import javax.annotation.Resource;
- import org.apache.shiro.authc.AuthenticationException;
- import org.apache.shiro.authc.AuthenticationInfo;
- import org.apache.shiro.authc.AuthenticationToken;
- import org.apache.shiro.authc.SimpleAuthenticationInfo;
- import org.apache.shiro.authc.UsernamePasswordToken;
- 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.springframework.util.StringUtils;
- import com.core.shiro.dao.IPermissionDao;
- import com.core.shiro.dao.IRoleDao;
- import com.core.shiro.dao.IUserDao;
- import com.core.shiro.entity.Permission;
- import com.core.shiro.entity.Role;
- import com.core.shiro.entity.User;
- public class CustomRealm extends AuthorizingRealm{
- @Resource
- private IUserDao userDao;
- @Resource
- private IPermissionDao permissionDao;
- @Resource
- private IRoleDao roleDao;
- /**
- * 添加角色
- * @param username
- * @param info
- */
- private void addRole(String username, SimpleAuthorizationInfo info) {
- List<Role> roles = roleDao.findByUser(username);
- if(roles!=null&&roles.size()>0){
- for (Role role : roles) {
- info.addRole(role.getRoleName());
- }
- }
- }
- /**
- * 添加權限
- * @param username
- * @param info
- * @return
- */
- private SimpleAuthorizationInfo addPermission(String username,SimpleAuthorizationInfo info) {
- List<Permission> permissions = permissionDao.findPermissionByName(username);
- for (Permission permission : permissions) {
- info.addStringPermission(permission.getUrl());//添加權限
- }
- return info;
- }
- /**
- * 獲取授權信息
- */
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
- //用戶名
- String username = (String) principals.fromRealm(getName()).iterator().next();
- //根據用戶名來添加相應的權限和角色
- if(!StringUtils.isEmpty(username)){
- SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
- addPermission(username,info);
- addRole(username, info);
- return info;
- }
- return null;
- }
- /**
- * 登錄驗證
- */
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken ) throws AuthenticationException {
- //令牌——基於用戶名和密碼的令牌
- UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
- //令牌中可以取出用戶名
- String accountName = token.getUsername();
- //讓shiro框架去驗證賬號密碼
- if(!StringUtils.isEmpty(accountName)){
- User user = userDao.findUser(accountName);
- if(user != null){
- return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());
- }
- }
- return null;
- }
- }
- package com.core.shiro.controller;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.shiro.SecurityUtils;
- import org.apache.shiro.authc.AuthenticationException;
- import org.apache.shiro.authc.UsernamePasswordToken;
- import org.apache.shiro.crypto.hash.Md5Hash;
- import org.apache.shiro.subject.Subject;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- @Controller
- public class ShiroAction {
- @RequestMapping("loginin")
- public String login(HttpServletRequest request){
- //當前Subject
- Subject currentUser = SecurityUtils.getSubject();
- //加密(md5+鹽),返回一個32位的字符串小寫
- String salt="("+request.getParameter("username")+")";
- String md5Pwd=new Md5Hash(request.getParameter("password"),salt).toString();
- //傳遞token給shiro的realm
- UsernamePasswordToken token = new UsernamePasswordToken(request.getParameter("username"),md5Pwd);
- try {
- currentUser.login(token);
- return "welcome";
- } catch (AuthenticationException e) {//登錄失敗
- request.setAttribute("msg", "用戶名和密碼錯誤");
- }
- return "login";
- }
- @RequestMapping("toLogin")
- public String toLogin(){
- return "login";
- }
- }
第六步:login頁面 略
login請求調用currentUser.login之後,shiro會將token傳遞給自定義realm,此時realm會先調用doGetAuthenticationInfo(AuthenticationToken authcToken )登錄驗證的方法,驗證通過後會接着調用 doGetAuthorizationInfo(PrincipalCollection principals)獲取角色和權限的方法(授權),最後返回視圖。
當其他請求進入shiro時,shiro會調用doGetAuthorizationInfo(PrincipalCollection principals)去獲取授權信息,若是沒有權限或角色,會跳轉到未授權頁面,若有權限或角色,shiro會放行,ok,此時進入真正的請求方法……
到此shiro的認證及授權便完成了。
Shiro安全框架入門篇(登錄驗證實例詳解與源碼)
一、Shiro框架簡單介紹
Apache Shiro是Java的一個安全框架,旨在簡化身份驗證和授權。Shiro在JavaSE和JavaEE項目中都可以使用。它主要用來處理身份認證,授權,企業會話管理和加密等。Shiro的具體功能點如下:
(1)身份認證/登錄,驗證用戶是不是擁有相應的身份;
(2)授權,即權限驗證,驗證某個已認證的用戶是否擁有某個權限;即判斷用戶是否能做事情,常見的如:驗證某個用戶是否擁有某個角色。或者細粒度的驗證某個用戶對某個資源是否具有某個權限;
(3)會話管理,即用戶登錄後就是一次會話,在沒有退出之前,它的所有信息都在會話中;會話可以是普通JavaSE環境的,也可以是如Web環境的;
(4)加密,保護數據的安全性,如密碼加密存儲到數據庫,而不是明文存儲;
(5)Web支持,可以非常容易的集成到Web環境;
Caching:緩存,比如用戶登錄後,其用戶信息、擁有的角色/權限不必每次去查,這樣可以提高效率;
(6)shiro支持多線程應用的併發驗證,即如在一個線程中開啓另一個線程,能把權限自動傳播過去;
(7)提供測試支持;
(8)允許一個用戶假裝爲另一個用戶(如果他們允許)的身份進行訪問;
(9)記住我,這個是非常常見的功能,即一次登錄後,下次再來的話不用登錄了。
文字描述可能並不能讓猿友們完全理解具體功能的意思。下面我們以登錄驗證爲例,向猿友們介紹Shiro的使用。至於其他功能點,猿友們用到的時候再去深究其用法也不遲。
二、Shiro實例詳細說明
本實例環境:eclipse + maven
本實例採用的主要技術:spring + springmvc + shiro
2.1、依賴的包
假設已經配置好了spring和springmvc的情況下,還需要引入shiro以及shiro集成到spring的包,maven依賴如下:
<!-- Spring 整合Shiro需要的依賴 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.1</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
2.2、定義shiro攔截器
對url進行攔截,如果沒有驗證成功的需要驗證,然後額外給用戶賦予角色和權限。
自定義的攔截器需要繼承AuthorizingRealm並實現登錄驗證和賦予角色權限的兩個方法,具體代碼如下:
package com.luo.shiro.realm;
import java.util.HashSet;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
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 com.luo.util.DecriptUtil;
public class MyShiroRealm extends AuthorizingRealm {
//這裏因爲沒有調用後臺,直接默認只有一個用戶("luoguohui","123456")
private static final String USER_NAME = "luoguohui";
private static final String PASSWORD = "123456";
/*
* 授權
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Set<String> roleNames = new HashSet<String>();
Set<String> permissions = new HashSet<String>();
roleNames.add("administrator");//添加角色
permissions.add("newPage.jhtml"); //添加權限
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
info.setStringPermissions(permissions);
return info;
}
/*
* 登錄驗證
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken authcToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
if(token.getUsername().equals(USER_NAME)){
return new SimpleAuthenticationInfo(USER_NAME, DecriptUtil.MD5(PASSWORD), getName());
}else{
throw new AuthenticationException();
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
2.3、shiro配置文件
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-lazy-init="true">
<description>Shiro Configuration</description>
<!-- Shiro's main business-tier object for web-enabled applications -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myShiroRealm" />
<property name="cacheManager" ref="cacheManager" />
</bean>
<!-- 項目自定義的Realm -->
<bean id="myShiroRealm" class="com.luo.shiro.realm.MyShiroRealm">
<property name="cacheManager" ref="cacheManager" />
</bean>
<!-- Shiro Filter -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/login.jhtml" />
<property name="successUrl" value="/loginsuccess.jhtml" />
<property name="unauthorizedUrl" value="/error.jhtml" />
<property name="filterChainDefinitions">
<value>
/index.jhtml = authc
/login.jhtml = anon
/checkLogin.json = anon
/loginsuccess.jhtml = anon
/logout.json = anon
/** = authc
</value>
</property>
</bean>
<!-- 用戶授權信息Cache -->
<bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />
<!-- 保證實現了Shiro內部lifecycle函數的bean執行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
<!-- AOP式方法級權限檢查 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true" />
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager" />
</bean>
</beans>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
這裏有必要說清楚”shiroFilter” 這個bean裏面的各個屬性property的含義:
(1)securityManager:這個屬性是必須的,沒什麼好說的,就這樣配置就好。
(2)loginUrl:沒有登錄的用戶請求需要登錄的頁面時自動跳轉到登錄頁面,可配置也可不配置。
(3)successUrl:登錄成功默認跳轉頁面,不配置則跳轉至”/”,一般可以不配置,直接通過代碼進行處理。
(4)unauthorizedUrl:沒有權限默認跳轉的頁面。
(5)filterChainDefinitions,對於過濾器就有必要詳細說明一下:
1)Shiro驗證URL時,URL匹配成功便不再繼續匹配查找(所以要注意配置文件中的URL順序,尤其在使用通配符時),故filterChainDefinitions的配置順序爲自上而下,以最上面的爲準
2)當運行一個Web應用程序時,Shiro將會創建一些有用的默認Filter實例,並自動地在[main]項中將它們置爲可用自動地可用的默認的Filter實例是被DefaultFilter枚舉類定義的,枚舉的名稱字段就是可供配置的名稱
3)通常可將這些過濾器分爲兩組:
anon,authc,authcBasic,user是第一組認證過濾器
perms,port,rest,roles,ssl是第二組授權過濾器
注意user和authc不同:當應用開啓了rememberMe時,用戶下次訪問時可以是一個user,但絕不會是authc,因爲authc是需要重新認證的
user表示用戶不一定已通過認證,只要曾被Shiro記住過登錄狀態的用戶就可以正常發起請求,比如rememberMe
說白了,以前的一個用戶登錄時開啓了rememberMe,然後他關閉瀏覽器,下次再訪問時他就是一個user,而不會authc
4)舉幾個例子
/admin=authc,roles[admin] 表示用戶必需已通過認證,並擁有admin角色纔可以正常發起’/admin’請求
/edit=authc,perms[admin:edit] 表示用戶必需已通過認證,並擁有admin:edit權限纔可以正常發起’/edit’請求
/home=user 表示用戶不一定需要已經通過認證,只需要曾經被Shiro記住過登錄狀態就可以正常發起’/home’請求
5)各默認過濾器常用如下(注意URL Pattern裏用到的是兩顆星,這樣才能實現任意層次的全匹配)
/admins/**=anon 無參,表示可匿名使用,可以理解爲匿名用戶或遊客
/admins/user/**=authc 無參,表示需認證才能使用
/admins/user/**=authcBasic 無參,表示httpBasic認證
/admins/user/**=user 無參,表示必須存在用戶,當登入操作時不做檢查
/admins/user/**=ssl 無參,表示安全的URL請求,協議爲https
/admins/user/*=perms[user:add:]
參數可寫多個,多參時必須加上引號,且參數之間用逗號分割,如/admins/user/*=perms[“user:add:,user:modify:*”]
當有多個參數時必須每個參數都通過纔算通過,相當於isPermitedAll()方法
/admins/user/**=port[8081]
當請求的URL端口不是8081時,跳轉到schemal://serverName:8081?queryString
其中schmal是協議http或https等,serverName是你訪問的Host,8081是Port端口,queryString是你訪問的URL裏的?後面的參數
/admins/user/**=rest[user]
根據請求的方法,相當於/admins/user/**=perms[user:method],其中method爲post,get,delete等
/admins/user/**=roles[admin]
參數可寫多個,多個時必須加上引號,且參數之間用逗號分割,如/admins/user/**=roles[“admin,guest”]
當有多個參數時必須每個參數都通過纔算通過,相當於hasAllRoles()方法
上文參考了http://www.cppblog.com/guojingjia2006/archive/2014/05/14/206956.html,更多詳細說明請訪問該鏈接。
2.4、web.xml配置引入對應的配置文件和過濾器
<!-- 讀取spring和shiro配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml,classpath:shiro/spring-shiro.xml</param-value>
</context-param>
<!-- shiro過濾器 -->
<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>*.jhtml</url-pattern>
<url-pattern>*.json</url-pattern>
</filter-mapping>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
2.5、controller代碼
package com.luo.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.druid.support.json.JSONUtils;
import com.luo.errorcode.LuoErrorCode;
import com.luo.exception.BusinessException;
import com.luo.util.DecriptUtil;
@Controller
public class UserController {
@RequestMapping("/index.jhtml")
public ModelAndView getIndex(HttpServletRequest request) throws Exception {
ModelAndView mav = new ModelAndView("index");
return mav;
}
@RequestMapping("/exceptionForPageJumps.jhtml")
public ModelAndView exceptionForPageJumps(HttpServletRequest request) throws Exception {
throw new BusinessException(LuoErrorCode.NULL_OBJ);
}
@RequestMapping(value="/businessException.json", method=RequestMethod.POST)
@ResponseBody
public String businessException(HttpServletRequest request) {
throw new BusinessException(LuoErrorCode.NULL_OBJ);
}
@RequestMapping(value="/otherException.json", method=RequestMethod.POST)
@ResponseBody
public String otherException(HttpServletRequest request) throws Exception {
throw new Exception();
}
//跳轉到登錄頁面
@RequestMapping("/login.jhtml")
public ModelAndView login() throws Exception {
ModelAndView mav = new ModelAndView("login");
return mav;
}
//跳轉到登錄成功頁面
@RequestMapping("/loginsuccess.jhtml")
public ModelAndView loginsuccess() throws Exception {
ModelAndView mav = new ModelAndView("loginsuccess");
return mav;
}
@RequestMapping("/newPage.jhtml")
public ModelAndView newPage() throws Exception {
ModelAndView mav = new ModelAndView("newPage");
return mav;
}
@RequestMapping("/newPageNotAdd.jhtml")
public ModelAndView newPageNotAdd() throws Exception {
ModelAndView mav = new ModelAndView("newPageNotAdd");
return mav;
}
/**
* 驗證用戶名和密碼
* @param String username,String password
* @return
*/
@RequestMapping(value="/checkLogin.json",method=RequestMethod.POST)
@ResponseBody
public String checkLogin(String username,String password) {
Map<String, Object> result = new HashMap<String, Object>();
try{
UsernamePasswordToken token = new UsernamePasswordToken(username, DecriptUtil.MD5(password));
Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()){
//使用shiro來驗證
token.setRememberMe(true);
currentUser.login(token);//驗證角色和權限
}
}catch(Exception ex){
throw new BusinessException(LuoErrorCode.LOGIN_VERIFY_FAILURE);
}
result.put("success", true);
return JSONUtils.toJSONString(result);
}
/**
* 退出登錄
*/
@RequestMapping(value="/logout.json",method=RequestMethod.POST)
@ResponseBody
public String logout() {
Map<String, Object> result = new HashMap<String, Object>();
result.put("success", true);
Subject currentUser = SecurityUtils.getSubject();
currentUser.logout();
return JSONUtils.toJSONString(result);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
上面代碼,我們只需要更多地關注登錄驗證和退出登錄的代碼。
其中DecriptUtil.MD5(password),對密碼進行md5加密解密是我自己寫的工具類DecriptUtil,對應MyShiroRealm裏面的登錄驗證裏面也有對應對應的方法。
另外,BusinessException是我自己封裝的異常類。
最後會提供整個工程源碼供猿友下載,裏面包含了所有的代碼。
2.6、login.jsp代碼
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<script src="<%=request.getContextPath()%>/static/bui/js/jquery-1.8.1.min.js"></script>
</head>
<body>
username: <input type="text" id="username"><br><br>
password: <input type="password" id="password"><br><br>
<button id="loginbtn">登錄</button>
</body>
<script type="text/javascript">
$('#loginbtn').click(function() {
var param = {
username : $("#username").val(),
password : $("#password").val()
};
$.ajax({
type: "post",
url: "<%=request.getContextPath()%>" + "/checkLogin.json",
data: param,
dataType: "json",
success: function(data) {
if(data.success == false){
alert(data.errorMsg);
}else{
//登錄成功
window.location.href = "<%=request.getContextPath()%>" + "/loginsuccess.jhtml";
}
},
error: function(data) {
alert("調用失敗....");
}
});
});
</script>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
2.7、效果演示
(1)如果未登錄前,輸入http://localhost:8080/web_exception_project/index.jhtml會自動跳轉到http://localhost:8080/web_exception_project/login.jhtml。
(2)如果登錄失敗和登錄成功:
(3)如果登錄成功,訪問http://localhost:8080/web_exception_project/index.jhtml就可以到其對應的頁面了。
2.8、源碼下載
http://download.csdn.net/detail/u013142781/9426670
2.9、我遇到的坑
在本實例的調試裏面遇到一個問題,雖然跟shiro沒有關係,但是也跟猿友們分享一下。
就是ajax請求設置了“contentType : “application/json””,導致controller獲取不到username和password這兩個參數。
後面去掉contentType : “application/json”,採用默認的就可以了。
具體原因可以瀏覽博文:http://blog.csdn.net/mhmyqn/article/details/25561535