CAS學習筆記(三)—— SERVER登入後使用者資訊的返回

來源:互聯網
上載者:User

標籤:singleton   tor   軟體   其他   ipa   ted   ase   tab   儲存   

一旦CAS SERVER驗證成功後,我們就會跳轉到用戶端中去。跳轉到用戶端去後,大家想一想,用戶端總要擷取使用者資訊吧,不然用戶端是怎麼知道登入的是哪個使用者。那麼用戶端要怎麼擷取使用者資訊呢?

其實驗證成功,跳轉用戶端這個過程中,CAS SERVER 會返回登入的相關資訊給用戶端,用戶端只要進行擷取,就能知道登入的具體是哪個使用者了。不過CAS 預設只返回使用者帳號給用戶端,那麼怎麼定義CAS SERVER返回的資訊呢? 這就是本篇具體講解的內容了,大家聽我慢慢道來。

 

相關介面                                                               

在開始時,我們先瞭解下有關相關的幾個介面

  • Credentials
  • Principal
  • IPersonAttributeDao
  • PrincipalResolver

 

Credentials                                                    

   Credentials (org.jasig.cas.authentication.Credentials)介面,我們在上一篇其實有使用過,我們當時有用過一個叫 UsernamePasswordCredential 的類,就是實現了Credentials介面。這個介面是用來定義我們登入頁上輸入的認證資訊的,比如使用者名稱、密碼、驗證碼等,可以理解為使用者認證的相關憑據。

 

Principal                                                     

  Principal (org.jasig.cas.authentication.principal.Principal) 介面,這個主要是用來儲存使用者認證後的使用者資訊,資訊儲存在一個Map中。

 

IPersonAttributeDao                                              

  IPersonAttributeDao (org.jasig.services.persondir.IPersonAttributeDao) 介面,這個是用來定義我們需要返回給用戶端相關資訊的介面,CAS SERVER 預設有提供許多實現,比如

  • LdapPersonAttributeDao :通過查詢 LDAP 目錄 ,來返回資訊
  • SingleRowJdbcPersonAttributeDao : 通過JDBC SQL查詢,來返回資訊

等等,還有許多,大家可以參考源碼中的實現,CAS SERVER 提供了各種功能的實現,有時候我們可以直接使用這個現成的就行了。

 

PrincipalResolver                                                 

  PrincipalResolver(org.jasig.cas.authentication.principal.PrincipalResolver) 介面,上面有說到 Credentials 是從登入頁面上進行擷取相關使用者資訊的。那麼認證成功後,怎麼把Credentials裡面的資訊轉換到 Principal  中呢,這就是這個介面的作用了。由於認證本身是沒有返回使用者資訊的,只是確定認證是通過還是沒有通過。這時還要用到我們上面的IPersonAttributeDao 介面,在這介面中我們就可以定義我們需要返回的資訊了。

這介面中有兩個方法

  • resolve : 解析Credentials中的資訊,返回 Principal 介面
  • supports : 判斷Credentials 是否支援 Principal 協議。

ps: 在3.x版本中沒有 PrincipalResolver介面,對應的是CredentialsToPrincipalResolver, PrincipalResolver這個是在4.0版本中加入的,大家要注意。

 

流程                                           

 相關介面講解後,大家應該對怎麼返回資訊有個大概的思路了。沒錯就是實現上面所說的 IPersonAttributeDao 、PrincipalResolver 介面 。下面根據代碼講解下具體的一個流程:

首先開啟 deployerConfigContext.xml 檔案,看下面的定義:

 <!--       | 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>

 

//PersonDirectoryPrincipalResolver 部分源碼

public final Principal resolve(final Credential credential) {        logger.debug("Attempting to resolve a principal...");              String principalId = extractPrincipalId(credential);  //extractPrincipalId 方法從credential中抽取id       //省略...        final IPersonAttributes personAttributes = this.attributeRepository.getPerson(principalId);  //根據IPersonAttributeDao 中的getPerson 擷取返回的屬性        final Map<String, List<Object>> attributes;       //最終返回 Principal         return new SimplePrincipal(principalId, convertedAttributes);    }    

 

 

 具體流程:

1.從上面的deployerConfigContext.xml 配置我們可以看到,CAS 預設配置了一個叫做 PersonDirectoryPrincipalResolver 的類,在 這個類的 resolve  方法中有調用 extractPrincipalId 這個方法,這個方法傳入一個 Credentials 類型的參數,預設調用的是Credentials  的getId() 方法,CAS預設是返回使用者的userName,即登入帳號。不過getId()  這個方法的實現我們可以在上一章中指定的UsernamePasswordCredential 類中自訂,一般是定義成返回使用者的userId或者其他唯一鍵,因為我們如果知道了使用者的userId,那麼就可以根據這個從資料庫中查詢中使用者的一些具體資訊了,進而就可以組成我們需要返回的資訊。

 

2. 繼續往下看源碼,接著在 PersonDirectoryPrincipalResolver  中有注入一個 attributeRepository 屬性,這個就是上面的IPersonAttributeDao 介面,然後在resolve方法中調用了 IPersonAttributeDao 介面 的getPerson方法,還傳入了一個參數principalId,其實這個傳入的參數就是我們上面 getId() 返回的值。

 

所以其實我們只要實現我們需要的 IPersonAttributeDao  就可以了。 下面給一個簡單的IPersonAttributeDao  例子: 

 

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);    }    }

 

這邊傳入的uid 預設是使用者的登入名稱,我們這邊沒有做修改,直接用預設的。

這邊是只是測試用,所以就直接寫死了,實際開發肯定是需要在資料庫或者LDAP中進行查詢後,然後組裝成需要的資訊 。

 

然後在 deployerConfigContext.xml 中修改

<bean id="primaryPrincipalResolver"          class="org.jasig.cas.authentication.principal.PersonDirectoryPrincipalResolver" >        <property name="attributeRepository" ref="attributeRepository" />    </bean>
<!-- 修改前 --> <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-->
<!--修改後--> <bean id="attributeRepository" class="org.jasig.services.persondir.support.BlogStubPersonAttributeDao" /> <!--修改後 end-->

 

 

3. 修改完成後,我們還需要在 casServiceValidationSuccess.jspcas-server-webapp\src\main\webapp\WEB-INF\view\jsp\protocol\2.0\casServiceValidationSuccess.jsp)

添加一段代碼(下面紅色部分):

<cas:serviceResponse xmlns:cas=‘http://www.yale.edu/tp/cas‘>    <cas:authenticationSuccess>        <cas:user>${fn:escapeXml(assertion.primaryAuthentication.principal.id)}</cas:user>        
    <!-- 這段 -- > <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. 接下來 在用戶端設定資訊的接收,我們直接在index.jsp中測試一下:

在Java中可以通過下面的方式擷取

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

Map attributes = principal.getAttributes();

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

...

 

<!DOCTYPE html"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>傳回值測試</title></head><body>    <%     request.setCharacterEncoding("UTF-8");    AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();    Map attributes = principal.getAttributes();    String userid=(String)attributes.get("userid");     String cnblogUsername = (String)attributes.get("cnblogUsername");     String cnblogPassword = (String)attributes.get("cnblogPassword");     String test=(String)attributes.get("test");         %>    <div>飛奔的蝸牛部落格:傳回值示範</div>    <ul>        <li>userid:<%= userid%></li>        <li>username:<%= cnblogUsername%></li>        <li>password:<%= cnblogPassword%></li>        <li>test:<%= test%></li>    </ul></body></html>

 

 

效果                                           

好了,我們登入運行看看結果。

 

 

大家看到沒,已經擷取成功了,在CAS SERVER那邊設定的資訊,我們正常擷取到了 。大家可以根據業務的需要,返回相關的資訊。然後在用戶端進行操作。

轉自:http://www.cnblogs.com/vhua/p/cas_4.html

CAS學習筆記(三)—— SERVER登入後使用者資訊的返回

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.