1. 程式人生 > >CAS之5.2x版本自定義登入,多資料來源登入-yellowcong

CAS之5.2x版本自定義登入,多資料來源登入-yellowcong

通過自定義登入的策略,可以根據傳遞過來的引數,來確定使用那個資料庫查詢使用者資訊。這種方式,可以說是,爽歪歪啊。可以自己登入,設定資料來源來訪問。我後期加jdbctemplate的配置,將jdbc整合springboot裡面,這樣用的是springboot裡面資料來源。

學習要求

需要對於cas和springboot環境搭建有所瞭解,不然看著,都不知道我說得啥玩意。

專案地址

https://gitee.com/yellowcong/springboot_cas/tree/master/cas-server-login

目錄結構

這裡寫圖片描述

新增登入處理類

登入處理類,需要繼承AbstractPreAndPostProcessingAuthenticationHandler

這個類,複寫抽象方法supports和doAuthentication

驗證類

登入驗證類,這個類用於處理使用者登入的請求。大家可以發現,當我是admin的時候,不管是啥情況,俺都返回資料,如果是lock ,我就鎖住類。我還可以從資料庫中查詢資料,判斷使用者的情況。

package com.yellowcong.auth.handler;

import java.security.GeneralSecurityException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import
java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import javax.security.auth.login.AccountLockedException; import javax.security.auth.login.FailedLoginException; import org.apereo.cas.authentication.Credential; import org.apereo.cas.authentication.HandlerResult; import
org.apereo.cas.authentication.PreventedException; import org.apereo.cas.authentication.UsernamePasswordCredential; import org.apereo.cas.authentication.exceptions.AccountDisabledException; import org.apereo.cas.authentication.exceptions.InvalidLoginLocationException; import org.apereo.cas.authentication.handler.support.AbstractPreAndPostProcessingAuthenticationHandler; import org.apereo.cas.authentication.principal.PrincipalFactory; import org.apereo.cas.services.ServicesManager; /** * @author yellowcong * 建立日期:2018/02/02 * */ public class CustomerHandler extends AbstractPreAndPostProcessingAuthenticationHandler { public CustomerHandler(String name, ServicesManager servicesManager, PrincipalFactory principalFactory, Integer order) { super(name, servicesManager, principalFactory, order); } /** * 用於判斷使用者的Credential(換而言之,就是登入資訊),是否是俺能處理的 * 就是有可能是,子站點的登入資訊中不止有使用者名稱密碼等資訊,還有部門資訊的情況 */ @Override public boolean supports(Credential credential) { //判斷傳遞過來的Credential 是否是自己能處理的型別 return credential instanceof UsernamePasswordCredential; } /** * 用於授權處理 */ @Override protected HandlerResult doAuthentication(Credential credential) throws GeneralSecurityException, PreventedException { UsernamePasswordCredential usernamePasswordCredentia = (UsernamePasswordCredential) credential; //獲取傳遞過來的使用者名稱和密碼 String username = usernamePasswordCredentia.getUsername(); String password = usernamePasswordCredentia.getPassword(); Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); //直接是原生的資料庫配置啊 String url = "jdbc:mysql://127.0.0.1:3306/yellowcong"; String user = "root"; String pass = "root"; conn = DriverManager.getConnection(url,user, pass); //查詢語句 String sql = "SELECT * FROM cas_user WHERE username =? AND PASSWORD = ?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, username); ps.setString(2, password); ResultSet rs = ps.executeQuery(); if(rs.next()) { //允許登入,並且通過this.principalFactory.createPrincipal來返回使用者屬性 return createHandlerResult(credential, this.principalFactory.createPrincipal(username, Collections.emptyMap()), null); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { if(conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } //當是admin使用者的情況,直接就登入了,誰叫他是admin使用者呢 if(username.startsWith("admin")) { //直接返回去了 return createHandlerResult(credential, this.principalFactory.createPrincipal(username, Collections.emptyMap()), null); }else if (username.startsWith("lock")) { //使用者鎖定 throw new AccountLockedException(); } else if (username.startsWith("disable")) { //使用者禁用 throw new AccountDisabledException(); } else if (username.startsWith("invali")) { //禁止登入該工作站登入 throw new InvalidLoginLocationException(); } else if (username.startsWith("passorwd")) { //密碼錯誤 throw new FailedLoginException(); } else if (username.startsWith("account")) { //賬號錯誤 throw new AccountLockedException(); } return null; } }

配置注入類

我們寫好了處理登入的類後,需要注入到springboot,這樣我們才可以呼叫到我們的自定義登入類

package com.yellowcong.auth.conf;

import org.apereo.cas.authentication.AuthenticationEventExecutionPlan;
import org.apereo.cas.authentication.AuthenticationEventExecutionPlanConfigurer;
import org.apereo.cas.authentication.AuthenticationHandler;
import org.apereo.cas.authentication.principal.DefaultPrincipalFactory;
import org.apereo.cas.services.ServicesManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;

import com.yellowcong.auth.handler.CustomerHandler;

/**
 * @author yellowcong
 * 建立日期:2018/02/02
 *
 */
public class CustomConfiguration  implements AuthenticationEventExecutionPlanConfigurer {
    @Autowired
    @Qualifier("servicesManager")
    private ServicesManager servicesManager;

    //註冊驗證器
    @Bean
    public AuthenticationHandler customAuthenticationHandler() {
        //優先驗證
        return new CustomerHandler("customerHandler",
                servicesManager, new DefaultPrincipalFactory(), 1);
    }

    //註冊自定義認證器
    @Override
    public void configureAuthenticationExecutionPlan(final AuthenticationEventExecutionPlan plan) {
        plan.registerAuthenticationHandler(customAuthenticationHandler());
    }
}

package

用於讓springboot知道這個是根目錄,下面有類可以掃描注入

/**
 * @author yellowcong
 * 建立日期:2018/02/02
 *
 */
package com.yellowcong.auth;

配置spring.factories

SpringFactoriesLoader屬於Spring框架私有的一種擴充套件方案,其主要功能就是從指定的配置檔案META-INF/spring.factories載入配置。通過這個方法,我們就能將自定義的認證信方法。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.yellowcong.auth.conf.CustomConfiguration

debug方式帶詳情啟動cas

#加上-X 就可以檢視詳情了
build.cmd debug -X

這裡寫圖片描述

專案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 ">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.apereo.cas</groupId>
    <artifactId>cas-server-login</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>

    <dependencies>
        <dependency>
            <groupId>org.apereo.cas</groupId>
            <artifactId>cas-server-webapp${app.server}</artifactId>
            <version>${cas.version}</version>
            <type>war</type>
            <scope>system</scope>
            <optional>true</optional>
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/cas-server-webapp-tomcat-5.2.1.war</systemPath>
        </dependency>

        <!-- 自定義認證的方式 begin -->
        <dependency>
            <groupId>org.apereo.cas</groupId>
            <artifactId>cas-server-core-webflow</artifactId>
            <version>${cas.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apereo.cas</groupId>
            <artifactId>cas-server-core-authentication</artifactId>
            <version>${cas.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apereo.cas</groupId>
            <artifactId>cas-server-webapp-config</artifactId>
            <version>${cas.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- MYSQL -->
        <!-- 資料庫驅動 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>com.rimerosolutions.maven.plugins</groupId>
                <artifactId>wrapper-maven-plugin</artifactId>
                <version>0.0.4</version>
                <configuration>
                    <verifyDownload>true</verifyDownload>
                    <checksumAlgorithm>MD5</checksumAlgorithm>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${springboot.version}</version>
                <configuration>
                    <mainClass>${mainClassName}</mainClass>
                    <addResources>true</addResources>
                    <executable>${isExecutable}</executable>
                    <layout>WAR</layout>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <!-- 新增依賴的外掛 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.10</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/lib</outputDirectory>
                            <includeScope>system</includeScope>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <warName>cas</warName>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <recompressZippedFiles>false</recompressZippedFiles>
                    <archive>
                        <compress>false</compress>
                        <manifestFile>${manifestFileToUse}</manifestFile>
                    </archive>
                    <overlays>
                        <overlay>
                            <groupId>org.apereo.cas</groupId>
                            <artifactId>cas-server-webapp${app.server}</artifactId>
                        </overlay>
                    </overlays>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
            </plugin>
        </plugins>
        <finalName>cas</finalName>
    </build>



    <properties>
        <cas.version>5.2.2</cas.version>
        <springboot.version>1.5.8.RELEASE</springboot.version>
        <!-- app.server could be -jetty, -undertow, -tomcat, or blank if you plan to provide appserver -->
        <app.server>-tomcat</app.server> 

        <mainClassName>org.springframework.boot.loader.WarLauncher</mainClassName>
        <isExecutable>false</isExecutable>
        <manifestFileToUse>${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF</manifestFileToUse>

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

    <repositories>
        <repository>
            <id>sonatype-releases</id>
            <url>http://oss.sonatype.org/content/repositories/releases/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <releases>
                <enabled>true</enabled>
            </releases>
        </repository>
        <repository>
            <id>sonatype-snapshots</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
        <repository>
            <id>shibboleth-releases</id>
            <url>https://build.shibboleth.net/nexus/content/repositories/releases</url>
        </repository>
    </repositories>

    <profiles>
        <profile>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <id>exec</id>
            <properties>
                <mainClassName>org.apereo.cas.web.CasWebApplication</mainClassName>
                <isExecutable>true</isExecutable>
                <manifestFileToUse></manifestFileToUse>
            </properties>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.soebes.maven.plugins</groupId>
                        <artifactId>echo-maven-plugin</artifactId>
                        <version>0.3.0</version>
                        <executions>
                            <execution>
                                <phase>prepare-package</phase>
                                <goals>
                                    <goal>echo</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <echos>
                            <echo>Executable profile to make the generated CAS web application executable.</echo></echos>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <profile>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <id>pgp</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>com.github.s4u.plugins</groupId>
                        <artifactId>pgpverify-maven-plugin</artifactId>
                        <version>1.1.0</version>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>check</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <pgpKeyServer>hkp://pool.sks-keyservers.net</pgpKeyServer>
                            <pgpKeysCachePath>${settings.localRepository}/pgpkeys-cache</pgpKeysCachePath>
                            <scope>test</scope>
                            <verifyPomFiles>true</verifyPomFiles>
                            <failNoSignature>false</failNoSignature>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

登入驗證

表資料

CREATE DATABASE /*!32312 IF NOT EXISTS*/`yellowcong` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `yellowcong`;



DROP TABLE IF EXISTS `cas_user`;

CREATE TABLE `cas_user` (
  `username` varchar(32) NOT NULL DEFAULT '',
  `password` varchar(32) NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



insert  into `cas_user`(`username`,`password`) values ('yellowcong','yellowcong'),('doubi','doubi');

這裡寫圖片描述

登入驗證

登入我們的配置,登入後,我將資料來源裡面添加了一條資料(zhangsan:zhangsan),然後也能擋路上。

https://yellowcong.com:9000/

這裡寫圖片描述

錯誤集合

找不到類自定義的類

這個報錯,就是沒有找到我們預設填寫的處理類。我剛開始一臉矇蔽,後來發現是pom.xml檔案中配置的編譯版本的問題。
這裡寫圖片描述

外掛版本是3.1.0的,預設是2點幾的版本,就是由於這個才導致報錯的,害我找半天,鬱悶死我了。

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.1.0</version>
    <configuration>
        <warName>cas</warName>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <recompressZippedFiles>false</recompressZippedFiles>
        <archive>
            <compress>false</compress>
            <manifestFile>${manifestFileToUse}</manifestFile>
        </archive>
        <overlays>
            <overlay>
                <groupId>org.apereo.cas</groupId>
                <artifactId>cas-server-webapp${app.server}</artifactId>
            </overlay>
        </overlays>
    </configuration>
</plugin>

參考文章