美文网首页
Spring整合Shiro

Spring整合Shiro

作者: JiangCheng97 | 来源:发表于2020-02-19 21:46 被阅读0次

    1、新建一个module,创建一个maven web项目

    2、在WEB-INF下新建一个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">
        <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>
    
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring.xml</param-value>
        </context-param>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
        <servlet>
            <servlet-name>DispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring/springmvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
            <async-supported>true</async-supported>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>DispatcherServlet</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <!-- 注册spring提供的针对POST请求的中文乱码问题 -->
        <filter>
            <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    </web-app>
    
    

    3、在resource下新建一个Spring文件夹,在Spring文件夹下新建spring.xml和springmvc.xml

    Spring.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/context
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
            <property name="securityManager" ref="securityManager"></property>
            <property name="loginUrl" value="login.html"></property>
            <property name="unauthorizedUrl" value="403.html"></property>
            <property name="filterChainDefinitions">
                <value>
                    /login.html = anon
                    /subLogin = anon
                    /* = authc
                </value>
            </property>
        </bean>
    
        <!--创建SecurityManager对象-->
        <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
            <property name="realm" ref="realm"></property>
        </bean>
    
        <bean id="realm" class="com.zjc.shiro.realm.CustomRealm">
            <property name="credentialsMatcher" ref="credentialsMatcher" />
        </bean>
    
        <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher" id="credentialsMatcher">
            <property name="hashAlgorithmName" value="md5"/>
            <property name="hashIterations" value="1"/>
        </bean>
    </beans>
    

    springmvc.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/context
           https://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="com.zjc.controller"/>
    
        <mvc:annotation-driven />
        
        <mvc:resources mapping="/*" location="/" />
    </beans>
    

    4、新建自定义Realm

    package com.zjc.shiro.realm;
    
    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.authz.AuthorizationInfo;
    import org.apache.shiro.authz.SimpleAuthorizationInfo;
    import org.apache.shiro.realm.AuthorizingRealm;
    import org.apache.shiro.subject.PrincipalCollection;
    import org.apache.shiro.util.ByteSource;
    
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    import java.util.Set;
    
    public class CustomRealm extends AuthorizingRealm {
    
        Map<String, String> userMap = new HashMap<>();
    
        {
            userMap.put("zjc", "bfe76993b7209d38fe91de3021fa2b36");
            super.setName("customRealm");
        }
    
        /**
         * 自定义授权过程
         *
         * @param principals
         * @return
         */
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            String userName = (String) principals.getPrimaryPrincipal();
    
            //从数据或者缓存中获取角色数据
            Set<String> roles = getRolesByUserName(userName);
    
            //从数据或者缓存中获取权限数据
            Set<String> permissions = getPermissionsByUserName(userName);
    
    
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    
            simpleAuthorizationInfo.setStringPermissions(permissions);
            simpleAuthorizationInfo.setRoles(roles);
            return simpleAuthorizationInfo;
    
    
        }
    
        private Set<String> getPermissionsByUserName(String userName) {
            Set<String> sets = new HashSet<>();
            sets.add("user:delete");
            sets.add("user:add");
            return sets;
    
        }
    
        private Set<String> getRolesByUserName(String userName) {
            Set<String> sets = new HashSet<>();
            sets.add("admin");
            sets.add("user");
            return sets;
    
        }
    
        /**
         * 自定义认证的过程
         *
         * @param token
         * @return
         * @throws AuthenticationException
         */
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    
            //1、从主体传过来的认证信息中,获得用户名
            String userName = (String) token.getPrincipal();
    
            //2、通过用户名到数据库中获取凭证
            String password = getPasswordByUserName(userName);
    
            if (password == null) {
                return null;
            }
    
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("zjc", password, "customRealm");
    
            //设置盐
            authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("zjc"));
            return authenticationInfo;
        }
    
        /**
         * 模拟数据库查询凭证
         *
         * @param userName
         * @return
         */
        private String getPasswordByUserName(String userName) {
            return userMap.get(userName);
        }
    
    
    }
    
    

    5、新建login.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>登陆</title>
    </head>
    <body>
     <form action="subLogin" method="post">
         用户名:<input type="text" name="username" /><br>
         密码:<input type="password" name="password" /><br>
         <input type="submit" value="登陆">
     </form>
    </body>
    </html>
    

    6、创建UserController

    package com.zjc.controller;
    
    import com.zjc.entity.User;
    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.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    
    @Controller
    public class UserController {
    
        @RequestMapping(value = "/subLogin",method = RequestMethod.POST,
                produces = "application/json;charset=utf-8")
        @ResponseBody
        public String subLogin(User user){
            Subject subject = SecurityUtils.getSubject();
    
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
    
            try {
                subject.login(token);
            } catch (AuthenticationException e) {
               return e.getMessage();
            }
            return "登陆成功";
        }
    }
    
    

    7、创建User实体类

    package com.zjc.entity;
    
    public class User {
    
        private String username;
    
        private String password;
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Spring整合Shiro

          本文链接:https://www.haomeiwen.com/subject/pkmzfhtx.html