【问题标题】:How to create a Principal object in a customAuthenticationProvider?如何在 customAuthenticationProvider 中创建 Principal 对象?
【发布时间】:2013-08-15 22:02:33
【问题描述】:

我有一个网络应用程序,我正在使用 Spring Security。我在 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 对象? (我认为这是问题所在)以及如何创建它(主体对象)?

【问题讨论】:

    标签: java authentication spring-security


    【解决方案1】:

    试试这个,

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

    【讨论】:

    • 我已经尝试过了,结果相同。我找到了一个不同的解决方案,我发现主体是创建的,但不是作为用户对象(就像我之前使用的那样),而只是作为字符串。我使用了这个字符串并为我工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-08
    • 1970-01-01
    相关资源
    最近更新 更多