同樣,忙於校招,忙於提升自己,忙於項目。直接把項目中的代碼拿來分享給大家。
一、配置ShiroFilter
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/spring-*.xml,
classpath:spring/spring-shiro.xml
</param-value>
</context-param>
<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>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
二、配置spring-shiro.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 配置shiro的過濾器工廠類,id- shiroFilter要和我們在web.xml中配置的過濾器一致 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 調用我們配置的權限管理器 -->
<property name="securityManager" ref="securityManager" />
<!-- 配置我們的登錄請求地址 -->
<property name="loginUrl" value="/login" />
<!-- 配置我們在登錄頁登錄成功後的跳轉地址,如果你訪問的是非/login地址,則跳到您訪問的地址,html已經有解析器 -->
<property name="successUrl" value="/index" />
<!-- TODO 需要403頁面地址纔可配置: 如果您請求的資源不再您的權限範圍,則跳轉到/403請求地址 -->
<property name="unauthorizedUrl" value="/unauthorized" />
<property name="filters">
<util:map>
<entry key="logout" value-ref="logoutFilter" />
</util:map>
</property>
<!-- 權限配置 -->
<property name="filterChainDefinitions">
<value>
<!-- anon表示此地址不需要任何權限即可訪問 -->
/**/**=anon
/index=anon
/login=anon
/vcode=anon
/icon/**=anon
/js/**=anon
/static/** = anon
/lg=anon
<!--所有的請求(除去配置的靜態資源請求或請求地址爲anon的請求)都要通過登錄驗證,如果未登錄則跳到/login -->
/** = authc
</value>
</property>
</bean>
<!-- TODO 需要403頁面地址纔可配置 -->
<bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">
<property name="redirectUrl" value="/login" />
</bean>
<!-- <!– 憑證匹配器 –>-->
<!-- <bean id="passwordMatcher" class="org.apache.shiro.authc.credential.PasswordMatcher">-->
<!-- <property name="passwordService" ref="passwordService" />-->
<!-- </bean>-->
<!-- <bean id="passwordService"-->
<!-- class="org.apache.shiro.authc.credential.DefaultPasswordService">-->
<!-- <property name="hashService" ref="hashService"></property>-->
<!-- <property name="hashFormat" ref="hashFormat"></property>-->
<!-- <property name="hashFormatFactory" ref="hashFormatFactory"></property>-->
<!-- </bean>-->
<!-- <bean id="hashService" class="org.apache.shiro.crypto.hash.DefaultHashService"></bean>-->
<!-- <bean id="hashFormat" class="org.apache.shiro.crypto.hash.format.Shiro1CryptFormat"></bean>-->
<!-- <bean id="hashFormatFactory"-->
<!-- class="org.apache.shiro.crypto.hash.format.DefaultHashFormatFactory">-->
<!-- </bean>-->
<!-- <!– 會話ID生成器 –>-->
<!-- <bean id="sessionIdGenerator"-->
<!-- class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" />-->
<!-- <!– 會話Cookie模板 maxAge=-1表示:關閉瀏覽器立即失效 –>-->
<!-- <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">-->
<!-- <constructor-arg value="sid" />-->
<!-- <property name="httpOnly" value="true" />-->
<!-- <property name="maxAge" value="-1" />-->
<!-- </bean>-->
<!-- <!– 會話DAO –>-->
<!-- <bean id="sessionDAO"-->
<!-- class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">-->
<!-- <property name="sessionIdGenerator" ref="sessionIdGenerator" />-->
<!-- </bean>-->
<!-- <!– 會話驗證調度器,每30分鐘執行一次驗證 ,設定會話超時及保存 –>-->
<!-- <bean name="sessionValidationScheduler"-->
<!-- class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler">-->
<!-- <property name="interval" value="1800000" />-->
<!-- <property name="sessionManager" ref="sessionManager" />-->
<!-- </bean>-->
<!-- <!– 會話管理器 –>-->
<!-- <bean id="sessionManager"-->
<!-- class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">-->
<!-- <!– 全局會話超時時間(單位毫秒),默認30分鐘 –>-->
<!-- <property name="globalSessionTimeout" value="1800000" />-->
<!-- <property name="deleteInvalidSessions" value="true" />-->
<!-- <property name="sessionValidationSchedulerEnabled" value="true" />-->
<!-- <property name="sessionValidationScheduler" ref="sessionValidationScheduler" />-->
<!-- <property name="sessionDAO" ref="sessionDAO" />-->
<!-- <property name="sessionIdCookieEnabled" value="true" />-->
<!-- <property name="sessionIdCookie" ref="sessionIdCookie" />-->
<!-- </bean>-->
<!-- TODO 已解決 需要註冊自定義的Realm,並把密碼匹配器注入,使用註解的方式自動註解會無法正確匹配密碼 已解決-->
<bean id="userRealm" class="com.lanou.web.controller.shiro.UserRealm">
<!-- <property name="credentialsMatcher" ref="passwordMatcher"/>-->
<property name="cachingEnabled" value="false"/>
</bean>
<!-- 安全管理器 作爲filter的成員變量而出現-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm" />
</bean>
<!-- 相當於調用SecurityUtils.setSecurityManager(securityManager) -->
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod"
value="org.apache.shiro.SecurityUtils.setSecurityManager" />
<property name="arguments" ref="securityManager" />
</bean>
<bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />
<!-- 保證實現了Shiro內部lifecycle函數的bean執行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
</beans>
- 編寫Realm完成角色權限分配
import org.apache.shiro.SecurityUtils;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashSet;
import java.util.Set;
public class UserRealm extends AuthorizingRealm {
// 用戶對應的角色信息與權限信息都保存在數據庫中,通過UserService獲取數據
@Autowired
public IUserService userService;
/*
* 這個方法是通過用戶名查詢到當前用戶的角色與權限,然後將這些信息放在simpleAuthorizationInfo中
* 即:提供用戶信息返回權限信息
* 登陸後來走這裏,拿出該用戶的權限和角色,放在info中。
* */
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String username = (String)principalCollection.getPrimaryPrincipal();
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
// 根據用戶名查詢當前用戶擁有的角色
Set<TbRole> roles = userService.findRolesByUsername(username);
Set<String> rolesName = new HashSet<String>();
for (TbRole role:roles) {
rolesName.add(role.getName());
}
// 根據用戶名查詢當前用戶權限
Set<TbPermission> permissions = userService.findPermissionByUsername(username);
Set<String> permissionNames = new HashSet<String>();
for (TbPermission permission : permissions) {
permissionNames.add(String.valueOf(permission.getPermission()));
}
// 將權限名稱提供給info
simpleAuthorizationInfo.setStringPermissions(permissionNames);
// 將角色名稱提供給info
simpleAuthorizationInfo.setRoles(rolesName);
return simpleAuthorizationInfo;
}
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//鑑權
String username = (String)authenticationToken.getPrincipal();
TbUser user = null;
SimpleAuthenticationInfo simpleAuthenticationInfo = null;
try{
user = userService.findByUsername(username);
}catch(Exception e) {
return null;
}
Subject subject = SecurityUtils.getSubject();
subject.getSession().setAttribute("user",user);
//第一個參數是傳入的用戶名(其實是一個principal參數,這個參數以爲着用戶所有認證信息的幾個),第二個是密碼,
//TODO 此處的對象創建沒有鹽值加密過程,可以再構造裏面看得到
simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),getName());
return simpleAuthenticationInfo;
}
}
四、使用註解完成角色權限控制
//用戶登錄後同時獲取用戶的個人信息
@RequestMapping(value = "/findInfo",method = RequestMethod.POST)
@ResponseBody
@RequiresRoles(value = {"student", "teacher"}, logical = Logical.OR) //允許具有老師或學生身份的訪問該接口
public Result findMyInfo(String identifier){
Subject subject = SecurityUtils.getSubject();
TbUser user = (TbUser) subject.getSession().getAttribute("user");
if (user != null) {
if (identifier.equals("student")) {
TbStudentInfo studentInfo = studentInfoService.findStudentInfo(user);
return ResultGenerator.genSuccessResult(studentInfo);
} else {
TbTeacherInfo teacherInfo = teacherInfoService.findTeacherInfoById(user.getId());
System.out.println(teacherInfo.toString());
return ResultGenerator.genSuccessResult(teacherInfo);
}
} else {
return ResultGenerator.genFailResult("未得到該用戶信息,可能原因:未鑑權");
}
}