CAS Https and Database authentication (iii)

Source: Internet
Author: User
Tags aop cas sessions log4j

CAS Https and Database authentication (iii)

tags (space delimited): CAS

Sso-examples-guides Source

Intro (Introduction)

From the previous section, we know Apereo CAS that the official default is to use HTTPS for deployment:
For security, we use HTTPS and disable static account information.

What do you ' ll need (need to master)
    • JDK 1.8 or later
    • Maven 3.2+
    • Spring Boot
    • Spring Tool Suite (STS)
    • IntelliJ idea
    • Keytool
Generate certificate Generate key
keytool -genkey -alias ssokeystore  "CN=www.galsang.org,OU=galsang.org,O=galsang,L=Shanghai,ST=Shanghai,C=CN""san=dns:www.galsang.org,ip:192.168.6.53"
Export certificate
keytool -export -file D:/sso/ssokeystore.crt -alias ssokeystore  -keystore D:/sso/sso.keystore  -keypass 123456 -storepass 123456# 或keytool -exportcert -alias ssokeystore   -keystore D:/sso/sso.keystore -file D:/sso/ssokeystore.crt -keypass 123456 -storepass 123456
Import certificate to local JDK (client authentication)
keytool -import -alias ssokeystore   -keystore D:/javaspace/Java/jdk1.8.0_131/jre/lib/security/cacerts -file D:/sso/ssokeystore.crt -keypass changeit -storepass changeit
Delete a certificate

If you have previously imported the certificate for that alias ssokeystore , delete the certificate

keytool -delete -alias ssokeystore   -keystore D:/javaspace/Java/jdk1.8.0_131/jre/lib/security/cacerts -keypass changeit -storepass changeit
View KeyStore Certificates
keytool -list  -keystore D:/javaspace/Java/jdk1.8.0_131/jre/lib/security/cacerts -keypass changeit -storepass changeit
View specified certificate contents
keytool  -printcert  "D:/sso/ssokeystore.crt "
HTTPS configuration

Step one: Copy the generated key sso.keystore to the src/main/resources directory
Step Two: Configure
Since the 5.2.3 version is turned on by default, it is closed first and then turned on and configured later on in production:
Ticket Granting Cookies

cas:  tgc:    secure: false  # cas.tgc.secure=true

Step Three: application.yml configure
I like to use yml the way the file configuration, so the configuration of the application.properties file is migrated to application.yml , but still keep the file to overwrite the application.properties original war application.properties files, because maven-war-plugin/overlays of the reason.

Spring:  Application:    Name:Cas-serverhttp:    Encoding:      Enabled:TrueCharSet:UTF-8Force :Truethymeleaf:    Encoding:UTF-8Cache:Truemode:HtmlAOP:    Auto:TrueProxy-target-class:True# CAS Server Context ConfigurationServer:  Context-path:/casPort:8443max-http-header-size:2097152use-forward-headers:Trueconnection-timeout:20000Error:    Include-stacktrace:AlwaysCompression:    Enabled:Truemime-types:Application/javascript,application/json,application/xml,text/html,text/xml,text/plainSSL:    Key-store:Classpath:sso.keystoreKey-store-password:123456Key-password:123456Enabled:TrueTomcat:    max-http-post-size:2097152Basedir:Build/tomcatmax-threads:10Port-header:X-forwarded-portProtocol-header:X-forwarded-protoProtocol-header-https-value:HttpsRemote-ip-header:X-forwarded-foruri-encoding:UTF-8Accesslog:      Enabled:TruePattern: "%t%a '%r '%s (%d ms)"      suffix:. logsession:    Timeout:300Cookies:      http-only:TrueTracking-modes:Cookiescontext-parameters:    islog4jautoinitializationdisabled:TrueCAs:  Server:    Name:https://www.galsang.org:8443prefix:Https://www.galsang.org:8443/casadminpagessecurity:    IP:127.0.0.1authn:    Accept:      Users:Casuser::mellon,admin::adminto# static User information# Webflow:# Crypto:# enabled:false #cas. Webflow.crypto.enabled=false  TGC:    Secure:False# cas.tgc.secure=trueManagement:  Security:    Enabled:Trueroles:Actuator,adminSessions:If_requiredContext-path:/statusAdd-application-context-header:FalseSecurity:  Basic:    Enabled:FalseAuthorize-mode:RolePath:/cas/status/**Endpoints:  Enabled:FalseSensitive:TrueRestart:    Enabled:FalseShutdown:    Enabled:FalseLogging:  Config:Classpath:log4j2.xmlInfo:  Description:Cas-server
Run (running)

Enter the cas-server module execution build run command.

sso-examples-guides\cas-server>build run

Access entrance: Https://127.0.0.1:8443/cas/login

Default static account information, account number: casuser , Password:Mellon
Or
Use my custom static account information, account number: admin , Password:adminto

At this point, the system can be used https in the form of access, then let's look at Database Authentication How to configure the implementation.

Database Authentication Configuration

Step One: Disable the static account

# 禁止静态认证staticAuthentication: false# 将将静态账户信息置空cas:    authn:        accept:          

Step two: Design the database

The database scripts are as follows:

DROP DATABASE IF EXISTS' Cas_dev ';CREATE DATABASE' Cas_dev 'character SetUTF8; Use' Cas_dev ';SETforeign_key_checks=0;-- ------------------------------Table structure for ' cas_user '-- ----------------------------DROP TABLE IF EXISTS' Cas_user ';CREATE TABLE' Cas_user ' (' ID ')int( One) not NULLAuto_increment, ' username 'varchar( -) not NULL, ' Password 'varchar( -) not NULL,PRIMARY KEY(' ID ')) Engine=innodb auto_increment=2 DEFAULTCHARSET=UTF8MB4;-- ------------------------------Records of Cas_user-- ----------------------------INSERT  into' Cas_user 'VALUES(' 1 ',' admin ',' 1e1e262780021c6844af137175b56804 ');

Step three: pom.xml increase dependency in the file

        <!--introduction of database certification related start-->        <dependency>            <groupId>Org.apereo.cas</groupId>            <artifactId>Cas-server-support-jdbc</artifactId>            <version>${cas.version}</version>            <exclusions>                <exclusion>                    <groupId>org.apache.logging.log4j</groupId>                    <artifactId>Log4j-slf4j-impl</artifactId>                </exclusion>                <exclusion>                    <groupId>Com.google.guava</groupId>                    <artifactId>Guava</artifactId>                </exclusion>                <exclusion>                    <groupId>Com.zaxxer</groupId>                    <artifactId>Hikaricp</artifactId>                </exclusion>            </exclusions>        </dependency>        <dependency>            <groupId>Mysql</groupId>            <artifactId>Mysql-connector-java</artifactId>            <version>${mysql.driver.version}</version>        </dependency>        <!--introduction of database certification related end-->

Step Four: application.yml add the relevant configuration in.
application.ymlThe final content is:

Spring:  Application:    Name:Cas-serverhttp:    Encoding:      Enabled:TrueCharSet:UTF-8Force :Truethymeleaf:    Encoding:UTF-8Cache:Truemode:HtmlAOP:    Auto:TrueProxy-target-class:True# CAS Server Context ConfigurationServer:  Context-path:/casPort:8443max-http-header-size:2097152use-forward-headers:Trueconnection-timeout:20000Error:    Include-stacktrace:AlwaysCompression:    Enabled:Truemime-types:Application/javascript,application/json,application/xml,text/html,text/xml,text/plainSSL:    Key-store:Classpath:sso.keystoreKey-store-password:123456Key-password:123456Enabled:TrueTomcat:    max-http-post-size:2097152Basedir:Build/tomcatmax-threads:10Port-header:X-forwarded-portProtocol-header:X-forwarded-protoProtocol-header-https-value:HttpsRemote-ip-header:X-forwarded-foruri-encoding:UTF-8Accesslog:      Enabled:TruePattern: "%t%a '%r '%s (%d ms)"      suffix:. logsession:    Timeout:300Cookies:      http-only:TrueTracking-modes:Cookiescontext-parameters:    islog4jautoinitializationdisabled:TrueCAs:  Server:    Name:https://www.galsang.org:8443prefix:Https://www.galsang.org:8443/casadminpagessecurity:    IP:127.0.0.1TGC:    Secure:False# cas.tgc.secure=true  authn:    Accept:      Users:   # Static user information Casuser::mellon,admin::adminto    JDBC:      Query[0]:        sql:SELECT * from Cas_user where username=?Healthquery:Select 1isolateinternalqueries:False# Specify time zone Servertimezone=asia/shanghai        URL:jdbc:mysql://127.0.0.1:3306/cas_dev?servertimezone=asia/shanghai&useunicode=true&characterencoding= Utf-8&autoreconnect=true&usessl=falseFailFast:TrueIsolationlevelname:isolation_read_committeddialect:Org.hibernate.dialect.MySQLDialectLeakthreshold:10Propagationbehaviorname:Propagation_requiredbatchsize:1User:RootPassword:Admintoautocommit:Falsemaxagedays:180Driverclass:Com.mysql.cj.jdbc.DriveridleTimeout:5000Fieldpassword:PasswordPasswordencoder:          Type:DEFAULTcharacterencoding:UTF-8Encodingalgorithm:MD5staticauthentication:FalseManagement:  Security:    Enabled:Trueroles:Actuator,adminSessions:If_requiredContext-path:/statusAdd-application-context-header:FalseSecurity:  Basic:    Enabled:FalseAuthorize-mode:RolePath:/cas/status/**Endpoints:  Enabled:FalseSensitive:TrueRestart:    Enabled:FalseShutdown:    Enabled:FalseLogging:  Config:Classpath:log4j2.xmlInfo:  Description:Cas-server
Run (running)

Enter the cas-server module execution build run command.

sso-examples-guides\cas-server>build run

Access entrance: Https://127.0.0.1:8443/cas/login

Use the default account information in the database, account: admin, Password: adminto

Password modification can be src/test/java done in the directory of the PasswordByMD5Main class to reset the password, and update to the database.

At this point, the system can be used https in the form of access, and through Database Authentication the user authentication.

Conclusions (CONCLUSION)
    • Database authentication is used in a JPA way that the DB connection pool usesHikariCP
    • JPAIs the default Database authentication method, you will explain how to replace it in a later article JPA .
Recommendations (recommended)
    • Using HTTPS
    • Disabling a static account
    • Engineering complex, it is important to pay attention to the relationship between the version, open source projects, preferably against the source code compiled version for deployment.
Original statement

With the wind floating clouds
Source: Http://www.cnblogs.com/ljmatlight
This article is copyrighted by the author, welcome reprint, but without the consent of the author must retain this paragraph of the statement.
The article has inappropriate or wrong place, welcome errata, if you have better suggestions, you can give me a message to discuss and common progress.
Internet technology timeliness is strong, quote please be cautious.

CAS Https and Database authentication (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.