java.net.HttpRequest - 为发布请求设置授权标头

时间:2021-06-04 15:22:13

标签: java spring http authentication

我有一个连接到数据库的 Rest API(Spring Boot 应用程序)和一个用 Java Swing 编写的桌面应用程序,它使用 java.net.HttpClient 连接到用于数据的 rest api。现在我正在尝试使用 spring-boot-security.

实现基本身份验证

我在后端提供了一个用户,当我通过浏览器连接到它时能够登录,我还可以通过设置 HttpRequest 的标头来发送 GET 请求。

但是,当我以相同的方式设置标头(状态 401)时,我无法发送 POST 请求。我也尝试使用 Apaches HttpClient 得到相同的结果。

这是我的安全配置:

@Configuration
@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {


    @Autowired
    private MyBasicAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("soft").password(passwordEncoder().encode("soft"))
                .authorities("ROLE_USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/securityNone").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic()
                .authenticationEntryPoint(authenticationEntryPoint);

        http.addFilterAfter(new CustomFilter(),
                BasicAuthenticationFilter.class);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

 class CustomFilter extends GenericFilterBean {

    @Override
    public void doFilter(
            ServletRequest request,
            ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, response);
    }
}

这是前端HttpClient的配置:

final String customerKey = "username";
        
        final String customerSecret = "userpass";

        concatenated string
        String plainCredentials = customerKey + ":" + customerSecret;
        String base64Credentials = new String(Base64.getEncoder().encode(plainCredentials.getBytes()));
        // authorization header
        String authorizationHeader = "Basic " + base64Credentials;
        HttpClient client = HttpClient.newHttpClient();

        url = "http://localhost:8080";

这是一个运行良好的 GET 请求:

request = HttpRequest.newBuilder()
                .uri(URI.create(url+"/users"))
                 .header("Authorization", authorizationHeader)
                .build();
        response = client.send(request, HttpResponse.BodyHandlers.ofString());

这是一个不起作用的 POST 请求,这是我的问题。

mapper = new ObjectMapper();
        User testUser = new User();
        testUser.setUsername("newUser");
        testUser.setIsContributor(0);
        testUser.setFullName("newUser");
        testUser.setPassword("password");
        String json = mapper.writeValueAsString(testUser);
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url+"/users"))
                .setHeader("Authorization", authorizationHeader)
                .header(HttpHeaders.CONTENT_TYPE, "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(json))
                .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        

知道这里出了什么问题吗? 谢谢!

0 个答案:

没有答案