Shiro在web的登录基础验证主要包括以下4个步骤:登录操作处理、表单页面、设置验证的Realm和配置shiro.ini文件
1、建立Servlet程序来进行具体的登录操作处理。@WebServlet("/shiroLogin") public class LoginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String mid = request.getParameter("mid") ; String password = request.getParameter("password") ; Subject subject = SecurityUtils.getSubject() ; UsernamePasswordToken token = new UsernamePasswordToken(mid,password) ; subject.login(token); request.getSession().setAttribute("mid", mid); request.getRequestDispatcher("/pages/welcome.jsp").forward(request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }2、在项目中建立前台表单界面
<form action="shiroLogin" method="post"> 用户名:<input type="text" name="mid" id="mid"><br> 密 码:<input type="password" name="password" id="password"><br> <input type="submit" value="登录"> <input type="reset" value="重置"> </form>3、设置验证的Realm
public class MyRealm extends AuthorizingRealm { @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { System.out.println("********** 2、用户角色与权限:doGetAuthorizationInfo **********"); String username = (String) principals.getPrimaryPrincipal() ; // 取得用户登录名 SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo() ; // 定义授权信息的返回数据 MemberLoginService service = new MemberLoginService() ; // 进行业务层处理 auth.setRoles(service.listRolesByMember(username)); // 所有的角色必须以Set集合的形式出现 auth.setStringPermissions(service.listActionsByMember(username)); // 所有的权限必须以Set集合的形式出现 service.close(); return auth; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.out.println("********** 1、用户登录认证:doGetAuthenticationInfo() **********"); // 1、登录认证的方法需要先执行,需要用他来判断登录的用户信息是否合法 String username = (String) token.getPrincipal() ; // 取得用户名 // 需要通过用户名取得用户的完整信息,利用业务层操作 MemberLoginService service = new MemberLoginService() ; Member vo = service.get(username) ; // 需要取得的是用户的信息 service.close(); if (vo == null) { throw new UnknownAccountException("该用户名称不存在!") ; } else { // 进行密码的验证处理 String password = new String((char []) token.getCredentials()) ; // 将数据库中的密码与输入的密码进行比较,这样就可以确定当前用户是否可以正常登录 if (vo.getPassword().equals(password)) { // 密码正确 AuthenticationInfo auth = new SimpleAuthenticationInfo(username, password, "memberRealm") ; return auth ; } else { throw new IncorrectCredentialsException("密码错误!") ; } } }4、设置shiro.ini文件
[main] # 如果现在认证失败,则跳转到loginUrl配置的路径 authc.loginUrl=/login.jsp # 需要配置上当角色认证失败之后的跳转页面 roles.unauthorizedUrl=/role.jsp jdbcRealm=MyRealm securityManager.realms=$jdbcRealm # 配置所有需要进行路径检测的页面 [urls] # 登录的页面是不需要进行检测处理的 /shiroLogin=anon # 指定的页面需要进行登录检测,此时表示需要先进行身份认证,而后再进行角色认证 /pages/welcome.jsp=authc 以上,就完成了web的前台登录验证