好好编程-物流项目13【登录认证-shiro实现】

简介: 我们已经完成了用户的CRUD操作。本文我们来介绍下基于Shiro的登录认证操作。

我们已经完成了用户的CRUD操作。本文我们来介绍下基于Shiro的登录认证操作。


登录认证


1.整合shiro


1.1 添加依赖

<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-spring</artifactId>
</dependency>


1.2 web.xml中注册

<!-- shiro过虑器,DelegatingFilterProxy通过代理模式将spring容器中的bean和filter关联起来 -->
<filter>
  <filter-name>shiroFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <!-- 设置true由servlet容器控制filter的生命周期 -->
  <init-param>
    <param-name>targetFilterLifecycle</param-name>
    <param-value>true</param-value>
  </init-param> 
  <!-- 设置spring容器filter的bean id,如果不设置则找与filter-name一致的bean -->
  <init-param>
    <param-name>targetBeanName</param-name>
    <param-value>shiro</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>shiroFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>


1.3 自定义Realm

/**
 * 自定义的Realm
 * @author 波波烤鸭
 *
 * dengpbs@163.com
 */
public class MyRealm extends AuthorizingRealm{
  /**
   * 认证的方法
   */
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    // TODO Auto-generated method stub
    return null;
  }
  /**
   * 授权的方法
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    // TODO Auto-generated method stub
    return null;
  }
}


1.4 添加shiro的配置文件


20190322192828569.png

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
  <!-- 注册自定义Realm -->
  <bean class="com.bobo.realm.MyRealm" id="myRealm">
  </bean>
  <!-- 注册SecurityManager -->
  <bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
    <!-- 配置自定义Realm -->
    <property name="realm" ref="myRealm"/>
  </bean>
  <!-- 注册ShiroFilterFactoryBean 注意id必须和web.xml中注册的targetBeanName的值一致 -->
  <bean class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" id="shiro">
    <!-- 注册SecurityManager -->
    <property name="securityManager" ref="securityManager"/>
    <!-- 登录地址 如果用户请求的的地址是 login.do 那么会对该地址认证-->
    <property name="loginUrl" value="/login.do"/>
    <!-- 登录成功的跳转地址 -->
    <property name="successUrl" value="/main"/>
    <!-- 访问未授权的页面跳转的地址 -->
    <property name="unauthorizedUrl" value="/jsp/refuse.jsp"/>
    <!-- 设置 过滤器链 -->
    <property name="filterChainDefinitions">
      <value>
        <!--加载顺序从上往下。
          authc需要认证
          anon可以匿名访问的资源
         -->
         / = anon
                /login = anon
                /images/** = anon
                /css/** = anon
                /js/** = anon
                /lib/** = anon
                /login.do = authc
                /** = authc
      </value>
    </property>
  </bean>
</beans>


2.登录实现


20190323100610107.png


2.1登录界面


http://localhost:8082/ 或者 http://localhost:8082/login


20190322194135942.png20190322194245101.png

登录页面代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>欢迎登录后台管理系统</title>
<link href="/css/style.css" rel="stylesheet" type="text/css" />
<script language="JavaScript" src="/js/jquery.js"></script>
<script src="/js/cloud.js" type="text/javascript"></script>
<script language="javascript">
  $(function() {
    $('.loginbox').css({
      'position' : 'absolute',
      'left' : ($(window).width() - 692) / 2
    });
    $(window).resize(function() {
      $('.loginbox').css({
        'position' : 'absolute',
        'left' : ($(window).width() - 692) / 2
      });
    })
  });
</script>
</head>
<body
  style="background-color: #1c77ac; background-image: url(/images/light.png); background-repeat: no-repeat; background-position: center top; overflow: hidden;">
  <div id="mainBody">
    <div id="cloud1" class="cloud"></div>
    <div id="cloud2" class="cloud"></div>
  </div>
  <div class="logintop">
    <span>欢迎登录后台管理界面平台</span>
    <ul>
      <li><a href="#">回首页</a></li>
      <li><a href="#">帮助</a></li>
      <li><a href="#">关于</a></li>
    </ul>
  </div>
  <div class="loginbody">
    <span class="systemlogo"></span>
    <div class="loginbox">
      <form action="/login.do" method="post">
        <ul>
          <li><input name="username" type="text" class="loginuser" />
          </li>
          <li><input name="password" type="password" class="loginpwd" />
          </li>
          <li><input name="" type="submit" class="loginbtn" value="登录"/>
            <label>
              <input name="" type="checkbox" value="" checked="checked" />记住密码
            </label>
            <label>
              <ahref="#">忘记密码?</a>
            </label>
          </li>
        </ul>
      </form>
    </div>
  </div>
  <div style="display: none">
    <script src='http://v7.cnzz.com/stat.php?id=155540&web_id=155540'
      language='JavaScript' charset='gb2312'></script>
  </div>
</body>
</html>


2.2登录认证


UserServiceImpl中修改query方法

@Override
public List<User> query(User user) {
  UserExample example = new UserExample();
  if(user!=null){
    if(!"".equals(user.getUserName()) && user.getUserName()!= null){
      // 根据账号查询
      example.createCriteria().andUserNameEqualTo(user.getUserName());
    }
  }
  return userMapper.selectByExample(example);
}


自定义Realm中完成认证的逻辑

@Resource
private IUserService userService;
/**
 * 认证的方法
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  // 获取提交的账号
  UsernamePasswordToken t = (UsernamePasswordToken) token;
  // 获取登录的账号
  String userName = t.getUsername();
  User user = new User();
  user.setUserName(userName);
  List<User> list = userService.query(user);
  if(list == null || list.size() > 1){
    // 账号不存在或者用户过多都返回null
    return null;
  }
  user = list.get(0);
  SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(),"bobo");
  return info;
}


完成controller逻辑

@Controller
public class LoginController {
  /**
   * 设定登录失败跳转的资源以及获取失败的信息
   * 
   * @param model
   * @param request
   * @return
   */
  @RequestMapping("/login.do")
  public String login(Model model, HttpServletRequest request) {
    Object ex = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
    if (ex != null) {
      System.out.println(ex.toString() + "----------");
    }
    if (UnknownAccountException.class.getName().equals(ex)) {
      System.out.println("----账号不正确----->");
      model.addAttribute("msg", "账号不正确");
    } else if (IncorrectCredentialsException.class.getName().equals(ex)) {
      System.out.println("----密码不正确----->");
      model.addAttribute("msg", "密码不正确");
    } else {
      System.out.println("----其他错误----->");
      model.addAttribute("msg", "其他错误");
    }
    return "login";
  }
}

3.测试


 启动后随便输入一个地址,会发现重新跳回了登录页面

http://localhost:8082/aaabcc


20190322200003868.png

登录测试

20190322200747162.png20190322200930840.png



账号密码正确的情况下进入了main.jsp页面


20190322201013330.png

4.退出功能

20190322201238911.png


top.jsp中修改

20190322201328998.png

LoginController中添加退出的方法

/**
 * 退出登录
 * @return
 */
@RequestMapping("/logout.do")
public String logout(){
  SecurityUtils.getSubject().logout();
  return "login";
}


操作测试即可


相关文章
|
11月前
|
存储 弹性计算 人工智能
2026年阿里云个人及企业用户新购和续费云服务器活动及优惠政策
2026年阿里云推出众多优惠政策,涵盖新购、续费、升级等多方面,形成全生命周期成本优化体系。个人用户可享38元秒杀、99元经济型实例及学生专属福利;企业用户则有199元普惠套餐、高性能实例及跨境专项补贴。全用户还可共享免费试用、权益领券与迁移补贴。用户应根据业务需求,选择适配方案,并善用优惠券和组合套餐,提前锁定低价,从而实现成本与效率的双重优化提升。
|
存储 Go
Go语言之接口与多态 -《Go语言实战指南》
Go 语言中的接口是实现多态的核心机制,通过一组方法签名定义行为。任何类型只要实现接口的所有方法即视为实现该接口,无需显式声明。本文从接口定义、使用、底层机制、组合、动态行为到工厂模式全面解析其特性与应用,帮助理解 Go 的面向接口编程思想及注意事项(如 `nil` 陷阱)。
456 22
|
安全 数据安全/隐私保护 Windows
Windows 查看已保存wifi密码
Windows 查看已保存wifi密码
3064 0
Windows 查看已保存wifi密码
|
机器学习/深度学习 数据采集 人工智能
【人工智能】机器学习介绍以及机器学习流程
机器学习(Machine Learning,ML)是一门多领域交叉学科,涉及 概率论、统计学、逼近论、凸分析、算法复杂度理论等多门学科。 研究计算机怎样模拟或实现人类的学习行为,以获取新的知识或技 能,重新组织已有的知识结构使之不断改善自身的性能。 普遍认为,机器学习的处理系统和算法是主要通过找出数据里隐藏 的模式进而做出预测的识别模式,它是人工智能的一个重要子领域。
737 1
【人工智能】机器学习介绍以及机器学习流程
|
人工智能 算法 搜索推荐
算法渣-排序-桶排序
没有一身好内功,招式再多都是空;算法绝对是防身必备,面试时更是不可或缺;跟着算法渣一起从零学算法
366 0
算法渣-排序-桶排序
|
机器人
LeetCode 5448. 判断路径是否相交(195周赛)
给你一个字符串 `path`,其中 `path[i]` 的值可以是 `'N'`、`'S'`、`'E'` 或者 `'W'`,分别表示向北、向南、向东、向西移动一个单位。
591 0
|
Web App开发 JavaScript 前端开发
漂浮广告代码兼容ie、firefox,多个漂浮不冲突,调用只需两行代码
原文:漂浮广告代码兼容ie、firefox,多个漂浮不冲突,调用只需两行代码 将广告内容放在div中,设置一个id,然后用下面方法调用var adcls=new AdMove("div的id");adcls.
1162 0
|
1天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8055 2
|
10天前
|
域名解析 人工智能 Linux
|
20天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
18201 63