java SpringSecurity UserDetailsS​​ervice 获取密码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14938823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:56:47  来源:igfitidea点击:

SpringSecurity UserDetailsService get password

javaspring-security

提问by Ilkar

I'm creating authentication service in Spring.

我正在 Spring 中创建身份验证服务。

I'm using UserDetailsService to get form variables, but i found that loadUserByUsername has only one variable - userName.

我正在使用 UserDetailsS​​ervice 来获取表单变量,但我发现 loadUserByUsername 只有一个变量 - 用户名。

How to get password ?

如何获取密码?

public class userAuthentication implements UserDetailsService{

    private @Autowired
    ASPWebServicesUtils aspWebServicesUtils;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

        //how to get password ?

        User user = new User("test", "test", true, true, true, true, getAuthorities(true));

        return user;  

    }

    private List<GrantedAuthority> getAuthorities(boolean isAdmin){

        List<GrantedAuthority> authorityList = new ArrayList<GrantedAuthority>(2);
        authorityList.add(new SimpleGrantedAuthority("USER_ROLE"));
        if(isAdmin){
            authorityList.add(new SimpleGrantedAuthority("ADMIN_ROLE"));
        }
        return authorityList;

    }
//...
}

Thanks

谢谢

回答by Arun P Johny

If you look at the Userobject, the second parameter in the constructor is the password.

如果查看User对象,构造函数中的第二个参数是密码。

The UserDetailsServiceis used to load the user from a back-end structure like database. The loadUserByUsernamemethod is called when a user tries to login with a username and password, then it is the responsibility of the service to load the user definition and return it to the security framework. The required details includes data like username, password, accountNonExpired, credentialsNonExpired, accountNonLockedand authorities.

所述的UserDetailsS​​ervice用于加载从后端结构像数据库中的用户。该loadUserByUsername方法被调用当用户尝试使用用户名和密码登录,然后是服务的责任加载用户定义并返回到安全框架。所需的信息包括数据喜欢usernamepasswordaccountNonExpiredcredentialsNonExpiredaccountNonLockedauthorities

Once the spring security receives the user object, it will validate the user against the password entered by the user and other data like user account status (accountNonExpired, credentialsNonExpired etc)

一旦 spring security 收到用户对象,它就会根据用户输入的密码和用户帐户状态等其他数据(accountNonExpired、credentialsNonExpired 等)验证用户

回答by Robin Rizvi

Some of the standard (out-of-the-box) mechanisms to retrieve the user information and provide authentication information are:

一些用于检索用户信息和提供身份验证信息的标准(开箱即用)机制是:

  • inMemoryAuthentication
  • jdbcAuthentication
  • ldapAuthentication
  • userDetailsService
  • 内存认证
  • jdbc认证
  • 身份验证
  • 用户详细信息服务

If the above does not suit your purpose and you need to have a custom solution, you can create and configure a new authentication provider like so:

如果以上不适合您的目的并且您需要自定义解决方案,您可以创建和配置一个新的身份验证提供程序,如下所示:

Security Configuration:

安全配置:

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(new CustomAuthenticationProvider());
    }

    ....
}

Authentication Provider:

身份验证提供程序:

public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
        String name = authentication.getName();
        // You can get the password here
        String password = authentication.getCredentials().toString();

        // Your custom authentication logic here
        if (name.equals("admin") && password.equals("pwd")) {
            Authentication auth = new UsernamePasswordAuthenticationToken(name,
                    password);

            return auth;
        }

        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}

回答by Sotirios Delimanolis

I believe a UserDetailsServiceis supposed to be used to acquire a UserDetailsobject from some back end storage, database, flat file, etc. Once you have that UserDetails, spring security (or you) have to compare it to the username (or other principals) and password (the credentials) provided by the user in order to authenticate that user.

我相信 aUserDetailsService应该用于UserDetails从一些后端存储、数据库、平面文件等获取对象。一旦你有了它UserDetails,spring security(或你)必须将它与用户名(或其他主体)和密码进行比较(凭据)由用户提供以验证该用户。

I don't think you are using it the way it is intended.

我认为您没有按照预期的方式使用它。

回答by xxg

Add to web.xml

添加到 web.xml

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

Get password in UserDetailsService

输入密码 UserDetailsService

public class MyUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String password = request.getParameter("password"); // get from request parameter
        ......
    }
}

RequestContextHolderis base on ThreadLocal.

RequestContextHolder是基于ThreadLocal.

回答by Siva Anand

XML Implementation:

XML 实现:

<authentication-manager  alias="loginAuthenticationManager">
    <authentication-provider ref="loginAuthenticationProvider" />
</authentication-manager>

<!-- Bean implementing AuthenticationProvider of Spring Security -->
<beans:bean id="loginAuthenticationProvider" class="com.config.LoginAuthenticationProvider">
</beans:bean>

AuthenticationProvider:

身份验证提供者:

public class LoginAuthenticationProvider implements AuthenticationProvider {
    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
        String name = authentication.getName();
        // You can get the password here
        String password = authentication.getCredentials().toString();

        // Your custom authentication logic here
        if (name.equals("admin") && password.equals("pwd")) {
            List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
            return new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
        }
        return null;
    }
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

回答by NimChimpsky

the loadUserByUsername(String name)is a method defined on an interface (userServicedetails I think), which your service implements. You have to write the implementation.

loadUserByUsername(String name)是在您的服务实现的接口(我认为是 userServicedetails)上定义的方法。您必须编写实现。

Just as you have to write the implementation for getPassword() or similar ... spring does not provide that. I imagine the password is stored in your user object, but you wrote that ... did you create a getPassword()method ?

就像您必须编写 getPassword() 或类似的实现一样...... spring 没有提供。我想密码存储在您的用户对象中,但是您写道……您是否创建了getPassword()方法?