好好编程-物流项目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";
}


操作测试即可


相关文章
|
2月前
|
SQL JSON 缓存
小说系统方案搭建开发,实现系统的用户登录验证说明
本文总结了小说系统源码中常见的身份认证方式,涉及JWT和Shiro。传统的认证流程包括用户提交凭证、服务器保存Session数据、发送Session_id给客户端,后续请求携带Session_id。但这种方式在多服务器或跨域场景下扩展性差。解决方案有Session数据共享或持久化。作者将服务端维护Session信息的认证方式归类为传统方式,反之为非传统方式,后者扩展性更优。文中还介绍了实例项目的SQL建表结构,用于演示认证流程。
|
3月前
|
小程序 JavaScript IDE
【社区每周】如何实现小程序代码热更新?芝麻工作证新增“企业员工”职业身份验证(1月第四期)
【社区每周】如何实现小程序代码热更新?芝麻工作证新增“企业员工”职业身份验证(1月第四期)
19 0
|
4月前
|
JavaScript 小程序 Java
基于Java的养老院管理系统的设计与实现(亮点:多角色、登录验证码、留言反馈)
基于Java的养老院管理系统的设计与实现(亮点:多角色、登录验证码、留言反馈)
24 0
|
5月前
|
前端开发 Java 关系型数据库
基于Springboot实现专业认证材料管理系统
基于Springboot实现专业认证材料管理系统
|
6月前
|
NoSQL 前端开发 数据库
淘东电商项目(36) -SSO单点登录(退出功能)
淘东电商项目(36) -SSO单点登录(退出功能)
31 0
|
6月前
|
移动开发 NoSQL Redis
淘东电商项目(35) -SSO单点登录(登录功能完善)
淘东电商项目(35) -SSO单点登录(登录功能完善)
46 0
|
9月前
|
存储 缓存
若依项目如何实现一个账户只能一个人登录(汇总)
若依项目如何实现一个账户只能一个人登录(汇总)
626 0
|
SQL 前端开发 Java
Java开发:实现用户注册登录的功能
在Java开发过程中,实现用户的注册功能是最基本的,用户通过手机号或者邮箱作为注册账号也是非常常见的操作方式,不管是通过手机号注册或者邮箱注册,原理都差不多,那么本文就来分享一下在Java开发过程中的用户注册账号的功能实现。
267 0
Java开发:实现用户注册登录的功能
|
前端开发
前端工作总结209-第三方登录
前端工作总结209-第三方登录
39 0
前端工作总结209-第三方登录
|
数据库
在线教育项目用户登录和注册(一)
在线教育项目用户登录和注册(一)
64 0
在线教育项目用户登录和注册(一)