1、引用maven
<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>
2、实现AuthorizingRealm类
package com.controller; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; 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.authc.UsernamePasswordToken; 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{ /** * 该方法在用户检查 角色、权限时调用,实际当中会在这里从数据库中检查用户角色及权限,并存在缓存当中,以便下次快速查询 * 从数据库检出对应的角色权限后存入 SimpleAuthorizationInfo 对象中。 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { String currentUsername = (String)super.getAvailablePrincipal(arg0); SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); if(currentUsername.equals("admin")){ simpleAuthorInfo.addStringPermission("admin:edit"); //这里硬编码写入 admin角色的edit权限 //实际中可能会像上面注释的那样从数据库取得 return simpleAuthorInfo; } return null; } /** * 该回调方法在用户调用Subject 对象的login方法时调用,这里可以用户名密码检验功能 */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken)authcToken; if("user".equals(token.getUsername())||"admin".equals(token.getUsername())){ AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(), this.getName()); this.setSession("currentUser", token.getUsername()); return authcInfo; } //没有返回登录用户名对应的SimpleAuthenticationInfo对象时,就会在LoginController中抛出UnknownAccountException异常 return null; } /** * 将一些数据放到ShiroSession中,以便于其它地方使用 * 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到 */ 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、配置applicationContex.xml
<!-- Shiro Filter --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <!-- 登录页面 ,用户 登录不成功自动 返回该页面 --> <property name="loginUrl" value="/login" /> <!-- 登录成功页面,登录成功后跳转到该页面 --> <property name="successUrl" value="/index" /> <!-- 无权访问跳转页面 --> <property name="unauthorizedUrl" value="permNo" /> <!-- 自定义权限页面设置url的访问权限。anon表示不用验证,都可以访问。anthc:authc filter 监听,不登陆不能访问。logout:logout filter监听。没有列出的常用配置:perms["remote:invoke"] :需要角色romote 和权限invoke才能访问。roles["admin"]需要角色admin才能访问。设置可用“,”隔开,如: /admin/test = authc,roles[admin] --> <property name="filterChainDefinitions"> <value> <!-- 无参,表示可匿名使用,可以理解为匿名用户或游客 --> /login = anon /index = authc <!-- 只有admin:edit权限才可以访问 index --> /permOk = authc,perms[admin:edit] </value> </property> </bean> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myRealm" /> </bean> <bean id="myRealm" class="com.controller.MyRealm" />
注:黑色部分是上面实现的类,注意包名
4、controller部分
@RequestMapping(value = "/login",method = {RequestMethod.GET}) public String login(Model model){ return "/login"; } @RequestMapping(value = "/login",method = {RequestMethod.POST}) public String login(HttpServletRequest request, HttpServletResponse response){ UsernamePasswordToken token = new UsernamePasswordToken(request.getParameter("userName"), request.getParameter("password")); token.setRememberMe(true); try{ //获取当前的Subject Subject currentUser = SecurityUtils.getSubject(); currentUser.login(token); //验证是否登录成功 if(currentUser.isAuthenticated()){ System.out.println("用户[" + "admin" + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)"); return "forward:/index"; }else{ token.clear(); } } catch(Exception ex){ } return "/login"; } @RequestMapping(value = "/index") public String index(HttpServletRequest request, HttpServletResponse response){ return "/index"; } @RequestMapping(value = "/permNo") public String permNo(HttpServletRequest request, HttpServletResponse response){ return "/permNo"; } @RequestMapping(value = "/permOk") public String permOk(HttpServletRequest request, HttpServletResponse response){ return "/permOk"; }
所需jsp页面
login.jsp
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" %> <html> <body> <form id="contentModel" action="login" method="post"> <span id="contentModel.errors" class="error">可分别用user、admin用户 测试 密码任意</span> <table> <tr> <td>Name</td> <td><input id="userName" name="userName" type="text" value=""/> </td> <td><span id="userName.errors" class="error"></span> </td> </tr> <tr> <td>password</td> <td><input id="password" name="password" type="text" value=""/> </td> <td> </td> </tr> <tr> <td colspan="3"><input type="submit" /> </td> </tr> </table> </form> </body> </html>
index.jsp
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" %> <html> <body> <h2>${userid}</h2> <a href="permOk">进入</a> </body> </html>
permNo.jsp
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" %> <html> <body> <h2>你没有权限访问 </h2> </body> </html>
permOk.jsp
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" %> <html> <body> <h2>成功 </h2> </body> </html>
最终效果:访问login页面使用user用户登录可以进入到index页面,但不能再进入里面的页面,换成admin用户可以继续往下点击。
时间: 2024-10-10 20:10:01