使用Apache Shiro进行身份认证

本文介绍了如何在WEB应用中使用Shiro进行身份认证。

在web.xml文件中配置一个Servlet ContextListener的监听器和Filter过滤器。

<listener>
		<listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
	</listener>
	<filter>
		<filter-name>ShiroFilter</filter-name>
		<filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>ShiroFilter</filter-name>
		<url-pattern>/login.do</url-pattern>
	</filter-mapping>

JSP页面提交用户名和口令。

<FORM name="form1" action="login.do" method="POST">
	<TABLE cellSpacing=0 cellPadding=0 align=center
		border=0>
		<TBODY>
			<TR>
				<TD width=250>
					<TABLE cellSpacing=3 cellPadding=0 border=0>
						<TBODY>
							<TR>
								<TD width=90><IMG height=29
									src="images/title_yhm.gif" width=90></TD>
								<TD><INPUT class=logininput name=loginName>
								</TD>
							</TR>
							<TR>
								<TD width=90><IMG height=27
									src="images/title_mima.gif" width=90></TD>
								<TD><INPUT class=logininput type=password
									name=password></TD>
							</TR>
							<TR>
								<TD width=90></TD>
								<TD align="right"></TD>
							</TR>
						</TBODY>
					</TABLE>
				</TD>
				<TD vAlign=top>
					<TABLE cellSpacing=6 cellPadding=0 border=0>
						<TBODY>
							<TR>
								<TD><IMG style="CURSOR: hand"
									οnclick=doSubmit() height=35
									src="images/button_login.gif" width=77
									border=0></TD>
							</TR>
						</TBODY>
					</TABLE>
				</TD>
			</TR>
		</TBODY>
	</TABLE>
</FORM>

Shiro的配置文件,/WEB-INF/Shiro.ini。

main]
ds = com.mysql.jdbc.jdbc2.optional.MysqlDataSource  
ds.serverName = 127.0.0.1
ds.user = root
ds.password = 123456
ds.databaseName = shiro  
ds.url = jdbc:mysql://127.0.0.1:3306/shiro  
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm  
jdbcRealm.permissionsLookupEnabled = true  
jdbcRealm.authenticationQuery = SELECT password FROM user_credence_information WHERE username = ?  
jdbcRealm.dataSource = $ds

shiro.loginUrl = /login.jsp

[users]
# format: username = password, role1, role2, ..., roleN


[roles]
# format: roleName = permission1, permission2, ..., permissionN

[urls]
# The /login.jsp is not restricted to authenticated users (otherwise no one could log in!), but
# the 'authc' filter must still be specified for it so it can process that url's
# login submissions. It is 'smart' enough to allow those requests through as specified by the
# shiro.loginUrl above.
/success.jsp = authc

服务端认证程序。

public class LoginController implements Controller {
	private static final Log log = LogFactory.getLog(LoginController.class);
	protected ErrMg error;

	public ModelAndView doReturnError(HttpServletRequest request,
			HttpServletResponse response, ErrMg message, String errpath) {
		request.setAttribute("Error_Message", message);
		return new ModelAndView(errpath);

	}
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String loginName = request.getParameter("loginName");
		String loginPwd = request.getParameter("password");
		log.info("用户认证开始:" + loginName + " , " + loginPwd);
		String userid = null;
		String username = null;
		error = new ErrMg();
		AuthenticationToken token = new UsernamePasswordToken(loginName,
				loginPwd);
		Subject currentUser = SecurityUtils.getSubject();
		try {
			currentUser.login(token);
			userid = (String)currentUser.getPrincipal();
			log.info( "User [" + currentUser.getPrincipal() + "] logged in successfully." );
			log.info("用户认证完毕:" + loginName + " , " + userid);
			HttpSession session = request.getSession(true);
			session.setAttribute("USERINFORMATION", userid);
			session.setAttribute("USERNAME", userid);
			return new ModelAndView("success.jsp");
		} catch (UnknownAccountException uae) {
			log.info("用户认证失败:" + "username wasn't in the system.");
			error.setErrorMessage("username wasn't in the system.");
		} catch (IncorrectCredentialsException ice) {
			log.info("用户认证失败:" + "password didn't match.");
			error.setErrorMessage("password didn't match.");
		} catch (LockedAccountException lae) {
			log.info("用户认证失败:" + "account for that username is locked - can't login.");
			error.setErrorMessage("account for that username is locked - can't login.");
		} catch (AuthenticationException ae) {
			log.info("用户认证失败:" + "unexpected condition.");
			error.setErrorMessage("unexpected condition.");
		}
		
		return this.doReturnError(request, response, error, "error.jsp");
	}

}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

peterwanghao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值