提供无效凭据时,Spring boot + JWT错误

时间:2018-03-20 10:19:00

标签: java spring-boot resttemplate

我使用spring boot和JWT实现了身份验证+授权。这就是我的配置的样子。

@EnableWebSecurity
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserRepository userRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers(HttpMethod.POST, "/rest/login").permitAll()
                .anyRequest().authenticated()
                .and()
                // We filter the rest/login requests
                .addFilterBefore(new JWTLoginFilter("/rest/login", authenticationManager()),
                        UsernamePasswordAuthenticationFilter.class)
                // And filter other requests to check the presence of JWT in header
                .addFilterBefore(new JWTAuthFilter(),
                        UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(username -> userRepository.findByUsername(username).map(a -> new User(a.getUsername(), a.getPassword(), true, true, true, true, AuthorityUtils.createAuthorityList("USER", "write"))).orElseThrow(() -> new UsernameNotFoundException("could not find the user '" + username + "'")));
    }
}

我正在使用RestTemplate进行休息调用,如果我向/ rest / login api提供正确的凭据,它会完美运行但是当我提供无效凭据时会抛出错误,因此我无法通过{{获取http状态1}}。

ResponseEntity.getStatusCode()

错误:

public static boolean login(String username, String password) {
    boolean retVal = false;
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<UserDTO> responseEntity = null;

    UserDTO userDTO = new UserDTO();
    userDTO.setUsername(username);
    userDTO.setPassword(password);

    try {
        responseEntity = restTemplate.postForEntity(Constant.REST_API + Constant.REST_COMMAND_LOGIN, userDTO, UserDTO.class);

        if (responseEntity.getStatusCode() == HttpStatus.OK) {

            //implement here
        }

    } catch (HttpClientErrorException httpClientEx) {
        switch (httpClientEx.getStatusCode()) {
            case BAD_REQUEST: //400
                break;

            case UNAUTHORIZED: //401
                break;
        }
        Log.debug(httpClientEx.getStackTrace().toString());

    } catch (Exception ex) {
        Log.debug(ex.getStackTrace().toString());
    }
    return retVal;
}

0 个答案:

没有答案