我正在学习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);
}
}
但是在第二个页面步骤中,我得到了一个错误:“CORS策略阻止了从原始'null‘访问'http://localhost:10000/getAllEmployee’处的XMLHttpRequest :对印前检查请求的响应没有通过访问控制检查:它没有HTTP ok状态。”
我不能处理这个问题,尽管我搜索了一些相关的问题。
除了这个问题,我在客户端存储身份验证令牌的方式是正确的吗?如果没有,我如何做到这一点?
谢谢!
发布于 2020-12-05 10:27:39
如果您在本地计算机上运行相同的Spring项目,并且具有此标记的JS项目将允许您访问rest服务,则可以使用此spring注释
@CrossOrigin(origins = "*", maxAge = 3600)
public class controllerRest{}
致以问候!
https://stackoverflow.com/questions/56497187
复制相似问题