BasicAuth与休息控制器 - 拒绝访问

时间:2017-01-31 23:56:07

标签: java spring spring-security

我试图将Basic Auth(从Spring Security)实现到我的新手项目。为了创建用户,我在POST/register发送JSON,然后创建用户并将其放入H2内存数据库 - 这部分工作正常。然后我在我的控制器中有这个方法:

@RequestMapping(value = "/username", method = RequestMethod.GET)
public String currentUserName(Principal principal) {
    return principal.getName();
}

返回登录人的姓名。我使用Postman就是这样 - 只需从droplist中选择Basic Auth,输入这个创建用户的用户名和密码(它在数据库中,我检查过),然后我得到Access Denied响应 - 所以我猜我是'我没有正确登录或者我的Spring配置不对吗?

我使用Spring Boot并拥有3个Spring Security配置:

UserAuthService.java

@Service
@Transactional
public class UserAuthService implements UserDetailsService {

    private UserRepository userRepository;

    @Autowired
    public UserAuthService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);

        if (user == null) {
            throw new UsernameNotFoundException("Could not find the user: " + username); 
        }

        return new org.springframework.security.core.userdetails.User(
            user.getUsername(),
            user.getPassword(),
            true,
            true,
            true,
            true,
            AuthorityUtils.createAuthorityList("USER"));
    }
}

AccountConfiguration.java

// Spring Security uses accounts from our database
@Configuration
public class AccountConfiguration extends GlobalAuthenticationConfigurerAdapter {


    private UserDetailsService userAuthService;

    @Autowired
    public AccountConfiguration(UserDetailsService userAuthService) {
        this.userAuthService = userAuthService;
    }

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

最后一个只是选择授权的内容以及什么不是

WebConfiguration.java

@EnableWebSecurity
@Configuration
public class WebConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // allow everyone to register an account; /console is just for testing
        http
            .authorizeRequests()
                .antMatchers("/register", "/console/**").permitAll();

        http
            .authorizeRequests()
                .anyRequest().fullyAuthenticated();

        // making H2 console working
        http
            .headers()
                .frameOptions().disable();

        /*
        https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#when-to-use-csrf-protection
        for non-browser APIs there is no need to use csrf protection
        */
        http
            .csrf().disable();
    }
}

如果有人想检查其他配置,这里是GitHub项目的链接 - 我是新手,所以也许我没有在这篇文章中提出相关内容: https://github.com/doublemc/ToDoWebApp

2 个答案:

答案 0 :(得分:1)

您必须在Spring Security配置中配置HTTP基本身份验证,请参阅Spring Security Reference

  

5.2 HttpSecurity

     

到目前为止,我们的WebSecurityConfig仅包含有关如何验证用户身份的信息。 Spring Security如何知道我们要求所有用户都经过身份验证? Spring Security如何知道我们想要支持基于表单的身份验证?原因是WebSecurityConfigurerAdapterconfigure(HttpSecurity http)方法中提供了默认配置,如下所示:

     
protected void configure(HttpSecurity http) throws Exception {
  http
      .authorizeRequests()
          .anyRequest().authenticated()
          .and()
      .formLogin()
          .and()
      .httpBasic();
}
     

上面的默认配置:

     
      
  • 确保对我们的应用程序的任何请求都要求用户进行身份验证
  •   
  • 允许用户使用基于表单的登录进行身份验证
  •   
  • 允许用户使用HTTP基本身份验证进行身份验证
  •   

您修改后的(和简化的)代码:

@EnableWebSecurity
@Configuration
public class WebConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .authorizeRequests()
                .antMatchers("/register", "/console/**").permitAll();
                .anyRequest().authenticated()
                .and()
            .headers()
                .frameOptions().disable()
                .and()
            .csrf().disable();
    }
}

答案 1 :(得分:0)

我发现的一个问题是,由于此行,用户需要完全通过身份验证才能访问资源:
http.authorizeRequests().anyRequest().fullyAuthenticated();

将其更改为:
http.authorizeRequests().anyRequest().authenticated();

authenticated()表示用户必须匿名或记住我的用户