首页 > 解决方案 > 具有基本身份验证和 cors 的 Spring Boot

问题描述

我正在学习spring boot,我对基本身份验证和cors有一些疑问。

我创建了两个页面和 ajax 到后端。

第一个页面ajax用户名和密码到后端,方法是POST。此外,它使用基本身份验证。如果成功,第一页将重定向到第二页。

加载第二页后,第二页将 ajax 到后端。它使用 GET 并且除了 HTTP.Status 之外不会获得任何数据。

这是我在第一页中的 ajax 函数。

function login () {
            var username = document.getElementById("username").value;
            var password = document.getElementById("password").value;

            alert(btoa(username + ":" + password));

            var settings = {
                "async": true,
                "crossDomain": true,
                "url": "http://localhost:10000/login",
                "method": "POST",
                "headers": {
                    "content-type": "application/json",
                    "accept": "application/json",
                    "authorization": "Basic " + btoa(username + ":" + password),
                    "cache-control": "no-cache",
                }
            }

            alert(settings);

            $.ajax(settings).done(function (response) {
                console.log(response);
                localStorage.setItem("token", btoa(username + ":" + password));
                window.location = "file:///home/cyl/SecurityTest/pages/getEmployeePage.html"
            });
}

这是我在第二页中的 ajax 函数。

function getData () {
            alert(localStorage.getItem("token"));
            var settings = {
                "async": true,
                "crossDomain": true,
                "url": "http://localhost:10000/getAllEmployee",
                "method": "GET",
                "headers": {
                    "authorization": "Basic " + localStorage.getItem("token"),
                    "accept": "application/json",
                    "content-type": "application/json",
                    "cache-control": "no-cache"
                }
            }

            $.ajax(settings).done(function (response, textStatus, xhr) {
                console.log(response);

            });
        }

这是我的 RestController

@RestController
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class EmployeeController {

    @CrossOrigin(origins="*", allowedHeaders = "*")
    @PostMapping(path = "/login")
    public ResponseEntity<String> login() {
        return new ResponseEntity<String>(HttpStatus.ACCEPTED);
    }

    @CrossOrigin(origins="*", allowedHeaders = "*")
    @GetMapping(path = "/getAllEmployee")
    public ResponseEntity<String> getAllEmployee() {
        //List<Employee> employeeList = this.employeeDAO.getAllEmployee();
        return new ResponseEntity<String>(HttpStatus.OK);
    }
}

CorsConfig

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST")
                .allowCredentials(true);
    }
}

但是在第二页步骤中,我收到一个错误“从源'null' 访问 XMLHttpRequest 在' http://localhost:10000/getAllEmployee ' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查: 它没有 HTTP ok 状态。”

尽管我搜索了一些相关问题,但我无法处理这个问题。

除了这个问题,我在客户端存储身份验证令牌的方式是正确的方式吗?如果没有,我该怎么做?

谢谢!

标签: springspring-boot

解决方案


如果您在本地机器上运行相同的 spring 项目,则可以使用此 Spring 注解,并且带有此标记的 JS 项目将允许您访问其余服务

@CrossOrigin(origins = "*", maxAge = 3600)
public class controllerRest{} 

问候!


推荐阅读