博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Shiro之与SpringMVC集成
阅读量:6246 次
发布时间:2019-06-22

本文共 8995 字,大约阅读时间需要 29 分钟。

SpringMVC 环境省略

 

http://shiro.apache.org/download.html

 

pom.xml增加maven依赖    

org.apache.shiro
shiro-core
1.2.6
org.apache.shiro
shiro-web
1.2.6
org.apache.shiro
shiro-aspectj
1.2.6
org.apache.shiro
shiro-cas
1.2.6
org.apache.shiro
shiro-ehcache
1.2.6
org.apache.shiro
shiro-guice
1.2.6
org.apache.shiro
shiro-quartz
1.2.6
org.apache.shiro
shiro-spring
1.2.6

 

web.xml增加shiro-filter,放在所有filter之前

shiroFilter
org.springframework.web.filter.DelegatingFilterProxy
targetFilterLifecycle
true
shiroFilter
/*

 

 

建立首页,登录页等等相关控制器和页面

 

增加spring-shiro.xml配置文件

/loginPage=anon /doLogin=anon /doLogout=anon /*=authc

 

在web.xml里的contextConfigLocation的Spring核心监听器增加spring-shiro.xml文件路径

控制器核心代码如下

package com.zns.controller;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.DisabledAccountException;import org.apache.shiro.authc.ExcessiveAttemptsException;import org.apache.shiro.authc.ExpiredCredentialsException;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.authz.UnauthorizedException;import org.apache.shiro.subject.Subject;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class AccountController {    @RequestMapping("/loginPage")    public String loginPage(){            return "/login";    }        @RequestMapping(value = "/doLogin")      public String doLogin(HttpServletRequest request, Model model) {          String msg = "";          String username = request.getParameter("username");          String password = request.getParameter("password");         System.out.println("用户名: "+username+" 密码: "+password);        UsernamePasswordToken token = new UsernamePasswordToken(username, password);          token.setRememberMe(true);          Subject subject = SecurityUtils.getSubject();          try {              subject.login(token);              if (subject.isAuthenticated()) {                  return "redirect:/";              } else {                  return "/login";              }          } catch (IncorrectCredentialsException e) {              msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.";              model.addAttribute("message", msg);              System.out.println(msg);          } catch (ExcessiveAttemptsException e) {              msg = "登录失败次数过多";              model.addAttribute("message", msg);              System.out.println(msg);          } catch (LockedAccountException e) {              msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";              model.addAttribute("message", msg);              System.out.println(msg);          } catch (DisabledAccountException e) {              msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";              model.addAttribute("message", msg);              System.out.println(msg);          } catch (ExpiredCredentialsException e) {              msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";              model.addAttribute("message", msg);              System.out.println(msg);          } catch (UnknownAccountException e) {              msg = "帐号不存在. There is no user with username of " + token.getPrincipal();              model.addAttribute("message", msg);              System.out.println(msg);          } catch (UnauthorizedException e) {              msg = "您没有得到相应的授权!" + e.getMessage();              model.addAttribute("message", msg);              System.out.println(msg);          }          return "/login";      }          @RequestMapping("/doLogout")      public void doLogout(HttpServletRequest request,HttpServletResponse response) throws Exception{          Subject subject = SecurityUtils.getSubject();          if (subject != null) {              try{                  subject.logout();              }catch(Exception ex){              }          }          response.sendRedirect("loginPage");      }  }

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
login

登录

 

 

新增一个Realm1继承AuthorizingRealm类

package com.zns.realm;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.authc.LockedAccountException;import org.apache.shiro.authc.SimpleAuthenticationInfo;import org.apache.shiro.authc.UnknownAccountException;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.authz.AuthorizationInfo;import org.apache.shiro.crypto.hash.SimpleHash;import org.apache.shiro.realm.AuthorizingRealm;import org.apache.shiro.subject.PrincipalCollection;public class Realm1 extends AuthorizingRealm {    /**     * 认证     */    @Override    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {        //把AuthenticationToken转换成UsernamePasswordToken        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken)authenticationToken;        //获取username        String username=usernamePasswordToken.getUsername();        //根据username从数据库查询信息(注入并调用UserService方法),此处省略                        //根据获取的用户信息,决定是否抛出AuthenticationException异常,此处写死        if(username.equals("unknown")){            throw new UnknownAccountException("用户不存在!");                    }        if (username.equals("lock")) {            throw new LockedAccountException("用户被锁定!");        }                //构建并返回AuthenticationInfo,通常是SimpleAuthenticationInfo        //principal:可以是username,也可以是数据表对应的用户实体类对象        //credentials:从数据库获取的密码        //realmName:当前realm对象的name        Object principal=username;        //Object credentials="123456";        Object credentials=new SimpleHash("MD5", "123456", "", 1);        String realmName=this.getName();        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(principal, credentials, realmName);        return info;        }    /**     * 授权     */    @Override    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {                return null;    }    public static void main(String[] args) {        String algorithmName="MD5";        String source="123456";        String salt="";        int hashIterations=1;        Object result=new SimpleHash(algorithmName, source, salt, hashIterations);        System.out.println(result);    }}

运行项目测试登录认证功能.......

转载于:https://www.cnblogs.com/zengnansheng/p/10389583.html

你可能感兴趣的文章
其实我们可以少写点if else和switch
查看>>
一行代码让你的TableView动起来-iOS动画
查看>>
Spring Cloud实战系列(八) - 微服务监控Spring Boot Admin
查看>>
MySql相关语句总结
查看>>
史上最全面的React-react基础
查看>>
聊聊Git原理
查看>>
如何评价Normalize.css
查看>>
CSS实现元素居中原理解析
查看>>
React 快速上手 - 08 redux 状态管理 react-redux
查看>>
当程序员有了中年危机 你会发现你就是个屁
查看>>
关于同步的一点思考-上
查看>>
阿里云函数计算
查看>>
Java 10 新特性全览
查看>>
你真的会正确使用断言吗?
查看>>
Android点将台:济世儒侠[-ContentProvider-]
查看>>
java基础学习:JavaWeb之Cookie和Session
查看>>
骨架屏(Skeleton Screen)在Android中的应用
查看>>
Spring源码分析(三)手写简单的IOC容器和解决循环依赖问题
查看>>
MySQL索引笔记
查看>>
vue-router 嵌套路由
查看>>