[SSO single-point series] (4): Return of user information after cas server logon, ssocas

Source: Internet
Author: User

[SSO single-point series] (4): Return of user information after cas server logon, ssocas

 

Next, in the previous article, we described how to add a verification code on the cas server logon page and log on. Once the cas server is successfully verified, we will jump to the client. After you jump to the client, let's think about it. The client always needs to obtain user information. Otherwise, how does the client know which user to log on. How does the client obtain user information?

In fact, the verification is successful. In the process of redirecting to the client, the cas server returns the logon information to the client. As long as the client obtains the information, it can know which user is logged on. However, CAS only returns the user account to the client by default. How does one define the information returned by cas server? This is the specific content of this article.

 

Related Interfaces

At the beginning, Let's first look at several related interfaces.

  • Credentials
  • Principal
  • IPersonAttributeDao
  • PrincipalResolver

 

Credentials

Credentials (org. jasig. cas. authentication.Credentials)Interface, which we used in the previous article. We usedUsernamePasswordCredentialClass is implementedCredentialsInterface. This interface is used to define the authentication information entered on the logon page, such as the user name, password, and verification code. It can be understood as the creden for user authentication.

 

Principal

Principal (org. jasig. cas. authentication. principal. Principal)Interface, which is used to save the user information after user authentication and save the information in a Map.

 

IPersonAttributeDao

IPersonAttributeDao (org. jasig. services. persondir. IPersonAttributeDao)Interface, which is used to define the interface we need to return relevant information to the client. cas server provides many implementations by default, such

  • LdapPersonAttributeDao: queries the LDAP directory to return information.
  • SingleRowJdbcPersonAttributeDao: return information through jdbc SQL query

And so on. You can refer to the implementation in the source code. cas server provides various functions. Sometimes we can directly use this ready-made function.

 

PrincipalResolver

PrincipalResolver (org. jasig. cas. authentication. principal. PrincipalResolver)Interface.CredentialsThe user information is obtained from the logon page. After the authentication is successfulCredentialsConvert the information inPrincipalThis is the role of this interface. Because the authentication itself does not return user information, it only determines whether the authentication passes or fails. We need to use the aboveIPersonAttributeDaoInterface, in which we can define the information we need to return.

There are two methods in this interface

  • Resolve: ResolutionCredentialsInformation in, returnPrincipalInterface
  • Supports: JudgmentCredentialsSupported?PrincipalProtocol.

Ps: Not in version 3.xPrincipalResolverInterface, correspondingCredentialsToPrincipalResolver,PrincipalResolverThis is added in version 4.0..

 

Process

After explaining the related interfaces, you should have a rough idea about how to return the information. That's right.IPersonAttributeDao,PrincipalResolverInterface. The following code explains a specific process:

OpenDeployerConfigContext. xmlFile, see the following definition:

 <!--       | Resolves a principal from a credential using an attribute repository that is configured to resolve       | against a deployer-specific store (e.g. LDAP).       -->    <bean id="primaryPrincipalResolver"          class="org.jasig.cas.authentication.principal.PersonDirectoryPrincipalResolver" >        <property name="attributeRepository" ref="attributeRepository" />    </bean>    <!--    Bean that defines the attributes that a service may return.  This example uses the Stub/Mock version.  A real implementation    may go against a database or LDAP server.  The id should remain "attributeRepository" though.    +-->    <bean id="attributeRepository" class="org.jasig.services.persondir.support.StubPersonAttributeDao"            p:backingMap-ref="attrRepoBackingMap" />        <util:map id="attrRepoBackingMap">        <entry key="uid" value="uid" />        <entry key="eduPersonAffiliation" value="eduPersonAffiliation" />         <entry key="groupMembership" value="groupMembership" />    </util:map>

 

//PersonDirectoryPrincipalResolverSome source code

Public final Principal resolve (final Credential credential) {logger. debug ("Attempting to resolve a principal... "); String principalId = extractPrincipalId (credential); // The extractPrincipalId method extracts id from credential // omitting... final IPersonAttributes personAttributes = this. attributeRepository. getPerson (principalId); // obtain the returned attribute final Map <String, List <Object> attributes according to getPerson in IPersonAttributeDao; // finally returnPrincipalReturn new SimplePrincipal (principalId, convertedAttributes );}

 

 

Specific process:

1. From the aboveDeployerConfigContext. xmlWe can see that CAS configuresPersonDirectoryPrincipalResolverIs called in the resolve method of this class.ExtractPrincipalIdThis method is used to pass inCredentialsType parameter, which is called by defaultCredentialsOfGetId ()Method. By default, CAS returns the userName of the user, that is, the Logon account. HoweverGetId ()The implementation of this method can be specified in the previous chapterUsernamePasswordCredentialClass, which is generally defined as the returned user's userId or other unique keys, because if we know the user's userId, then, you can query the user's specific information from the database to form the information we need to return.

 

2. Continue to read the source code, and then goPersonDirectoryPrincipalResolverOneAttributeRepositoryAttribute. This is the above IPersonAttributeDao interface. Then, the getPerson method of the IPersonAttributeDao interface is called in the resolve method, and a parameter principalId is passed in. In fact, the input parameter is above getId () returned value.

 

So we only need to implement what we needIPersonAttributeDaoYou can. Below is a simpleIPersonAttributeDaoExample:

 

public class BlogStubPersonAttributeDao extends StubPersonAttributeDao {    @Override    public IPersonAttributes getPerson(String uid) {                Map<String, List<Object>> attributes = new HashMap<String, List<Object>>();        attributes.put("userid", Collections.singletonList((Object)uid));        attributes.put("cnblogUsername", Collections.singletonList((Object)"http://www.cnblogs.com/vhua"));        attributes.put("cnblogPassword", Collections.singletonList((Object)"123456"));        attributes.put("test", Collections.singletonList((Object)"test"));        return new AttributeNamedPersonImpl(attributes);    }    }

 

The uid passed in here is the user's login name by default. We have not made any changes here, and use the default one directly.

This is only for testing purposes, so the writing is dead. The actual development must be performed in the database or LDAP, and then assembled into the required information.

 

ThenDeployerConfigContext. xmlModifying

<Bean id = "primaryPrincipalResolver" class = "org. jasig. cas. authentication. principal. personDirectoryPrincipalResolver "> <property name =" attributeRepository "ref =" attributeRepository "/> </bean>
<! -- Before modification --> <bean id = "attributeRepository" class = "org. jasig. services. persondir. support. stubPersonAttributeDao "p: backingMap-ref =" attrRepoBackingMap "/> <util: map id = "attrRepoBackingMap"> <entry key = "uid" value = "uid"/> <entry key = "eduPersonAffiliation" value = "eduPersonAffiliation"/> <entry key =" groupMembership "value =" groupMembership "/> </util: map> <! -- End before modification -->
<! -- After modification --> <bean id = "attributeRepository" class = "org. jasig. services. persondir. support. BlogStubPersonAttributeDao"/> <! -- End after modification -->

 

 

3. After the modification is completed, we needCasServiceValidationSuccess. jspcas-server-webapp \ src \ main \ webapp \ WEB-INF \ view \ jsp \ protocol \ 2.0 \ casServiceValidationSuccess. jsp)

Add a piece of code (the red part below ):

<Cas: serviceResponse xmlns: cas = 'HTTP: // www.yale.edu/tp/cas'> <cas: authenticationSuccess> <cas: user >$ {fn: escapeXml (assertion. primaryAuthentication. principal. id)} </cas: user>
<! -- This section --> <c: if test = "$ {fn: length (assertion. chainedAuthentications [fn: length (assertion. chainedAuthentications)-1]. principal. attributes)> 0} "> <cas: attributes> <c: forEach var =" attr "items =" $ {assertion. chainedAuthentications [fn: length (assertion. chainedAuthentications)-1]. principal. attributes} "> <cas :$ {fn: escapeXml (attr. key) }>$ {fn: escapeXml (attr. value)} </cas :$ {fn: escapeXml (attr. key) }></c: forEach> < /Cas: attributes> </c: if> <! -- End -->

<C: if test = "$ {not empty pgtIou}"> <cas: proxyGrantingTicket >$ {pgtIou} </cas: proxyGrantingTicket> </c: if> <c: if test = "$ {fn: length (assertion. chainedAuthentications)> 1} "> <cas: proxies> <c: forEach var =" proxy "items =" $ {assertion. chainedAuthentications} "varStatus =" loopStatus "begin =" 0 "end =" $ {fn: length (assertion. chainedAuthentications)-2} "step =" 1 "> <cas: proxy >$ {fn: escapeXml (proxy. principal. id)} </cas: proxy> </c: forEach> </cas: proxies> </c: if> </cas: authenticationSuccess> </cas: serviceResponse>

 

 

4. Next, set the receiving of information on the client. We will test it in index. jsp:

In java, you can obtain

AttributePrincipal principal = (AttributePrincipal) request. getUserPrincipal ();

Map attributes = principal. getAttributes ();

String xxx = attributes. get ("xxx ");

...

 

<! DOCTYPE html "> 

 

 

Effect

Okay. Let's log on and run the command to see the result.

 

No, we have obtained the information successfully. We have obtained the information set on the cas server. You can return relevant information based on your business needs. Then, perform operations on the client.

 

Summary

This article was written last night and is ready for release. As a result, it was too difficult to save the draft and was found in the morning.

Thank you.

 

After finishing the work...

 

Related Article

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.