基于Spring框架的Shiro配置

来源:互联网 发布:手机淘宝抢购页面刷新 编辑:程序博客网 时间:2024/05/22 05:14

1、配置applicationContext-shiro.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util"       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.xsd       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">        <property name="securityManager" ref="securityManager"/>        <property name="loginUrl" value="/views/login"/>        <property name="successUrl" value="/views/sysmain"/>        <property name="unauthorizedUrl" value="/views/unauthorized"/>        <property name="filters"><map><entry key="authc" value-ref="formAuthenticationFilter" /></map></property>        <property name="filterChainDefinitions">            <value>                <!-- 静态资源允许访问 -->                /gis/** = anon                /resources/** = anon                /svg/** = anon                /index.jsp = anon                /views/workPlanApp/** = anon                /views/processMonitor/queryProcessStatus = anon                <!-- 登录页允许访问 -->                /views/login = authc                /views/loginmobile = anon                /views/loginbefore = anon                /views/logout = logout                <!-- 其他资源需要认证 -->                /** = user            </value>        </property>    </bean>        <!-- 基于Form表单的身份验证过滤器 -->    <bean id="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">        <property name="usernameParam" value="username" />        <property name="passwordParam" value="password" />        <property name="rememberMeParam" value="rememberMe" />        <property name="loginUrl" value="/views/login" />    </bean>         <!-- 持久cookie设置 --><bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie"><constructor-arg value="rememberMe" /><!--  HttpOnly 属性 指定一个Cookie 是否可通过客户端脚本访问--><property name="httpOnly" value="false" /><property name="maxAge" value="2592000" /><!-- 30天 --></bean><!-- rememberMe管理器 --><bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager"><!-- rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位) --><property name="cipherKey" value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}" /><property name="cookie" ref="rememberMeCookie" /></bean>    <!-- 缓存管理器 使用Ehcache实现 -->    <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">        <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>    </bean>    <!-- 会话DAO -->    <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO"/>    <!-- 会话管理器 -->    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">        <!-- 去掉JSESSION ID-->        <property name="sessionIdUrlRewritingEnabled" value="false" />        <property name="globalSessionTimeout" value="3600000" /><!-- 60min --><property name="deleteInvalidSessions" value="true" /><property name="sessionDAO" ref="sessionDAO" />    </bean>    <!-- 安全管理器 -->    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">        <property name="realms">            <list>                <ref bean="userRealm"/>            </list>        </property>        <!-- cacheManager,集合spring缓存工厂 -->        <property name="cacheManager" ref="shiroEhcacheManager" />        <property name="sessionManager" ref="sessionManager" />        <property name="rememberMeManager" ref="rememberMeManager"/>    </bean></beans>


2、web.xml的配置

<filter>    <filter-name>shiroFilter</filter-name>    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>    <async-supported>true</async-supported>    <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><filter-mapping><filter-name>shiroFilter</filter-name><url-pattern>/*</url-pattern><dispatcher>REQUEST</dispatcher></filter-mapping>

3、UserRealm.java的代码

package com.accenture.icc.security;import java.util.Collection;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.authz.AuthorizationInfo;import org.apache.shiro.authz.SimpleAuthorizationInfo;import org.apache.shiro.realm.AuthorizingRealm;import org.apache.shiro.subject.PrincipalCollection;import org.springframework.stereotype.Component;import com.accenture.icc.systemManager.model.UserNew;import com.accenture.icc.systemManager.service.SystemManagerService;import com.accenture.icc.user.model.User;import com.accenture.icc.user.service.UserInfoService;/** * 用户身份验证,授权 Realm 组件 *  **/@Component(value="userRealm")public class UserRealm extends AuthorizingRealm {    @Resource    private UserInfoService userInfoService;     @Resource    private SystemManagerService systemManagerService;    /**     * 权限检查     */    @Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();String userName = String.valueOf(principals.getPrimaryPrincipal());final UserNew  userNew = systemManagerService.getUserByUserName(userName);/* 根据角色与权限的关联关系查询出所有当前用户的权限(集合) */Collection<String> permissions = systemManagerService.getPermissionListByUserId(userNew.getUser_id());if (null != permissions&&permissions.size()!=0) {authorizationInfo.addStringPermissions(permissions);}/* 根据条件查出当前用户的所有角色(集合) */Collection<String> roles = systemManagerService.getRoleListByUserId(userNew.getUser_id());;if (null != roles&&roles.size()!=0) {authorizationInfo.addRoles(roles);}return authorizationInfo;}    /**     * 登录验证     */    @Override    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {        String username = String.valueOf(token.getPrincipal());        String password = new String((char[]) token.getCredentials());        // 通过数据库进行验证        final User authentication = userInfoService.authentication(new User(username, password));        if (authentication == null) {            throw new AuthenticationException("用户名或密码错误.");        }        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, password, getName());        return authenticationInfo;    }}


4、在LoginController中增加以下代码进行登录验证

Subject subject = SecurityUtils.getSubject();// 身份验证if (user.getPassword() != null) {String password = EncrpytionUtil.encryptString(password());UsernamePasswordToken token = new UsernamePasswordToken(username, password);subject.login(token);}




原创粉丝点击