spring整合shiro,實現登錄認證與授權


先貼出pom.xml  需要用到的依賴:

<?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">
    <parent>
        <artifactId>shiro</artifactId>
        <groupId>lyf.top.shiro</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>shiro-web</artifactId>
    <packaging>war</packaging>

    <name>shiro-web Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.0</version>
        </dependency>

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

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

        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.26</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.6</version>
        </dependency>

        <!--或者用hibernate或者mybatis都可以,這里就用jdbc來訪問數據了-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>shiro-web</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

接着創建一個自定義Realm:

package com.yunyun.shiro.realm;

import com.yunyun.dao.UserDao;
import com.yunyun.vo.user;
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.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserDao userDao;

    //授權
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        String userName = (String) principalCollection.getPrimaryPrincipal();
        //實際開發時這里從數據庫或者緩存中獲取角色數據
        Set<String> roles = getRolesByUserName(userName);

        Set<String> permissions = getPermissionsByUserName();
        //將取來的角色數據與權限數據返回
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //設置權限
        simpleAuthorizationInfo.setStringPermissions(permissions);
        //設置角色
        simpleAuthorizationInfo.setRoles(roles);

        return simpleAuthorizationInfo;
    }

    private Set<String> getPermissionsByUserName() {
        Set<String> sets= new HashSet<>();
        sets.add("user:delete");
        sets.add("user:add");
        return sets;
    }

    /**
     * 根據賬號取角色信息
     * @param userName
     * @return
     */
    private Set<String> getRolesByUserName(String userName) {
        List<String> list = userDao.queryRolesByUserName(userName);
        Set<String> sets = new HashSet<>(list);
        return sets;
    }

    //認證
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //1.通過主體傳過來的認證信息中去獲取用戶名
        String userName = (String)authenticationToken.getPrincipal();

        //2.通過用戶名到數據庫中獲取憑證
        String password = getPasswordByUserName(userName);
        if (password == null){
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo
                (userName,password,"customRealm");

        return authenticationInfo;
    }

    /**
     * 通過數據庫查詢憑證
     * @param userName
     * @return
     */
    private String getPasswordByUserName(String userName){
        //查詢數據庫
        user user = userDao.getUserByUserName(userName);
        if (user != null){
            return user.getPassword();
        }
        return null;
    }

    public static void main(String[] args){//數據庫中的密碼應該都是被MD5加密過的數據
        //所以需要在這里直接打印出加密后的密碼
        Md5Hash md5Hash = new Md5Hash("123qwe");
        System.out.println(md5Hash.toString());
    }
}

接着配置Spring,文件目錄如下:

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: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 http://www.springframework.org/schema/context/spring-context.xsd">

    <!--引入創建的配置文件-->
    <import resource="spring-dao.xml"/>
    <!--配置掃描路徑-->
    <context:component-scan base-package="com.yunyun"/>
    
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <!--登錄頁的url-->
        <property name="loginUrl" value="login.html"/>
        <!--未認證的跳轉頁面-->
        <property name="unauthorizedUrl" value="403.xml" />
        <!--過濾器鏈//從上往下匹配攔截認證,-->
        <property name="filterChainDefinitions">
            <value>
                <!--登錄頁面不需要攔截-->
                /login.html = anon
                <!--提交登錄請求的url也不許要攔截-->
                /subLogin = anon
                <!--登錄頁面以外的需要攔截認證-->
                /* = authc
            </value>
        </property>

    </bean>

    <!--創建SecurityManager對象-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!--將realm設置到securityManager主體中-->
        <property name="realm" ref="realm"/>
    </bean>

    <bean class="com.yunyun.shiro.realm.CustomRealm" id="realm">
        <!--將加密管理器對象,加入到自定義的Realm中-->
        <property name="credentialsMatcher" ref="credentialsMatcher"/>
    </bean>

    <!--加密管理器對象-->
    <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"
          id="credentialsMatcher">
        <!--設置加密算法為MD5-->
        <property name="hashAlgorithmName" value="md5"/>
        <!--設置加密次數為1次-->
        <property name="hashIterations" value="1"/>

    </bean>

</beans>

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

    <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
        <property name="url" value="jdbc:mysql://localhost:3306/test"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

spring-mvc.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:p="http://www.springframework.org/schema/p"
       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-3.0.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-3.2.xsd">

    <!--確定掃描路徑-->
    <context:component-scan base-package="com.yunyun.controller"/>

    <mvc:annotation-driven/>

    <mvc:resources mapping="/*" location="/" />
</beans>

接着寫接口UserDao:

public interface UserDao {
    user getUserByUserName(String userName);

    List<String> queryRolesByUserName(String userName);
}

實現類:

@Component
public class UserDaoImpl implements UserDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public user getUserByUserName(String userName) {

        String sql = "select username,password from users where username = ?";
        List<user> list = jdbcTemplate.query(sql, new String[]{userName}, new RowMapper<user>(){
            @Override
            public user mapRow(ResultSet resultSet, int i) throws SQLException {
                //將查詢到的結果集 設置到對象中
                user user = new user();
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        });

        //判斷集合是否為空
        if (CollectionUtils.isEmpty(list)){
            //若為空直接返回null
            return null;
        }

        //若不為空,直接返回集合的第一條(因為username肯定不會重復,結果肯定唯一)
        return list.get(0);
    }

    @Override
    public List<String> queryRolesByUserName(String userName) {
       String sql = "select role_name from user_roles where username = ?";

       //直接返回結果集
        return jdbcTemplate.query(sql, new String[]{userName}, new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getString("role_name");
            }
        });
    }
}

這里的sql都是自定義sql,也可以將sql改成自己的數據庫操作。

接着創建controller:

@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();
        }

        if (subject.hasRole("admin")){
            return "有admin權限";
        }else {
            return "無admin權限";
        }
    }
}

 user實體類里只有username與password和它們的set、get方法。

然后運行項目:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM