使用basicauth的Ajax CORS请求在浏览器上出现401错误

时间:2018-02-28 05:17:51

标签: java ajax spring spring-boot cors

我知道有很多关于同一问题的帖子,但没有一个能解决我的问题。

我有一个带有以下API的springboot微服务应用程序

@RestController
@RequestMapping({ "/sample" })
public class SampleController {


    @CrossOrigin(origins = "http://192.168.0.31:8080", allowCredentials = "false", allowedHeaders = "*")
    //@CrossOrigin//(allowCredentials = "false")
    @RequestMapping(value="/welcome" , method=RequestMethod.POST, produces={"application/json"})
    public JSONObject getWelcomeResponse(@RequestParam Map<String,String> request){
        JSONObject response=new JSONObject();

        response.put("response", "Welcome user");
        System.out.println("Complterd ****");
        return response;
    }
}

属性文件

server.port=8081
security.user.name=test
security.user.password=test123
#security.basic.enabled=false

我的客户端代码是

 $(document).ready(function(){
            $.ajax({
                url: "http://192.168.0.31:8081/sample/welcome",
                type : "POST",
                crossDomain:true,
                crossOrigin:true,

                beforeSend: function (xhr) {
                    // Use BASIC Authentication
                    xhr.setRequestHeader ("Authorization", "Basic " + btoa("test:test123"));
                },
                error: function(xhr, status, errorThrown) {
                    alert(status, errorThrown);
                    // Error block
                    console.log("xhr: " + xhr);
                    console.log("status: " + status);
                    console.log("errorThrown: " + errorThrown);
                }
            })
            .then(function(data, status, xhr) {
                alert(data);
                console.log("xhr: " + xhr);
                console.log("status: " + status);
                console.log("data: "+ data);

                $('.message').append(JSON.stringify(data));

            });
        });

当我禁用基本身份验证时,cors请求工作正常。但如果启用它会给出401预检请求错误。

我已尝试使用默认的@CrossOrigin以及自定义方式。但得到同样的错误。还尝试使用如下所示的过滤器类。

@EnableWebMvc
public class MyAppConfigurations  implements Filter {

       @Override
       public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

                     throws IOException, ServletException {

              HttpServletResponse httpResponse = (HttpServletResponse) response;

              HttpServletRequest httpRequest = (HttpServletRequest) request;

              if("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {

                     httpResponse.setStatus(HttpServletResponse.SC_OK);
                     System.out.println("filterde response");

              } else {

                     chain.doFilter(request, response);

              }
       }
}

有人可以帮我弄清楚,我在这段代码上缺少什么。

3 个答案:

答案 0 :(得分:1)

您必须为import { APP_BASE_HREF } from "@angular/common"; export const sharedConfig: NgModule = { bootstrap: [ AppComponent ], declarations: [ AppComponent, ... ], imports: [ HttpModule, ..., RouterModule.forRoot([ { path: "", redirectTo: "home", pathMatch: "full" }, { path: "**", redirectTo: "home" } ], { useHash: true }), ], providers: [ { provide: APP_BASE_HREF, useValue: '/' }, ], };

创建CORS FILTER
Spring MicroService

答案 1 :(得分:0)

在课前添加@CrossOrigin,如

@RequestMapping({ "/sample" })
@CrossOrigin(origins = "http://192.168.0.31:8080")
public class SampleController {

尝试添加/welcome Rest Controller

response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

答案 2 :(得分:0)

根据CORS specification,无需任何身份验证即可接受CORS预检请求。

您必须配置您的Web服务器或Spring Security以禁用与预检相关的所有OPTIONS请求的身份验证。