如何使用Vue.js登录用户到spring-security应用程序?

问题描述 投票:1回答:1

[嗨,这是我关于堆栈溢出的第一篇文章。我想将后端与前端分离,并使用Spring Boot应用程序创建REST API。我使用spring-security登录。它使用一种称为JSESSION_ID的名称,但是如何使用Vue.js登录并授权用户?我要填写表单以登录我的服务并使用JSESSION_ID授权请求。

这是我在Vue.js中的第一个应用程序。我尝试使用教程和文档中的代码,但是并不能解决我的问题。我对CORS也有疑问。

    export default {
        name: 'Login',
        data(){
            return{
                username: '',
                password: '',
                error: false
            }
        },
        updated(){
            if (localStorage.token){
                this.$router.replace(this.$route.query.redirect  || '/')
            }
        },
        methods:{
            login(){
                this.$http.post('http://localhost:8080/login', { username: this.username, password: this.password })
                    .then(request => this.loginSuccessful(request))
                    .catch(() => this.loginFailed())
            },
            loginSuccessful (req) {
                if (!req.data.token) {
                    this.loginFailed();
                    return
                }
                this.error = false;
                localStorage.token = req.data.token;
                this.$router.replace(this.$route.query.redirect || '/')
            },
            loginFailed () {
                this.error = 'Login failed!';
                delete localStorage.token
            }
        }
    }

我希望使用REST Spring-Boot API从Vue.js登录并授权用户。

javascript java spring vue.js vuejs2
1个回答
0
投票

问题是您尝试将对象{ username: this.username, password: this.password }作为数据传递给请求,但未指定Content-Type,它可能默认为'text / html'或'application / json'。您可以尝试先将其转换为表单数据,然后将其传递给请求,这是AXIOS的示例:

login() {
  let formData = new FormData();
  formData.set("username", this.username);
  formData.set("password", this.password);
  AXIOS.post('/login', formData, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
      .then((result) => {
        this.loginSuccessful(result);
      })
      .catch((error) => {
        this.loginFailed();
      })
}

也许在不指定标题的情况下也可以使用,例如AXIOS.post('/login', formData, null),没有尝试过。

© www.soinside.com 2019 - 2024. All rights reserved.