这里用的是SpringMVC-3.2.4和Shiro-1.2.2,示例代码如下
首先是web.xml
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.util.IntrospectorCleanupListener
org.springframework.web.context.ContextLoaderListener
SpringEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
SpringEncodingFilter
/*
shiroFilter
org.springframework.web.filter.DelegatingFilterProxy
targetFilterLifecycle
true
shiroFilter
/*
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:applicationContext.xml
SpringMVC
/
405
/WEB-INF/405.html
404
/WEB-INF/404.jsp
500
/WEB-INF/500.jsp
java.lang.Throwable
/WEB-INF/500.jsp
下面是用于显示Request method 'GET' not supported的//WebRoot//WEB-INF//405.html
405.html
Request method 'GET' not supported
The specified HTTP method is not allowed for the requested resource.
下面是允许匿名用户访问的//WebRoot//login.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
${message_login}
下面是用户登录后显示的//WebRoot//main.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
普通用户可访问用户信息页面
管理员可访问用户列表页面
Logout
下面是只有管理员才允许访问的//WebRoot//admin//listUser.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
This is listUser.jsp
Logout
下面是普通的登录用户所允许访问的//WebRoot//user//info.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
当前登录的用户为${currUser}
Logout
下面是//src//log4j.properties
#use Root for GobalConfig
log4j.rootLogger=DEBUG,CONSOLE
log4j.logger.java.sql=DEBUG
log4j.logger.org.apache.shiro=DEBUG
log4j.logger.org.apache.commons=DEBUG
log4j.logger.org.springframework=DEBUG
#use ConsoleAppender for ConsoleOut
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=DEBUG
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%d{yyyyMMdd HH:mm:ss}][%t][%C{1}.%M]%m%n
下面是//src//applicationContext.xml
WEB-INF/error_fileupload
WEB-INF/500
/mydemo/login=anon
/mydemo/getVerifyCodeImage=anon
/main**=authc
/user/info**=authc
/admin/listUser**=authc,perms[admin:manage]
下面是自定义的Realm类----MyRealm.java
package com.jadyer.realm;
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;
/**
* 自定义的指定Shiro验证用户登录的类
* @see 在本例中定义了2个用户:jadyer和玄玉,jadyer具有admin角色和admin:manage权限,玄玉不具有任何角色和权限
* @create Sep 29, 2013 3:15:31 PM
* @author 玄玉
*/
public class MyRealm extends AuthorizingRealm {
/**
* 为当前登录的Subject授予角色和权限
* @see 经测试:本例中该方法的调用时机为需授权资源被访问时
* @see 经测试:并且每次访问需授权资源时都会执行该方法中的逻辑,这表明本例中默认并未启用AuthorizationCache
* @see 个人感觉若使用了Spring3.1开始提供的ConcurrentMapCache支持,则可灵活决定是否启用AuthorizationCache
* @see 比如说这里从数据库获取权限信息时,先去访问Spring3.1提供的缓存,而不使用Shior提供的AuthorizationCache
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
//获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()
String currentUsername = (String)super.getAvailablePrincipal(principals);
// List roleList = new ArrayList();
// List permissionList = new ArrayList();
// //从数据库中获取当前登录用户的详细信息
// User user = userService.getByUsername(currentUsername);
// if(null != user){
// //实体类User中包含有用户角色的实体类信息
// if(null!=user.getRoles() && user.getRoles().size()>0){
// //获取当前登录用户的角色
// for(Role role : user.getRoles()){
// roleList.add(role.getName());
// //实体类Role中包含有角色权限的实体类信息
// if(null!=role.getPermissions() && role.getPermissions().size()>0){
// //获取权限
// for(Permission pmss : role.getPermissions()){
// if(!StringUtils.isEmpty(pmss.getPermission())){
// permissionList.add(pmss.getPermission());
// }
// }
// }
// }
// }
// }else{
// throw new AuthorizationException();
// }
// //为当前用户设置角色和权限
// SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
// simpleAuthorInfo.addRoles(roleList);
// simpleAuthorInfo.addStringPermissions(permissionList);
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中的的配置
return null;
}
/**
* 验证当前登录的Subject
* @see 经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
//获取基于用户名和密码的令牌
//实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的
//两个token的引用都是一样的,本例中是org.apache.shiro.authc.UsernamePasswordToken@33799a1e
UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
System.out.println("验证当前Subject时获取到token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
// User user = userService.getByUsername(token.getUsername());
// if(null != user){
// AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), user.getNickname());
// this.setSession("currentUser", user);
// return authcInfo;
// }else{
// return null;
// }
//此处无需比对,比对的逻辑Shiro会做,我们只需返回一个和令牌相关的正确的验证信息
//说白了就是第一个参数填登录用户名,第二个参数填合法的登录密码(可以是从数据库中取到的,本例中为了演示就硬编码了)
//这样一来,在随后的登录页面上就只有这里指定的用户和密码才能通过验证
if("jadyer".equals(token.getUsername())){
AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("jadyer", "jadyer", this.getName());
this.setSession("currentUser", "jadyer");
return authcInfo;
}else if("玄玉".equals(token.getUsername())){
AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("玄玉", "xuanyu", this.getName());
this.setSession("currentUser", "玄玉");
return authcInfo;
}
//没有返回登录用户名对应的SimpleAuthenticationInfo对象时,就会在LoginController中抛出UnknownAccountException异常
return null;
}
/**
* 将一些数据放到ShiroSession中,以便于其它地方使用
* @see 比如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);
}
}
}
}
下面是处理用户登录的LoginController.java
package com.jadyer.controller;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
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.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.jadyer.util.VerifyCodeUtil;
/**
* 本例中用到的jar文件如下
* @see aopalliance.jar
* @see commons-lang3-3.1.jar
* @see commons-logging-1.1.2.jar
* @see log4j-1.2.17.jar
* @see shiro-all-1.2.2.jar
* @see slf4j-api-1.7.5.jar
* @see slf4j-log4j12-1.7.5.jar
* @see spring-aop-3.2.4.RELEASE.jar
* @see spring-beans-3.2.4.RELEASE.jar
* @see spring-context-3.2.4.RELEASE.jar
* @see spring-core-3.2.4.RELEASE.jar
* @see spring-expression-3.2.4.RELEASE.jar
* @see spring-jdbc-3.2.4.RELEASE.jar
* @see spring-oxm-3.2.4.RELEASE.jar
* @see spring-tx-3.2.4.RELEASE.jar
* @see spring-web-3.2.4.RELEASE.jar
* @see spring-webmvc-3.2.4.RELEASE.jar
* @create Sep 30, 2013 11:10:06 PM
* @author 玄玉
*/
@Controller
@RequestMapping("mydemo")
public class LoginController {
/**
* 获取验证码图片和文本(验证码文本会保存在HttpSession中)
*/
@RequestMapping("/getVerifyCodeImage")
public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
//设置页面不缓存
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_ONLY, 4, null);
//将验证码放到HttpSession里面
request.getSession().setAttribute("verifyCode", verifyCode);
System.out.println("本次生成的验证码为[" + verifyCode + "],已存放到HttpSession中");
//设置输出的内容的类型为JPEG图像
response.setContentType("image/jpeg");
BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(verifyCode, 90, 30, 3, true, Color.WHITE, Color.BLACK, null);
//写给浏览器
ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());
}
/**
* 用户登录
*/
@RequestMapping(value="/login", method=RequestMethod.POST)
public String login(HttpServletRequest request){
String resultPageURL = InternalResourceViewResolver.FORWARD_URL_PREFIX + "/";
String username = request.getParameter("username");
String password = request.getParameter("password");
//获取HttpSession中的验证码
String verifyCode = (String)request.getSession().getAttribute("verifyCode");
//获取用户请求表单中输入的验证码
String submitCode = WebUtils.getCleanParam(request, "verifyCode");
System.out.println("用户[" + username + "]登录时输入的验证码为[" + submitCode + "],HttpSession中的验证码为[" + verifyCode + "]");
if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(verifyCode, submitCode.toLowerCase())){
request.setAttribute("message_login", "验证码不正确");
return resultPageURL;
}
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
token.setRememberMe(true);
System.out.println("为了验证登录用户而封装的token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
//获取当前的Subject
Subject currentUser = SecurityUtils.getSubject();
try {
//在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
//每个Realm都能在必要时对提交的AuthenticationTokens作出反应
//所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
System.out.println("对用户[" + username + "]进行登录验证..验证开始");
currentUser.login(token);
System.out.println("对用户[" + username + "]进行登录验证..验证通过");
resultPageURL = "main";
}catch(UnknownAccountException uae){
System.out.println("对用户[" + username + "]进行登录验证..验证未通过,未知账户");
request.setAttribute("message_login", "未知账户");
}catch(IncorrectCredentialsException ice){
System.out.println("对用户[" + username + "]进行登录验证..验证未通过,错误的凭证");
request.setAttribute("message_login", "密码不正确");
}catch(LockedAccountException lae){
System.out.println("对用户[" + username + "]进行登录验证..验证未通过,账户已锁定");
request.setAttribute("message_login", "账户已锁定");
}catch(ExcessiveAttemptsException eae){
System.out.println("对用户[" + username + "]进行登录验证..验证未通过,错误次数过多");
request.setAttribute("message_login", "用户名或密码错误次数过多");
}catch(AuthenticationException ae){
//通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
System.out.println("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下");
ae.printStackTrace();
request.setAttribute("message_login", "用户名或密码不正确");
}
//验证是否登录成功
if(currentUser.isAuthenticated()){
System.out.println("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
}else{
token.clear();
}
return resultPageURL;
}
/**
* 用户登出
*/
@RequestMapping("/logout")
public String logout(HttpServletRequest request){
SecurityUtils.getSubject().logout();
return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/";
}
}
下面是处理普通用户访问的UserController.java
package com.jadyer.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("mydemo")
public class UserController {
@RequestMapping(value="/getUserInfo")
public String getUserInfo(HttpServletRequest request){
String currentUser = (String)request.getSession().getAttribute("currentUser");
System.out.println("当前登录的用户为[" + currentUser + "]");
request.setAttribute("currUser", currentUser);
return "/user/info";
}
}
最后是用于生成登录验证码的VerifyCodeUtil.java
package com.jadyer.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* 验证码生成器
* @see --------------------------------------------------------------------------------------------------------------
* @see 可生成数字、大写、小写字母及三者混合类型的验证码
* @see 支持自定义验证码字符数量,支持自定义验证码图片的大小,支持自定义需排除的特殊字符,支持自定义干扰线的数量,支持自定义验证码图文颜色
* @see --------------------------------------------------------------------------------------------------------------
* @see 另外,给Shiro加入验证码有多种方式,也可以通过继承修改FormAuthenticationFilter类,通过Shiro去验证验证码
* @see 而这里既然使用了SpringMVC,也为了简化操作,就使用此工具生成验证码,并在Controller中处理验证码的校验
* @see --------------------------------------------------------------------------------------------------------------
* @create Sep 29, 2013 4:23:13 PM
* @author 玄玉
*/
public class VerifyCodeUtil {
/**
* 验证码类型为仅数字,即0~9
*/
public static final int TYPE_NUM_ONLY = 0;
/**
* 验证码类型为仅字母,即大小写字母混合
*/
public static final int TYPE_LETTER_ONLY = 1;
/**
* 验证码类型为数字和大小写字母混合
*/
public static final int TYPE_ALL_MIXED = 2;
/**
* 验证码类型为数字和大写字母混合
*/
public static final int TYPE_NUM_UPPER = 3;
/**
* 验证码类型为数字和小写字母混合
*/
public static final int TYPE_NUM_LOWER = 4;
/**
* 验证码类型为仅大写字母
*/
public static final int TYPE_UPPER_ONLY = 5;
/**
* 验证码类型为仅小写字母
*/
public static final int TYPE_LOWER_ONLY = 6;
private VerifyCodeUtil(){}
/**
* 生成随机颜色
*/
private static Color generateRandomColor() {
Random random = new Random();
return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
}
/**
* 生成图片验证码
* @param type 验证码类型,参见本类的静态属性
* @param length 验证码字符长度,要求大于0的整数
* @param excludeString 需排除的特殊字符
* @param width 图片宽度(注意此宽度若过小,容易造成验证码文本显示不全,如4个字符的文本可使用85到90的宽度)
* @param height 图片高度
* @param interLine 图片中干扰线的条数
* @param randomLocation 每个字符的高低位置是否随机
* @param backColor 图片颜色,若为null则表示采用随机颜色
* @param foreColor 字体颜色,若为null则表示采用随机颜色
* @param lineColor 干扰线颜色,若为null则表示采用随机颜色
* @return 图片缓存对象
*/
public static BufferedImage generateImageCode(int type, int length, String excludeString, int width, int height, int interLine, boolean randomLocation, Color backColor, Color foreColor, Color lineColor){
String textCode = generateTextCode(type, length, excludeString);
return generateImageCode(textCode, width, height, interLine, randomLocation, backColor, foreColor, lineColor);
}
/**
* 生成验证码字符串
* @param type 验证码类型,参见本类的静态属性
* @param length 验证码长度,要求大于0的整数
* @param excludeString 需排除的特殊字符(无需排除则为null)
* @return 验证码字符串
*/
public static String generateTextCode(int type, int length, String excludeString){
if(length <= 0){
return "";
}
StringBuffer verifyCode = new StringBuffer();
int i = 0;
Random random = new Random();
switch(type){
case TYPE_NUM_ONLY:
while(i < length){
int t = random.nextInt(10);
//排除特殊字符
if(null==excludeString || excludeString.indexOf(t+"")<0) {
verifyCode.append(t);
i++;
}
}
break;
case TYPE_LETTER_ONLY:
while(i < length){
int t = random.nextInt(123);
if((t>=97 || (t>=65&&t<=90)) && (null==excludeString||excludeString.indexOf((char)t)<0)){
verifyCode.append((char)t);
i++;
}
}
break;
case TYPE_ALL_MIXED:
while(i < length){
int t = random.nextInt(123);
if((t>=97 || (t>=65&&t<=90) || (t>=48&&t<=57)) && (null==excludeString||excludeString.indexOf((char)t)<0)){
verifyCode.append((char)t);
i++;
}
}
break;
case TYPE_NUM_UPPER:
while(i < length){
int t = random.nextInt(91);
if((t>=65 || (t>=48&&t<=57)) && (null==excludeString || excludeString.indexOf((char)t)<0)){
verifyCode.append((char)t);
i++;
}
}
break;
case TYPE_NUM_LOWER:
while(i < length){
int t = random.nextInt(123);
if((t>=97 || (t>=48&&t<=57)) && (null==excludeString || excludeString.indexOf((char)t)<0)){
verifyCode.append((char)t);
i++;
}
}
break;
case TYPE_UPPER_ONLY:
while(i < length){
int t = random.nextInt(91);
if((t >= 65) && (null==excludeString||excludeString.indexOf((char)t)<0)){
verifyCode.append((char)t);
i++;
}
}
break;
case TYPE_LOWER_ONLY:
while(i < length){
int t = random.nextInt(123);
if((t>=97) && (null==excludeString||excludeString.indexOf((char)t)<0)){
verifyCode.append((char)t);
i++;
}
}
break;
}
return verifyCode.toString();
}
/**
* 已有验证码,生成验证码图片
* @param textCode 文本验证码
* @param width 图片宽度(注意此宽度若过小,容易造成验证码文本显示不全,如4个字符的文本可使用85到90的宽度)
* @param height 图片高度
* @param interLine 图片中干扰线的条数
* @param randomLocation 每个字符的高低位置是否随机
* @param backColor 图片颜色,若为null则表示采用随机颜色
* @param foreColor 字体颜色,若为null则表示采用随机颜色
* @param lineColor 干扰线颜色,若为null则表示采用随机颜色
* @return 图片缓存对象
*/
public static BufferedImage generateImageCode(String textCode, int width, int height, int interLine, boolean randomLocation, Color backColor, Color foreColor, Color lineColor){
//创建内存图像
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//获取图形上下文
Graphics graphics = bufferedImage.getGraphics();
//画背景图
graphics.setColor(null==backColor ? generateRandomColor() : backColor);
graphics.fillRect(0, 0, width, height);
//画干扰线
Random random = new Random();
if(interLine > 0){
int x = 0, y = 0, x1 = width, y1 = 0;
for(int i=0; i