spring整合shiro,實現登陸認證與受權

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

<?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:java

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,文件目錄以下:mysql

spring.xml代碼以下:web

<?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代碼以下:spring

<?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:sql

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改爲本身的數據庫操做。apache

接着建立controller:json

@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方法。

而後運行項目:

相關文章
相關標籤/搜索