侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 742 篇文章
  • 累计创建 64 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

安全/权限框架Shiro(5)之登录功能实现

zze
zze
2018-05-28 / 0 评论 / 0 点赞 / 629 阅读 / 7983 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

思路

  1. 获取当前用户即Subject,调用 SecurityUtils.getSubject()
  2. 判断当前用户是否已经被认证,即是否已登录。调用 Subject.isAuthenticated()
  3. 若没有被认证,则把用户名和密码封装为 UsernamePasswordToken 对象。
    a.创建一个表单页面。
    b.把请求提交到 SpringMVC 的 Handler。
    c.获取用户名和密码。
  4. 执行登录,调用 Subject.login(AuthenticationToken) 方法。
  5. 自定义认证 Realm,从数据库中获取对应用户的记录,返回给 Shiro。
    a.实际上需要继承 org.apache.shiro.realm.AuthenticatingRealm 类。
    b.实现 org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo 方法。
  6. 由 Shiro 完成用户名和密码的校验。

编码

1、创建登录控制器:

// com.zze.shiro.web.controller.LoginController
package com.zze.shiro.web.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {
    private static final transient Logger log = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping("login")
    public String login(String username, String password) {
        Subject currentUser = SecurityUtils.getSubject();
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);

            token.setRememberMe(true);
            try {
                currentUser.login(token);
            } catch (AuthenticationException ae) {
                System.out.println(ae.getMessage());
            }
        }
        return "redirect:list.jsp";
    }

    @RequestMapping("logout")
    public String logout() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "redirect:login.jsp";
    }
}

2、创建登录 Realm

// com.zze.shiro.realms.LoginRealm
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;

public class LoginRealm extends AuthenticatingRealm {


    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // authenticationToken 实际就是 Controller 中通过 Subject.Login 方法传入的 token,保存了前台输入的密码
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        // 获取页面传入的用户名
        String username = usernamePasswordToken.getUsername();
        // 根据用户名从数据库获取密码,假如获取到的是 123456
        String dbPassword = "123456";

        // 假如 unknown 用户名不存在
        if ("unknown".equals(username)) {
            throw new UnknownAccountException("用户名不存在");
        }
        // 假如 monster 用户名已经被锁定
        if ("monster".equals(username)) {
            throw new LockedAccountException("用户已被锁定");
        }

        // 根据用户情况,构建 AuthenticationInfo 对象返回,通常使用的实现类为 SimpleAuthenticationInfo
        // a. principal : 认证的实体信息,可以是 username,也可以是用户对应的实体对象
        Object principal = username;
        // b. credentials : 密码
        Object credentials = dbPassword;
        // c. realmName : 当前 realm 对象的 name,调用父类的 getName() 方法获得
        String realmName = getName();

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(principal, credentials, realmName);

        return simpleAuthenticationInfo; // 返回认证信息,交给 Shiro 完成比对

    }
}

3、修改登录页面:

<!-- login.jsp -->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Login Page</title>
</head>
<body>
<form action="/login" method="post">
    <table>
        <tr>
            <td>username:</td>
            <td><input type="text" name="username"></td>
        </tr>

        <tr>
            <td>password:</td>
            <td><input type="password" name="password"></td>
        </tr>
        <tr>
            <td colspan="2" style="text-align: center">
                <input type="submit" value="submit">
            </td>
        </tr>
    </table>
</form>
</body>
</html>

4、注意要修改 Spring 中的 Shiro 拦截配置,允许登录控制器匿名访问:

<!-- applicationContext.xml -->
<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--
    1、配置安全管理器 SecurityManager
    -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="cacheManager" ref="cacheManager"/>
        <property name="realm" ref="jdbcRealm"/>
    </bean>

    <!--
    2、配置缓存管理器 CacheManager
        a、需加入 ehcache jar 和 配置文件
    -->
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
    </bean>
    <!--
    4、配置 lifecycleBeanPostProcessor,可以自动调用配置在 Spring IOC 容器中 Shiro bean 的生命周期方法
    -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

    <!--
    5、启用 IOC 容器中使用 Shiro 注解,必须在配置 lifecycleBeanPostProcessor 之后才可使用
    -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor"/>

    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/login.jsp"/>
        <property name="successUrl" value="/list.jsp"/>
        <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
        <property name="filterChainDefinitions">
            <value>
                /logout = anon
                /login* = anon
                /** = authc
            </value>
        </property>
    </bean>
    <bean id="jdbcRealm" class="com.zze.shiro.realms.LoginRealm"/>
</beans>
0

评论区