0

我有一个网络应用程序,我正在使用弹簧安全性。我在 securityContext.xml 中为身份验证提供程序进行了以下配置:

<authentication-provider>
        <password-encoder hash="sha-256" />
        <jdbc-user-service data-source-ref="dataSource"
            users-by-username-query="<the query>"

            authorities-by-username-query="<the other query>" />
</authentication-provider>

这工作正常。现在我想在 java 类的 customAuthentication 提供程序中进行身份验证。就像是:

public class CustomAuthenticationProvider implements AuthenticationProvider {

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();

        //I check the username-password, and grantedAuths       

        Authentication auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuths);

        return auth;

        else //it enters here with an incorrect username-password (the if is in the original code) 
        {
            return null;
        }

}

现在,身份验证工作正常。不正确的用户名密码不允许您登录,而正确的用户名密码会。问题是,我在应用程序中使用了 Principal 对象,我收到了类似的错误

Invalid property 'principal.username' of bean class [org.springframework.security.authentication.UsernamePasswordAuthenticationToken]:

为什么 customAuthenticationProvider 没有创建 Principal 对象?(我认为这是问题所在)以及如何创建它(主体对象)?

4

1 回答 1

0

尝试这个,

public class CustomAuthenticationProvider implements AuthenticationProvider {

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String name = authentication.getPrincipal();
        String password = authentication.getCredentials().toString();
        List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();

        //I check the username-password, and grantedAuths       

        Authentication auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuths);

        return auth;

        else //it enters here with an incorrect username-password (the if is in the original code) 
        {
            return null;
        }

}
于 2013-08-15T14:02:33.807 回答