Shiro+SpringMVC

来源:互联网 发布:淘宝达人申请直播入口 编辑:程序博客网 时间:2024/06/07 03:40

pom.xml

<dependency>    <groupId>org.apache.shiro</groupId>    <artifactId>shiro-core</artifactId>    <version>1.3.2</version></dependency><dependency>    <groupId>org.apache.shiro</groupId>    <artifactId>shiro-web</artifactId>    <version>1.3.2</version></dependency><dependency>    <groupId>org.apache.shiro</groupId>    <artifactId>shiro-spring</artifactId>    <version>1.3.2</version></dependency><dependency>    <groupId>org.apache.shiro</groupId>    <artifactId>shiro-ehcache</artifactId>    <version>1.3.2</version></dependency>


web.xml

<context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath*:applicationContext-mvc.xml,classpath*:applicationContext.xml,classpath*:applicationContext-shiro.xml</param-value></context-param><filter>    <filter-name>shiroFilter</filter-name>    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>    <init-param>        <!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->        <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>


ehcache.xml

<?xml version="1.0" encoding="UTF-8"?><ehcache name="shiroCache">    <diskStore path="java.io.tmpdir" />    <defaultCache            maxEntriesLocalHeap="2000"            eternal="false"            timeToIdleSeconds="1800"            timeToLiveSeconds="0"            overflowToDisk="false"            statistics="true"            diskPersistent="false"            diskExpiryThreadIntervalSeconds="120"/></ehcache>


applicationContext-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-4.2.xsd"><!-- 安全管理器 --><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><!-- 设置自定义realm --><property name="realm" ref="shiroDbRealm"/><!-- 将缓存管理器交给安全管理器 --><property name="cacheManager" ref="cacheManager"/></bean><!-- Realm实现 --><bean id="shiroDbRealm" class="com.per.util.ShiroDbRealm" ><property name="credentialsMatcher" ref="credentialsMatcher"/></bean><!-- 缓存管理器 使用Ehcache实现 --><bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"><property name="cacheManagerConfigFile" value="classpath:ehcache.xml" /></bean><!-- 数据库保存的密码是使用MD5算法加密的,所以这里需要配置一个密码匹配对象 --><bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"><property name="hashAlgorithmName" value="MD5"/></bean><!-- Shiro的Web过滤器 --><bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"><!-- Shiro的核心安全接口,这个属性是必须的 --><property name="securityManager" ref="securityManager" /><!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 --><property name="loginUrl" value="/user/login.do" /><!-- 登录成功后要跳转的连接 --><!-- <property name="successUrl" value="/system/main"/> --><!-- 用户访问未对其授权的资源时,所显示的连接 --><property name="unauthorizedUrl" value="/user/login.do" /><!-- Shiro连接约束配置,即过滤链的定义 --><!-- anon表示此地址不需要任何权限即可访问 --><!-- perms[user:query]表示访问此连接需要权限为user:query的用户 --><!-- roles[manager]表示访问此连接需要用户的角色为manager --><!-- authc 要权限才可访问 --><property name="filterChainDefinitions"><value>/user/login.do = anon/cust/list.do = authc/cust/chancelist.do = roles[manager]</value></property></bean><!-- 保证实现了Shiro内部lifecycle函数的bean执行 --><bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /></beans>


ShiroDbRealm.java

import com.htjx.crm.model.Empl;import com.htjx.crm.model.Role;import com.htjx.crm.model.SysPermission;import com.htjx.crm.service.EmplService;import com.htjx.crm.service.RoleService;import org.apache.shiro.authc.*;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 javax.annotation.Resource;import java.util.HashSet;import java.util.List;import java.util.Set;/** * Created by yangbin on 2017/5/13. */public class ShiroDbRealm extends AuthorizingRealm {    @Resource    private EmplService emplService;    @Resource    private RoleService roleService;    /**     * 提供用户信息返回权限信息     * @param principalCollection     * @return     */    @Override    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {        Empl user = (Empl)principalCollection.getPrimaryPrincipal();        Role role = emplService.getRoleByEmplId(user.getId());        Set<String> sysPermissionSet = new HashSet<>();            List<SysPermission> permissionList = roleService.getPermissionListByRoleId(role.getId());            permissionList.forEach(permission -> {                sysPermissionSet.add(permission.getUrl());            });        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(sysPermissionSet);        return simpleAuthorizationInfo;    }    /**     * 提供账户信息返回认证信息     * @param authenticationToken     * @return     * @throws AuthenticationException     */    @Override    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;        Empl user = emplService.checkUserName(token.getUsername());        if (user == null) {            // 用户名不存在抛出异常            throw new UnknownAccountException();        }        if (0 == user.getStatus()) {            // 用户被管理员锁定抛出异常            throw new LockedAccountException();        }        // 数据库数据库中的密码只做了一次md5,因此不传salt        return new SimpleAuthenticationInfo(user, user.getUserPwd(), user.getUserName());    }}


LoginController.java

import com.per.crm.constants.UserConstants;import com.per.crm.service.EmplService;import com.per.crm.util.BaseController;import com.per.crm.util.MD5Utils;import com.per.crm.vo.EmplVo;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.subject.Subject;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import javax.annotation.Resource;@Controller@RequestMapping("/user")public class LoginController extends BaseController {private Logger logger = LoggerFactory.getLogger(LoginController.class);@Resourceprivate EmplService emplService;@RequestMapping(value = "/login", method = RequestMethod.POST)public String login(String userName, String pwd) {EmplVo empl = emplService.emplLogin(userName, MD5Utils.toMD5(pwd));Subject subject = SecurityUtils.getSubject();UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName, pwd);usernamePasswordToken.setRememberMe(true);subject.login(usernamePasswordToken);// 将用户信息放入sessionsession.setAttribute(UserConstants.SESSION_KEY_USER_ID, empl);return "redirect:/cust/list.do";}}


0 0
原创粉丝点击