1

我必须为一个项目实现一个自定义的“身份验证提供程序”,但是当我尝试在 JSP 中访问身份验证的对象属性时遇到了麻烦。详细信息:我的自定义身份验证提供程序成功创建了一个身份验证对象

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

(这里只有相关代码)

然后,在控制器方法中,我只显示带有用户名的日志消息(这证明 Authentication 对象已创建并放置在安全上下文中):

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">...

不起作用,尽管用户在 Authentication 对象中添加了必要的角色。

有什么我做错了吗?身份验证工作正常,我只是无法访问身份验证对象的属性。

非常感谢,祝您有美好的一天。

4

3 回答 3

2

您的 AuthenticationProvider 必须返回 UserDetails 对象。

来自 spring 文档 这个标签允许访问存储在安全上下文中的当前 Authentication 对象。它直接在 JSP 中呈现对象的属性。因此,例如,如果 Authentication 的 principal 属性是 Spring Security 的 UserDetails 对象的一个​​实例,那么 using 将呈现当前用户的名称。

于 2012-09-21T20:58:24.997 回答
1

鉴于我看不出您的情况有什么问题,我认为这可能是SPR-8347错误,该错误已在 Spring 3.1.1 中修复。可以升级吗?

于 2012-09-21T13:13:01.010 回答
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
    }

现在,在你的 tamplete 中,嗯可以使用这样的东西:

<span class="hidden-sm-down" sec:authentication="principal.email">Email</span>
于 2017-02-20T14:47:30.317 回答