【问题标题】:Axios Interceptor is not working after page refresh (Vue.js)页面刷新后 Axios 拦截器不起作用(Vue.js)
【发布时间】:2020-11-18 15:49:05
【问题描述】:

我正在开发一个简单的 crud-application,它是用 spring、vue.js 和 h2 数据库开发的。

我差不多完成了,但不幸的是,我在身份验证方面遇到了一些问题。当我键入所有必需的凭据时,登录将成功,我将被重定向到带有餐表的页面,该页面显示来自 API 的数据。

当我点击其他页面时,控制台突然向我显示一条错误消息: [1]:https://i.stack.imgur.com/zQBw0.png

过了一会儿,我把所有的“href”都换成了“to”。最后,通过 Web 应用程序的导航工作正常,并且对数据的访问也没有被拒绝。不幸的是,刷新页面后,访问被拒绝,我再次收到上述错误消息。

如果我的用户帐户在页面刷新后仍然保存,我已经检查了浏览器中的会话存储并且是这种情况。

我不知道,确切的错误是什么。

感谢您的帮助:)

后端:

SpringSecurityConfigurationAuthentication.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SpringSecurityConfigurationAuthentication extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .anyRequest().authenticated()
                .and()
                //.formLogin().and()
                .httpBasic();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
      authenticationManagerBuilder.inMemoryAuthentication()
              .withUser("admin")
              .password("{noop}admin")
              .roles("ADMIN")
              .and()
              .withUser("user")
              .password("{noop}user")
              .roles("USER");

    }
}

AuthenticationBeanController.java

@RestController
@RequestMapping(value="/basicauth")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class AuthenticationBeanController {


    @GetMapping
    public AuthenticationBean authenticating() {
       return new AuthenticationBean("You are authenticated");
    }

}

前端 Vue.js:

http-common.js:

import axios from 'axios'

    export default axios.create({
        baseURL: "http://localhost:8080",
        headers: {
            "Content-type": "application/json",
        }
    })

AuthenticationService.js

import http from '../http-common'

class AuthenticationService {
    registerSuccesfulLogin(username, password) {
        this.setupAxiosInterceptors(this.createBasicAuthToken(username, password))
    }

    startAuthentication(username, password) {
        return http.get('/basicauth', {headers: {authorization: this.createBasicAuthToken(username, password)}});

    }

    createBasicAuthToken(username, password) {
        let userToken = 'Basic ' + window.btoa(username + ":" + password);
        sessionStorage.setItem('authenticatedUser', username)
        return userToken
    }

    logout() {
        sessionStorage.removeItem('authenticatedUser');
    }

    isUserLoggedIn() {
        let user = sessionStorage.getItem('authenticatedUser');
        if (user === null) return false
        return true
    }

    setupAxiosInterceptors(userToken) {
        http.interceptors.request.use(
            (config) => {
                if (this.isUserLoggedIn()) {
                    config.headers.Authorization = userToken
                }
                return config
            }
        )
    }
}

export default new AuthenticationService();

MealDataService.js

import http from '../http-common'

class MealDataService {
    retrieveAllMeals() {
        return http.get('/meal');
    }
    deleteMealById(id) {
        return http.delete(`/meal/${id}`);
    }
    getMealById(id) {
        return http.get(`/meal/${id}`);
    }
    updateMealById(data) {
        return http.put('/meal', data);
    }
    addMealById(data) {
        return http.post('/meal', data);
    }
}
export default new MealDataService();

【问题讨论】:

    标签: vue.js spring-security axios interceptor


    【解决方案1】:

    可能的线索: 由于您的应用程序是单页客户端应用程序,没有适当的服务器配置,如果用户直接在浏览器中访问与主页不同的任何其他路由(或通过清爽)。

    查看您的网络服务器配置,看看是否有任何配置可以处理此行为HTML5 history mode

    【讨论】:

      猜你喜欢
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 2018-01-20
      • 2022-01-25
      • 1970-01-01
      • 2018-07-27
      • 2021-02-11
      相关资源
      最近更新 更多