SSO Single Point series (7): CAS4.0 server authenticates users by database

Source: Internet
Author: User
Tags aop cas

In the previous few, there is a brief introduction to the service-side authentication method, the default is directly in the Deployerconfigcontext.xml file in a bean called Primaryauthenticationhandler in the configuration. However, this only supports an account, and is fixed, which has very large limitations, in the real system is certainly not in such a way.

Now the application system is generally by reading the database to verify the user name, password is correct, and then to authenticate. Therefore, in this article will be introduced, how to change the default authentication method of the server to the database authentication method, in order to meet the basic needs of the system.

1. Add Data Source Configuration

The configuration of the data source is similar to what we configured in the usual way, CAs can be configured using spring, and in order to separate from the original configuration file, I have created a configuration called Applicationcontext-datasource.xml to store the data source configuration, (placed under Cas-server-webapp\src\main\webapp\web-inf\spring-configuration) is as follows:

<?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:p= "http://www.springframework.org/schema/p" xmlns:aop= " Http://www.springframework.org/schema/aop "xmlns:tx=" Http://www.springframework.org/schema/tx "xsi: schemalocation= "Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/ Spring-aop-3.1.xsd Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.1.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-3.1.xsd "> <description>datasource</description> <bean id=" Casdatasource "class=" Com.alibaba.druid.pool.DruidDataSource "init-method=" Init "destroy-method=" close "> <property name=" url "value = "${url}"/> <property name= "username" value= "${username}"/> <property name= "passWOrd "value=" ${password} "/> <property name=" driverclassname "value=" ${driverclassname} "/> &L T;property name= "maxactive" value= "${maxactive}"/> <property name= "initialsize" value= "${initialSize}"/&G          T            <property name= "maxwait" value= "${maxwait}"/> <property name= "Minidle" value= "${minidle}"/>  <property name= "Timebetweenevictionrunsmillis" value= "${timebetweenevictionrunsmillis}"/> <property Name= "Minevictableidletimemillis" value= "${minevictableidletimemillis}"/> <property name= "ValidationQue Ry "value=" ${validationquery} "/> <property name=" Testwhileidle "value=" ${testwhileidle} "/> &L T;property name= "Testonborrow" value= "${testonborrow}"/> <property name= "Testonreturn" value= "${testOnRetu RN} "/> <property name=" maxopenpreparedstatements "value=" ${maxopenpreparedstatements} "/> < Property NamE= "removeabandoned" value= "${removeabandoned}"/> <!--open removeabandoned function--<property name= "remove Abandonedtimeout "value=" ${removeabandonedtimeout} "/> <!--1800 seconds, i.e. 30 minutes---<property name=" Logaban doned "value=" ${logabandoned} "/> <!--turn off abanded connection when output error log--</bean> <bean id=" Jdbctemplat E "class=" Org.springframework.jdbc.core.JdbcTemplate "p:datasource-ref=" Casdatasource "/> <bean id=" transact Ionmanager "class=" Org.springframework.jdbc.datasource.DataSourceTransactionManager "p:datasource-ref=" Casdataso Urce "/> <!--provides transaction enhancement through AOP configuration, allowing all the methods of all beans under Accountservice to have transactions--<aop:config> <aop:point Cut id= "Servicemethod" expression= "Execution (* Com.blog.cas.account.service.impl). *(..))" /> <aop:advisor pointcut-ref= "Servicemethod" advice-ref= "Txadvice"/> </aop:config> <tx:adv Ice id= "Txadvice" transaction-manager= "transactionmanageR "> <tx:attributes> <tx:method name=" get* "propagation=" REQUIRED "read-only=" true "/>            <tx:method name= "update*" propagation= "REQUIRED"/> </tx:attributes> </tx:advice> <bean id= "Accountservice" class= "Com.blog.cas.account.service.impl.AccountServiceImpl" p:accountdao-ref= "Accou Ntdao "/> <bean id=" Accountdao "class=" Com.blog.cas.account.dao.impl.AccountDaoImpl "p:jdbctemplate-ref=" JdbcTemplate "/> </beans>

Note: In this case there is a service, a DAO, is used to interact with the database, in which everyone write their own needs of the method on the line. This side uses the spring provided by the JdbcTemplate to query. These two classes will not be posted out, everyone free to achieve

Then the data sources related to the information I put directly in the file Cas.properties (cas-server-webapp\src\main\webapp\web-inf\cas.properties), add the following at the end:

# # Jdbcurl=jdbc:oracle:thin:@192.168.1.101:1521:odsorclusername=blogpassword=blogdriverclassname= Oracle.jdbc.driver.oracledrivervalidationquery=select 1 from dual Filters=stat  maxactive=20  initialSize=1  maxwait=60000  minidle=10  timebetweenevictionrunsmillis=60000  minevictableidletimemillis= 300000  testwhileidle=true  testonborrow=false  testonreturn=false  maxopenpreparedstatements=  removeabandoned=true  removeabandonedtimeout=1800  logabandoned=true

The Oracle database is used.

2. Custom Authentication Handler Class

CAS uses the default authentication class as Org.jasig.cas.authentication.AcceptUsersAuthenticationHandler. We look at its source code, found that the certification is in a method called authenticateusernamepasswordinternal, in fact, look at the method name we can guess what this method is to do. And then the parent class of this class is Abstractusernamepasswordauthenticationhandler, so we inherit this class, The implementation of the Authenticateusernamepasswordinternal method is actually possible.

Here also note that the parameter in the Authenticateusernamepasswordinternal method is a usernamepasswordcredential type parameter, which actually contains the user-related information we entered on the page, That is, the user name and password. Well, know the way, so let's do it.

public class Blogusersauthenticationhandler extends Abstractusernamepasswordauthenticationhandler {    private Accountserviceimpl Accountservice;        @Override    protected Handlerresult authenticateusernamepasswordinternal (            usernamepasswordcredential Credential)            throws Generalsecurityexception, preventedexception {                String username = credential.getusername () ;        String password = Credential.getpassword ();                Boolean flag = Accountservice.checkaccount (username, password);        if (!flag) {           throw new failedloginexception ();        }        Return Createhandlerresult (Credential, New Simpleprincipal (username), null);    }    Omit Get/set Method    }

This is just a simple validation logic that can actually be complex, such as judging the user's state, disabling, and so on.

Then modify the relevant configuration to open the file Cas-server-webapp\src\main\webapp\web-inf\deployerconfigcontext.xml find ID primaryprincipalresolver Bean, change this to our new class

<!--<bean id= "Primaryauthenticationhandler"          class= " Org.jasig.cas.authentication.AcceptUsersAuthenticationHandler ">        <property name=" Users ">            < map>                <entry key= "admin" value= "admin"/>            </map>        </property>    </bean>-- >     <bean id= "Primaryauthenticationhandler"          class= " Org.jasig.cas.authentication.BlogUsersAuthenticationHandler ">          <property name=" Accountservice "ref=" Accountservice "/>    </bean>

Well, now has been modified to pass the database authentication way, we can try.

3. Certification process

After reading the above, you may feel a little bit out of comprehension. Why only add a class, covering the method to complete the certification, in this section describes a general certification process, as well as to the final information returned to the client such a process.

Some of the content in the fourth article is introduced, it is best to understand the fourth post-login user information return related content, portal

    1. User Login Page Enter relevant information, click Submit Login
    2. Execute the Submit method in the Authenticationviaformaction class
    3. The Grantserviceticket method of the Centralauthenticationservice class is called in the Submit method, which has parameters passed into the credential type
    4. The Authenticate method of the AuthenticationManager class (The actual class is Policybasedauthenticationmanager) is then called in the Grantserviceticket method
    5. The Authenticateinternal method is also called in the Authenticate method
    6. Finally, Authenticationhandler's authenticate method is called in the Authenticateinternal method, authenticate Method invokes the Blogusersauthenticationhandler method that we have customized above
    7. Then we call the Resolveprincipal method based on the information returned by the method we wrote, turning the information of the credential type into the principal type of information, that is, assembling some information that we need to return to the client. This is mainly through the Principalresolver class to turn to become, the fourth chapter has focused on, this side is not detailed.
    8. Finally successfully landed on the client

The above process is only the main process of certification, does not include the generation of St, validation and other processes.

4. Summary

Through the database certification basically finished, but the above is just a simple demonstration, we need to change according to their own situation.

This article is all transferred from http://www.cnblogs.com/vhua/tag/cas/

SSO Single Point series (7): CAS4.0 server authenticates users by database

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.