【问题标题】:Spring boot basic auth username is not validatedSpring Boot基本身份验证用户名未验证
【发布时间】:2017-07-31 02:06:23
【问题描述】:

我是 Spring Security 的新手,我已经为我的 Spring Boot 应用程序创建了一个基本身份验证来试用它

我已经创建了 MYGlobalAuthenticationConfigurerAdapter 像这样:

@Value("${username}")
    String username;

    @Value("${password}")
    String password;

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsService() {

            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                return new User(username, password, true, true, true, true,
                        AuthorityUtils.createAuthorityList("USER"));
            }
        };
    }

请注意,我从属性文件加载用户名和密码,并根据值进行验证

和这样的 MyWebSecurityConfigurerAdapter:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().fullyAuthenticated().and().
    httpBasic().and().
    csrf().disable();
} 

带有@EnableWebSecurity 注释。

每次我更改用户名时,我都会尝试使用 postman 使用用户名和密码连接到我的一个 Web 服务,即使用户名与我放入属性文件中的用户名不同,请求也会得到验证

【问题讨论】:

    标签: spring spring-boot spring-security basic-authentication


    【解决方案1】:

    这是因为您在所有情况下都返回 User 对象,而没有与参数中收到的对象进行任何检查。试试下面的代码:

    @Value("${username}")
        String username;
    
        @Value("${password}")
        String password;
    
        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService());
        }
    
        @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsService() {
    
            @Override
            public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
                if(name.equals(username)){
                    return new User(username, password, true, true, true, true,
                        AuthorityUtils.createAuthorityList("USER"));
                }else{
                    throw new UsernameNotFoundException("Could not find the user '" + name + "'");
                }
    
            }
        };
    }
    

    更新

    用户不会被任何密码验证,而只会使用您在 loadUserByUsername() 方法中创建用户时使用的密码。在这种方法中,您只能通过用户名找到用户并返回,这里不进行身份验证,但身份验证是由 spring 在内部完成的,它将您在创建用户(并返回)时传递的密码与您在要求。它还验证您正在访问的 url 的用户角色,如果 url 映射到任何特定角色,则具有该角色的用户被授予访问权限,对于任何其他角色,它将发送拒绝访问响应。 因此,它不会使用任何密码对用户进行身份验证。

    【讨论】:

    猜你喜欢
    • 2019-04-25
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 2018-04-13
    • 2017-11-02
    • 2014-07-29
    • 1970-01-01
    • 2018-01-22
    相关资源
    最近更新 更多