-1

我目前正在尝试为我的 spring 应用程序添加安全性,只想知道如何将凭据添加到请求中,以便它具有访问 getall URL 的安全访问权限这是我的客户端应用程序上的邮政编码

    public void save(String object) {
    try {
        final String URL = "http://localhost:8080/opject/getall";
        Gson g = new Gson();
        String jsonsStrinjg = g.toJson(object);
        String p = post(URL, jsonsStrinjg);
        if (p != null)
            JOptionPane.showMessageDialog(null,"Sucsess");
        else
            JOptionPane.showMessageDialog(null,"Fail");


    }catch (Exception e){
        JOptionPane.showMessageDialog(null,e.getMessage());
    }
}

public String post(final String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();
    try(Response response= client.newCall(request).execute()){
        return response.body().string();

    }

}

这是我的服务器端处理安全性的代码

@Configuration
@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {


@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  auth.inMemoryAuthentication()
          .withUser("Admin")
          .password(encoder().encode("123"))
          .roles("ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST,"**/getall").hasRole("ADMIN")
                .and()
                .csrf().disable()
                .formLogin().disable();
}
@Bean
public PasswordEncoder encoder(){

    return  new BCryptPasswordEncoder();


}

那么有什么我必须添加到他的正文或请求中,我可以在其中添加密码和用户名。

4

1 回答 1

0

您必须将基本身份验证添加到您的标题中,如下所示,

Authorization: Basic <base64encode(userid:password)>

为了实现这一点,

String auth = username + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")) );
String authHeader = "Basic " + new String( encodedAuth );

然后authHeader在调用 api 时将其设置为 http 标头。

于 2021-10-18T14:35:08.517 回答