1.在spring mvc配置文件中添加shiro的配置
<bean id="myRealm" class="com.suninfo.util.MyRealm"/> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myRealm"></property> </bean> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"></property> <property name="successUrl" value="/index.do"></property> <property name="loginUrl" value="/login.do"></property> <property name="unauthorizedUrl" value="/login.do"></property> <property name="filterChainDefinitions"> <value> /login/login.do = anon /login/load.do = anon /images/** = anon /css/** = anon /js/** = anon /lang/** = anon /system/** = anon /**=authc </value> </property> </bean>
2.写一个MyRealm类并继承AuthorizingRealm
package com.suninfo.util; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.apache.shiro.SecurityUtils; 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.session.Session; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; public class MyRealm extends AuthorizingRealm { protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){ // //获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next() // String currentUsername = (String)super.getAvailablePrincipal(principals); // SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); // //实际中可能会像上面注释的那样从数据库取得 // if(null!=currentUsername && "jadyer".equals(currentUsername)){ // //添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色 // simpleAuthorInfo.addRole("admin"); // //添加权限 // simpleAuthorInfo.addStringPermission("admin:manage"); // System.out.println("已为用户[jadyer]赋予了[admin]角色和[admin:manage]权限"); // return simpleAuthorInfo; // }else if(null!=currentUsername && "玄玉".equals(currentUsername)){ // System.out.println("当前用户[玄玉]无授权"); // return simpleAuthorInfo; // } // //若该方法什么都不做直接返回null的话,就会导致任何用户访问/admin/listUser.jsp时都会自动跳转到unauthorizedUrl指定的地址 // //详见applicationContext.xml中的<bean id="shiroFilter">的配置 return null; } /** * 验证当前登录的Subject * @see 经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken)authcToken; System.out.println("验证当前Subject时获取到token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE)); if (token.getUsername() != null) { AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(), this.getName()); this.setSession("currentUser", token.getUsername()); //设置session值 return authcInfo; } return null; } /** * 将一些数据放到ShiroSession中,以便于其它地方使用 * @see */ private void setSession(Object key, Object value){ Subject currentUser = SecurityUtils.getSubject(); if(null != currentUser){ Session session = currentUser.getSession(); System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒"); if(null != session){ session.setAttribute(key, value); } } } }
3.登陆方法
@RequestMapping(value = "login") @ResponseBody public Object login() { String username = (String)this.getParameter("username"); String password = (String)this.getParameter("password"); User user = new User(username, password); user = userService.getUserByPwd(user); if (null == user) { // login failed return this.error2Json(ErrorCode.LOGIN_USREPWD_NOMATCH, "no match!!!"); } this.setSessionAttr(Const.SESSION_LOGGED, true); this.setSessionAttr(Const.SESSION_USER, user); UsernamePasswordToken token = new UsernamePasswordToken(username, password); token.setRememberMe(true); Subject currentUser = SecurityUtils.getSubject(); currentUser.login(token); /* try { Subject subject = this.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(username, password); subject.login(token); } catch (AuthenticationException e) { return this.error2Json(ErrorCode.LOGIN_TOKEN_EXCEPTION, "token exception!!!"); } */ Map map = new HashMap(); map.put("success", true); return map; }