【Web前端问题】spring security 前端登录后,请求后台api报302

问题描述

我在spring boot项目中引入有了security" title="spring security">spring security来做登录验证这样的事情.因为是前后端分离的项目,所以,我的前端有个这样的登录请求

        function login(){

$.ajax({

useDefaultXhrHeader: false,

type:"post",

url:"http://127.0.0.1:8080/user/login",

data:{"userName": document.getElementById("userName").value,

"password":document.getElementById("password").value},

dataType:'json',

success:function (result) {

console.log(result);

if(result["code"] == 0) {

showVideoByAll();

setCookie("username",result["username"],1);

alert("login success");

// location.href = "./index.html";

} else {

alert("invalid password or userName")

}

},

error:function () {

alert("error")

}

});

}

在登录后,我使用ajax调后台的接口

    function showVideoByAll(){/**/

$.ajax({

useDefaultXhrHeader: false,

type:"GET",

url:"http://127.0.0.1:8080/video/selectVideoByAll",

data:"",

dataType:'json',

success:function (result) {

alert("success")

console.log(result);

},

error:function () {

alert("error");

}

});

}

这是后台的security配置

 @Override

protected void configure(HttpSecurity httpSecurity) throws Exception {

httpSecurity

.formLogin()

.loginProcessingUrl("/user/login")

.usernameParameter("userName")

.passwordParameter("password")

.successHandler(myAuthenticationSuccessHandler)

.failureHandler(myAuthenticationFailureHandler)

.and()

.authorizeRequests()

.antMatchers("/user/register","/user/login",

"/swagger-ui.html",

"/swagger-resources/**",

"/webjars/**",

"/v2/api-docs",

"Swagger2Config").permitAll()

.anyRequest().authenticated()

.and()

.logout()

.logoutUrl("/user/logout")

.logoutSuccessHandler(myLogoutSuccessHandler)

.permitAll()

.and()

.cors().and()

.csrf().disable();

}

可以看到我配置了

  .csrf().disable();

这是后台controller的部分代码

@RestController

@CrossOrigin

@RequestMapping("/video")

public class VideoController {

@Autowired

private VideoDAO videoDAO;

/**

* @return

*/

@RequestMapping(value = {"/selectVideoByAll"}, method = RequestMethod.GET)

public ResultModel selectVideoByAll() {

try {

List<Video> videoList = videoDAO.selectVideoByAll();

Map<String, Object> map = new HashMap<String, Object>();

map.put("content", videoList);

return ResultUtil.result(0, "", map);

} catch (Exception e) {

return ResultUtil.result(404, e.getMessage(), null);

}

}

...

我在前端成功登录,

clipboard.png

clipboard.png

我想这确实是登录成功了吧,然后我的showVideoByAll()请求确实这样的结果

clipboard.png

clipboard.png

可以看到showVideoByAll请求的cookie值和login的也不一样,我不是很清楚是什么原因导致的.

总结起来,问题就是,我登录成功了,但是请求api还是失败.当然,我用后台的地址直接访问是没有问题的.

clipboard.png

so,有人可以帮助我一下吗?感谢感谢,真心求教!

回答:

这是跨域问题

以上是 【Web前端问题】spring security 前端登录后,请求后台api报302 的全部内容, 来源链接: utcz.com/a/141258.html

回到顶部