springmvc+shiro+maven 实现登录认证与权限授权管理
shiro 是shiro 是一个 apache 下的一开源项目项目,旨在简化身份验证和授权。
1:shiro的配置,通过maven加入shiro相关jar包
<!-- shiro --> <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 :在web.xml中添加shiro过滤器
<!-- 配置shiro的核心拦截器 --> <filter> <filter-name>shirofilter</filter-name> <filter-class>org.springframework.web.filter.delegatingfilterproxy</filter-class> </filter> <filter-mapping> <filter-name>shirofilter</filter-name> <url-pattern>/admin/*</url-pattern> </filter-mapping>
3: springmvc中对shiro配置
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <!-- web.xml中shiro的filter对应的bean --> <bean id="shirofilter" class="org.apache.shiro.spring.web.shirofilterfactorybean"> <!-- 管理器,必须设置 --> <property name="securitymanager" ref="securitymanager" /> <!-- 拦截到,跳转到的地址,通过此地址去认证 --> <property name="loginurl" value="/admin/login.do" /> <!-- 认证成功统一跳转到/admin/index.do,建议不配置,shiro认证成功自动到上一个请求路径 --> <property name="successurl" value="/admin/index.do" /> <!-- 通过unauthorizedurl指定没有权限操作时跳转页面 --> <property name="unauthorizedurl" value="/refuse.jsp" /> <!-- 自定义filter,可用来更改默认的表单名称配置 --> <property name="filters"> <map> <!-- 将自定义 的formauthenticationfilter注入shirofilter中 --> <entry key="authc" value-ref="formauthenticationfilter" /> </map> </property> <property name="filterchaindefinitions"> <value> <!-- 对静态资源设置匿名访问 --> /images/** = anon /js/** = anon /styles/** = anon <!-- 验证码,可匿名访问 --> /validatecode.jsp = anon <!-- 请求 logout.do地址,shiro去清除session --> /admin/logout.do = logout <!--商品查询需要商品查询权限 ,取消url拦截配置,使用注解授权方式 --> <!-- /items/queryitems.action = perms[item:query] /items/edititems.action = perms[item:edit] --> <!-- 配置记住我或认证通过可以访问的地址 --> /welcome.jsp = user /admin/index.do = user <!-- /** = authc 所有url都必须认证通过才可以访问 --> /** = authc </value> </property> </bean> <!-- securitymanager安全管理器 --> <bean id="securitymanager" class="org.apache.shiro.web.mgt.defaultwebsecuritymanager"> <property name="realm" ref="customrealm" /> <!-- 注入缓存管理器 --> <property name="cachemanager" ref="cachemanager" /> <!-- 注入session管理器 --> <!-- <property name="sessionmanager" ref="sessionmanager" /> --> <!-- 记住我 --> <property name="remembermemanager" ref="remembermemanager" /> </bean> <!-- 自定义realm --> <bean id="customrealm" class="com.zhijianj.stucheck.shiro.customrealm"> <!-- 将凭证匹配器设置到realm中,realm按照凭证匹配器的要求进行散列 --> <!-- <property name="credentialsmatcher" ref="credentialsmatcher" /> --> </bean> <!-- 凭证匹配器 --> <bean id="credentialsmatcher" class="org.apache.shiro.authc.credential.hashedcredentialsmatcher"> <!-- 选用md5散列算法 --> <property name="hashalgorithmname" value="md5" /> <!-- 进行一次加密 --> <property name="hashiterations" value="1" /> </bean> <!-- 自定义form认证过虑器 --> <!-- 基于form表单的身份验证过滤器,不配置将也会注册此过虑器,表单中的用户账号、密码及loginurl将采用默认值,建议配置 --> <!-- 可通过此配置,判断验证码 --> <bean id="formauthenticationfilter" class="com.zhijianj.stucheck.shiro.customformauthenticationfilter "> <!-- 表单中账号的input名称,默认为username --> <property name="usernameparam" value="username" /> <!-- 表单中密码的input名称,默认为password --> <property name="passwordparam" value="password" /> <!-- 记住我input的名称,默认为rememberme --> <property name="remembermeparam" value="rememberme" /> </bean> <!-- 会话管理器 --> <bean id="sessionmanager" class="org.apache.shiro.web.session.mgt.defaultwebsessionmanager"> <!-- session的失效时长,单位毫秒 --> <property name="globalsessiontimeout" value="600000" /> <!-- 删除失效的session --> <property name="deleteinvalidsessions" value="true" /> </bean> <!-- 缓存管理器 --> <bean id="cachemanager" class="org.apache.shiro.cache.ehcache.ehcachemanager"> <property name="cachemanagerconfigfile" value="classpath:shiro-ehcache.xml" /> </bean> <!-- remembermemanager管理器,写cookie,取出cookie生成用户信息 --> <bean id="remembermemanager" class="org.apache.shiro.web.mgt.cookieremembermemanager"> <property name="cookie" ref="remembermecookie" /> </bean> <!-- 记住我cookie --> <bean id="remembermecookie" class="org.apache.shiro.web.servlet.simplecookie"> <!-- rememberme是cookie的名字 --> <constructor-arg value="rememberme" /> <!-- 记住我cookie生效时间30天 --> <property name="maxage" value="2592000" /> </bean> </beans>
4 :自定义realm编码
public class customrealm extends authorizingrealm { // 设置realm的名称 @override public void setname(string name) { super.setname("customrealm"); } @autowired private adminuserservice adminuserservice; /** * 认证 */ @override protected authenticationinfo dogetauthenticationinfo(authenticationtoken token) throws authenticationexception { // token中包含用户输入的用户名和密码 // 第一步从token中取出用户名 string username = (string) token.getprincipal(); // 第二步:根据用户输入的usercode从数据库查询 tadminuser adminuser = adminuserservice.getadminuserbyusername(username); // 如果查询不到返回null if (adminuser == null) {// return null; } // 获取数据库中的密码 string password = adminuser.getpassword(); /** * 认证的用户,正确的密码 */ authenticationinfo authcinfo = new simpleauthenticationinfo(adminuser, password, this.getname()); //md5 加密+加盐+多次加密 //<span style="color:#ff0000;">simpleauthenticationinfo authcinfo = new simpleauthenticationinfo(adminuser, password,bytesource.util.bytes(salt), this.getname());</span> return authcinfo; } /** * 授权,只有成功通过<span style="font-family: arial, helvetica, sans-serif;">dogetauthenticationinfo方法的认证后才会执行。</span> */ @override protected authorizationinfo dogetauthorizationinfo(principalcollection principals) { // 从 principals获取主身份信息 // 将getprimaryprincipal方法返回值转为真实身份类型(在上边的dogetauthenticationinfo认证通过填充到simpleauthenticationinfo中身份类型), tadminuser activeuser = (tadminuser) principals.getprimaryprincipal(); // 根据身份信息获取权限信息 // 从数据库获取到权限数据 tadminrole adminroles = adminuserservice.getadminroles(activeuser); // 单独定一个集合对象 list<string> permissions = new arraylist<string>(); if (adminroles != null) { permissions.add(adminroles.getrolekey()); } // 查到权限数据,返回授权信息(要包括 上边的permissions) simpleauthorizationinfo simpleauthorizationinfo = new simpleauthorizationinfo(); // 将上边查询到授权信息填充到simpleauthorizationinfo对象中 simpleauthorizationinfo.addstringpermissions(permissions); return simpleauthorizationinfo; } // 清除缓存 public void clearcached() { principalcollection principals = securityutils.getsubject().getprincipals(); super.clearcache(principals); } }
5 缓存配置
ehcache.xml代码如下:
<ehcache updatecheck="false" name="shirocache"> <defaultcache maxelementsinmemory="10000" eternal="false" timetoidleseconds="120" timetoliveseconds="120" overflowtodisk="false" diskpersistent="false" diskexpirythreadintervalseconds="120" /> </ehcache>
通过使用ehache中就避免第次都向服务器发送权限授权(dogetauthorizationinfo)的请求。
6.自定义表单编码过滤器
customformauthenticationfilter代码,认证之前调用,可用于验证码校验
public class customformauthenticationfilter extends formauthenticationfilter { // 原formauthenticationfilter的认证方法 @override protected boolean onaccessdenied(servletrequest request, servletresponse response) throws exception { // 在这里进行验证码的校验 // 从session获取正确验证码 httpservletrequest httpservletrequest = (httpservletrequest) request; httpsession session = httpservletrequest.getsession(); // 取出session的验证码(正确的验证码) string validatecode = (string) session.getattribute("validatecode"); // 取出页面的验证码 // 输入的验证和session中的验证进行对比 string randomcode = httpservletrequest.getparameter("randomcode"); if (randomcode != null && validatecode != null && !randomcode.equals(validatecode)) { // 如果校验失败,将验证码错误失败信息,通过shirologinfailure设置到request中 httpservletrequest.setattribute("shirologinfailure", "randomcodeerror"); // 拒绝访问,不再校验账号和密码 return true; } return super.onaccessdenied(request, response); } }
在此符上验证码jsp界面的代码 validatecode.jsp
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <%@ page import="java.util.random"%> <%@ page import="java.io.outputstream"%> <%@ page import="java.awt.color"%> <%@ page import="java.awt.font"%> <%@ page import="java.awt.graphics"%> <%@ page import="java.awt.image.bufferedimage"%> <%@ page import="javax.imageio.imageio"%> <% int width = 60; int height = 32; //create the image bufferedimage image = new bufferedimage(width, height, bufferedimage.type_int_rgb); graphics g = image.getgraphics(); // set the background color g.setcolor(new color(0xdcdcdc)); g.fillrect(0, 0, width, height); // draw the border g.setcolor(color.black); g.drawrect(0, 0, width - 1, height - 1); // create a random instance to generate the codes random rdm = new random(); string hash1 = integer.tohexstring(rdm.nextint()); // make some confusion for (int i = 0; i < 50; i++) { int x = rdm.nextint(width); int y = rdm.nextint(height); g.drawoval(x, y, 0, 0); } // generate a random code string capstr = hash1.substring(0, 4); //将生成的验证码存入session session.setattribute("validatecode", capstr); g.setcolor(new color(0, 100, 0)); g.setfont(new font("candara", font.bold, 24)); g.drawstring(capstr, 8, 24); g.dispose(); //输出图片 response.setcontenttype("image/jpeg"); out.clear(); out = pagecontext.pushbody(); outputstream strm = response.getoutputstream(); imageio.write(image, "jpeg", strm); strm.close(); %>
7.登录控制器方法
/** * 到登录界面 * * @return * @throws exception */ @requestmapping("login.do") public string adminpage(httpservletrequest request) throws exception { // 如果登陆失败从request中获取认证异常信息,shirologinfailure就是shiro异常类的全限定名 string exceptionclassname = (string) request.getattribute("shirologinfailure"); // 根据shiro返回的异常类路径判断,抛出指定异常信息 if (exceptionclassname != null) { if (unknownaccountexception.class.getname().equals(exceptionclassname)) { // 最终会抛给异常处理器 throw new customjsonexception("账号不存在"); } else if (incorrectcredentialsexception.class.getname().equals(exceptionclassname)) { throw new customjsonexception("用户名/密码错误"); } else if ("randomcodeerror".equals(exceptionclassname)) { throw new customjsonexception("验证码错误 "); } else { throw new exception();// 最终在异常处理器生成未知错误 } } // 此方法不处理登陆成功(认证成功),shiro认证成功会自动跳转到上一个请求路径 // 登陆失败还到login页面 return "admin/login"; }
8.用户回显controller
当用户登录认证成功后,customrealm在调用完dogetauthenticationinfo时,通过
authenticationinfo authcinfo = new simpleauthenticationinfo(adminuser, password, this.getname()); return authcinfo;
simpleauthenticationinfo构造参数的第一个参数传入一个用户的对象,之后,可通过subject subject = securityutils.getsubject();中的subject.getprincipal()获取到此对象。所以需要回显用户信息时,我这样调用的
@requestmapping("index.do") public string index(model model) { //从shiro的session中取activeuser subject subject = securityutils.getsubject(); //取身份信息 tadminuser adminuser = (tadminuser) subject.getprincipal(); //通过model传到页面 model.addattribute("adminuser", adminuser); return "admin/index"; }
9.在jsp页面中控制权限
先引入shiro的头文件
<!-- shiro头引入 --> <%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro"%>
采用shiro标签对权限进行处理
<!-- 有curd权限才显示修改链接,没有该 权限不显示,相当 于if(haspermission(curd)) --> <shiro:haspermission name="curd"> <br /> 我拥有超级的增删改查权限额 </shiro:haspermission>
10.在controller控制权限
通过@requirespermissions注解,指定执行此controller中某个请求方法需要的权限
@requestmapping("/queryinfo.do") @requirespermissions("q")//执行需要"q"权限 public modelandview queryitems(httpservletrequest request) throws exception { }
11.md5加密加盐处理
这里以修改密码为例,通过获取新的密码(明文)后通过md5加密+加盐+3次加密为例
@requestmapping("updatepassword.do") @responsebody public string updateadminuserpassword(string newpassword) { // 从shiro的session中取activeuser subject subject = securityutils.getsubject(); // 取身份信息 tadminuser adminuser = (tadminuser) subject.getprincipal(); // 生成salt,随机生成 securerandomnumbergenerator securerandomnumbergenerator = new securerandomnumbergenerator(); string salt = securerandomnumbergenerator.nextbytes().tohex(); md5hash md5 = new md5hash(newpassword, salt, 3); string newmd5password = md5.tohex(); // 设置新密码 adminuser.setpassword(newmd5password); // 设置盐 adminuser.setsalt(salt); adminuserservice.updateadminuserpassword(adminuser); return newpassword; }
总结
以上所述是小编给大家介绍的springmvc+shiro+maven 实现登录认证与权限授权管理,希望对大家有所帮助