shiro篇:使用Shiro对一个SSM项目进行身份加密验证

Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理

1.配置环境

1.1pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>1014_1_shirowebspring</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-all</artifactId>
            <version>1.4.0</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
    </dependencies>
</project>

1.2web.xml配置spring+spingMVC+乱码过滤+shiroFilter过滤

<?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">
    <!--spring-->
    <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>

<!--    springMVC-->
    <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:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
<!--    乱码处理-->
    <!--3.处理乱码-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

<!--    shiroFilter-->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    
    
    
    
</web-app>

1.3 Spring的配置:applicationContext-shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <!--shiro+spring整合的核心配置-->
    <!--1.SecurityManager-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!--配置realm-->
        <property name="realms" ref="myUerRealm"></property>
    </bean>
    <!--2.配置自定义realm,走数据库  不用默认的iniRealm shiro.ini,不利于后期维护-->
    <bean id="myUerRealm" class="realm.MyRealm"></bean>

    <!--3.shiroFilter,shiro拦截后会把请求,交给该过滤器处理,id需要和web.xml中配置的名字一致-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!--        登录界面-->
        <property name="loginUrl" value="/login.jsp"></property>
<!--        没有权限的跳转-->
        <property name="unauthorizedUrl" value="/unauthorized.jsp"></property>

        <property name="securityManager" ref="securityManager"></property>
        <property name="filterChainDefinitions">
<!--
            1.顺序问题:  严格的(/** = authc)过滤器往后配置
            2.anon:     匿名访问,不登录就可以访问
            3.authc :   认证后访问
-->
            <value>
                /doLogin = anon
                /js/** = anon
                /** = authc
            </value>
        </property>
    </bean>


</beans>

1.4SpringMVC的环境springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="controller"></context:component-scan>

    <mvc:annotation-driven></mvc:annotation-driven>

    <!--    静态资源放行问题1-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>

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

2.创建一个自定义realm类

package realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * zt
 * 2020/10/14
 * 11:08
 */
public class MyRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("---------->授权");
        return null;
    }

    /**
     *subject.login(token);  在controller中查找执行认证方法
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("---------->认证,登录");

        String username = (String) token.getPrincipal();
        String password = new String((char[])token.getCredentials());

        String u = "admin";//数据库的,写死
//        String p = "123";//数据库
        String p = "3cb336337a3bdceb3c0b65bdcc5f122c";
        int isLock = 1;
        if(!username.equals(u)) {//账号错误
            throw new UnknownAccountException("账号异常");
        }
        if(!password.equals(p)) {//密码错误
            throw new IncorrectCredentialsException("密码错误");
        }
        if(isLock!=1){
            throw new LockedAccountException("账户锁定");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,password,this.getName());

        return info;
    }
}

3.创建controller

package controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * zt
 * 2020/10/14
 * 11:28
 */
@Controller
public class MyController {
    @RequestMapping("/doLogin")
    public String doLogin(String username,String password){
        System.out.println("登录");
        //1.shiro认证
        Subject subject = SecurityUtils.getSubject();
        //加密
        password = new Md5Hash(password, username, 2014).toString();
        System.out.println(password);
        //2.把用户输入的用户名和密码封装成一个usernamePasswordToken对象
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        //3.登录  查找,执行认证方法
        subject.login(token);

        System.out.println(subject.isAuthenticated()?"登录成功":"登录失败");
        return "success";
    }

}

4.写一个页面测试

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: 49841
  Date: 2020/10/14
  Time: 11:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<form action="/doLogin" method="post">
    <input type="text" name="username" id="id"><br>
    <input type="text" name="password"  id="name"><br>

    <input type="submit" value="提交" id="btn">
</form>
</body>
</html>

success.jsp

<%--
  Created by IntelliJ IDEA.
  User: 49841
  Date: 2020/10/14
  Time: 11:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--shiro标签--%>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
success
<shiro:principal></shiro:principal>,欢迎您!!!!!!
<shiro:authenticated>success</shiro:authenticated>
<shiro:guest>guest</shiro:guest>
</body>
</html>

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
好的,下面是一个Spring+SpringMVC+Mybatis的SSM使用Shiro进行登陆验证的完整程序示例: 1. 添加依赖 在pom.xml文件中添加Shiro的依赖: ```xml <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.7.1</version> </dependency> ``` 2. 配置Shiro 在Spring的配置文件中添加Shiro的配置,例如在applicationContext.xml中添加如下配置: ```xml <!-- Shiro配置 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myRealm" /> </bean> <bean id="myRealm" class="com.example.shiro.MyRealm"> <property name="credentialsMatcher"> <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <property name="hashAlgorithmName" value="SHA-256" /> </bean> </property> </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="/index.jsp" /> <property name="unauthorizedUrl" value="/unauthorized.jsp" /> <property name="filterChainDefinitions"> <value> /login.jsp = anon /login.do = anon /logout.do = logout /** = authc </value> </property> </bean> ``` 其中,securityManager配置了SecurityManager实现类;myRealm配置了自定义的Realm实现类;shiroFilter配置了ShiroFilter的相关设置。 3. 编写Realm实现类 创建一个自定义的Realm实现类,用于验证用户的账号和密码。具体代码如下: ```java import java.util.HashSet; import java.util.Set; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; public class MyRealm extends AuthorizingRealm { //模拟数据库中的用户信息 private static final String USERNAME = "admin"; private static final String PASSWORD = "admin"; private static final String SALT = "123456"; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { //授权 Set<String> roles = new HashSet<>(); roles.add("admin"); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(roles); return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //认证 UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); if (!USERNAME.equals(username)) { return null; } String password = PASSWORD; String salt = SALT; HashedCredentialsMatcher matcher = new HashedCredentialsMatcher("SHA-256"); matcher.setHashIterations(1024); SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, password, matcher); authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(salt)); return authenticationInfo; } } ``` 其中,doGetAuthorizationInfo方法用于授权,可以设置用户的角色和权限;doGetAuthenticationInfo方法用于认证,可以验证用户的账号和密码。 4. 编写登陆验证代码 在Java代码中创建一个Shiro的工具类,用于登陆验证和权限控制。具体代码如下: ```java import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; public class ShiroUtils { @Autowired private SecurityManager securityManager; public boolean login(String username, String password) { //1.将SecurityManager设置到运行环境中 SecurityUtils.setSecurityManager(securityManager); //2.创建Subject Subject subject = SecurityUtils.getSubject(); //3.创建Token UsernamePasswordToken token = new UsernamePasswordToken(username, password); try { //4.登陆 subject.login(token); return true; } catch (UnknownAccountException e) { //用户名不存在 System.out.println("用户名不存在"); } catch (IncorrectCredentialsException e) { //密码错误 System.out.println("密码错误"); } catch (LockedAccountException e) { //账户被锁定 System.out.println("账户被锁定"); } catch (AuthenticationException e) { //认证失败 System.out.println("认证失败"); } return false; } public void logout() { //1.获取Subject Subject subject = SecurityUtils.getSubject(); //2.登出 subject.logout(); } } ``` 5. 在Controller中使用Shiro进行登陆验证 在需要进行登陆验证的Controller中,引入ShiroUtils,并调用其login方法进行验证。具体代码如下: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class LoginController { @Autowired private ShiroUtils shiroUtils; @RequestMapping("/login.do") public String login(String username, String password) { if (shiroUtils.login(username, password)) { return "redirect:/index.jsp"; } else { return "redirect:/login.jsp"; } } } ``` 以上就是一个简单的Spring+SpringMVC+Mybatis的SSM使用Shiro进行登陆验证的完整程序示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值