Shiro 的整合 Spring 的第一个例子之 JdbcRealm

本文详细记录了一位开发者在整合Spring Security与Apache Shiro时遇到的登录失败问题。通过逐步排查,发现realm配置为空以及`authenticationQuery`的SQL错误是问题所在。修复这些问题后,成功实现了登录功能。主要涉及的数据源配置、Shiro Filter、realm设置、以及登录控制器的代码都在文中给出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我是看这篇文章做的,但是其中有一个坑,困扰了我很久,总算弄完了,算是帮助了我 debug 认真的看了一遍源码吧 其实我不仅会 Spring Security,Shiro 也略懂一二!

  • 添加依赖
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>RELEASE</version>
        </dependency>

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.27</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>RELEASE</version>
        </dependency>
  • web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--<session-config>-->
        <!--<tracking-mode>COOKIE</tracking-mode>-->
    <!--</session-config>-->

</web-app>
  • 添加applicationContext.xml和spring-servlet.xml配置文件,先贴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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


    <context:property-placeholder location="classpath:dataSource.properties"/>
    <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
        <property name="url" value="${mysql.url}"></property>
        <property name="username" value="${mysql.username}"></property>
        <property name="password" value="${mysql.password}"></property>
        <property name="driverClassName" value="${mysql.driver-class}"></property>
    </bean>
    <bean class="org.apache.shiro.realm.jdbc.JdbcRealm" id="jdbcRealm">
        <property name="dataSource" ref="dataSource"></property>
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <property name="hashIterations" value="1024"></property>
                <property name="hashAlgorithmName" value="sha-512"></property>
            </bean>
        </property>
        <property name="saltIsBase64Encoded" value="false"></property>
        <property name="saltStyle" value="COLUMN"></property>
        <property name="authenticationQuery" value="select password,username from users where username = ?"></property>
    </bean>

    <bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
    </bean>
    <bean class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" id="shiroFilter">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/login.jsp"></property>
        <property name="successUrl" value="/success.jsp"/>
        <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
        <property name="filterChainDefinitions">
            <value>
                /login=anon
                /**=authc
            </value>
        </property>
    </bean>

</beans>
<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.shiro"/>
    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>
  • 数据源 dataSource.properties
mysql.username=root
mysql.password=root
mysql.driver-class=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&relaxAutoCommit=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
  • 添加 Controller
    @RequestMapping("/login")
    public String login(String username,String password) {
        System.out.println(username+"-"+password);
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            currentUser.login(token);
            return "success";
        }catch (UnknownAccountException e){
            System.out.println("未知用户");
            return "unauthorized";
        }catch (IncorrectCredentialsException e){
            System.out.println("密码不正确");
            return "unauthorized";
        }
    }
  • 添加三个页面,login、success、unauthorized
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form method="post" action="/login">
        <div class="login-background">
            <div class="login-title">用户登录</div>
            <div class="login-input">
                <i class="fa fa-user"></i>
                <input type="text" placeholder="用户名" name="username" />
            </div>
            <div class="login-input">
                <i class="fa fa-lock"></i>
                <input type="password" placeholder="密码" name="password" />
            </div>
            <button type="submit" class="btn login-btn">立即登录</button>
        </div>
    </form>

</body>
</html>
  • 数据库三个表,随便创建

结果登录失败,最后 debug 发现 realms 为空,需要注入 realm,然后 authenticationQuery 的 SQL 也不对,第一个参数是密码,第二个参数是 密码盐,修改如下图

<-- 给securityManager注入jdbcRealm -->
<bean class="org.apache.shiro.web.mgt.DefaultWebSecurityManager" id="securityManager">
        <property name="realm" ref="jdbcRealm"></property>
</bean>
    <bean class="org.apache.shiro.realm.jdbc.JdbcRealm" id="jdbcRealm">
        <property name="dataSource" ref="dataSource"></property>
        <property name="credentialsMatcher">
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <property name="hashIterations" value="1024"></property>
                <property name="hashAlgorithmName" value="sha-512"></property>
            </bean>
        </property>
        <property name="saltIsBase64Encoded" value="false"></property>
        <property name="saltStyle" value="COLUMN"></property>
        <property name="authenticationQuery" value="select password,password_salt from users where username = ?"></property>
    </bean>

最终登录成功。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值