2012-09-21 34 views
1

我必須爲一個項目實現一個自定義的「身份驗證提供程序」,但是當嘗試訪問身份驗證的時候遇到了麻煩JSP中的對象屬性。詳細信息: 我的自定義驗證提供商成功地創建了一個驗證對象Spring Security - bean類的無效屬性'principal'[org.springframework.security.authentication.UsernamePasswordAuthenticationToken]

Authentication auth = new UsernamePasswordAuthenticationToken(username, password, getAuthorities(userRoles)); 
log.info("User is authenticated"); 
return auth; 

(這裏只是相關的代碼)

然後,在控制器的方法,我只是顯示與用戶名日誌消息(這證明了被創建並放置在安全上下文中)認證對象:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();   
log.info("Welcoming user " + auth.getPrincipal()); 

然後在JSP頁面中我想顯示的用戶名使用

<sec:authentication property="principal"/> 

然而,這會引發錯誤500:

org.springframework.beans.NotReadablePropertyException: Invalid property 'principal' of bean class [org.springframework.security.authentication.UsernamePasswordAuthenticationToken]: Bean property 'principal' is not readable... 

我也注意到,

<sec:authorize ifAnyGranted="role">... 

不工作,雖然用戶在認證對象添加了必要的作用。

有什麼我做錯了嗎?身份驗證正常工作,我只是無法訪問身份驗證對象的屬性。

非常感謝你,祝你有美好的一天。

+0

你使用的是什麼版本的Spring Framework和Spring Security? – Xaerxess

+0

對不起,忘了提及 - Spring Framework 3.1.0和Spring Security 3.1.0 –

回答

1

鑑於我看不出你的情況有什麼問題,我認爲它可能是SPR-8347錯誤,這在Spring 3.1.1中已修復。你可以做升級嗎?

+0

Yey!將Spring Security和Spring Framework升級到3.1.2就像一個魅力一樣。非常感謝! 但是,問題仍然存在。用戶具有必要的角色,但標記中的片段不顯示... –

+0

解決了這個問題,原來是鍵盤和椅子之間的錯誤 - 我在角色名稱。 –

2

您的AuthenticationProvider必須返回UserDetails對象。

來自spring documentation 該標籤允許訪問存儲在安全上下文中的當前認證對象。它直接在JSP中呈現對象的屬性。因此,例如,如果Authentication的主體屬性是Spring Security的UserDetails對象的實例,則使用將呈現當前用戶的名稱。

+1

Deepak,** UsernamePasswordAuthenticationToken **實現**身份驗證**,所以一切都是正確的。唯一的區別是您必須使用 而不是

0

老問題,但我認爲我可以幫助其他人。

作爲UsernamePasswordAuthenticationToken的第一個參數,您可以發送一個用戶。

而不是傳遞用戶名,傳遞用戶本身。但用戶必須是擴展org.springframework.security.core.userdetails.UserDetails類:

Authentication auth = new UsernamePasswordAuthenticationToken(user, password, getAuthorities(userRoles)); 
log.info("User is authenticated"); 
return auth; 

見你是使用方法:

public UsernamePasswordAuthenticationToken(Object principal, Object credentials, 
      Collection<? extends GrantedAuthority> authorities) { 
     super(authorities); 
     this.principal = principal; 
     this.credentials = credentials; 
     super.setAuthenticated(true); // must use super, as we override 
    } 

現在,在YOUT tamplete,嗯可以使用像這樣的東西:

<span class="hidden-sm-down" sec:authentication="principal.email">Email</span> 
相關問題