当前位置: 首页 > 知识库问答 >
问题:

Vue Google oAuth2 Spring Boot Rest Api不同端口

戴嘉珍
2023-03-14

我有一个web应用程序,它由两部分组成

  1. Spring boot rest,服务器端端口8081
  2. Vue vuex axios,端口8080上的前端
  • 在我的Spring Boot应用程序下方

包com.example.googleoauth;

package com.example.googleoauth;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class GoogleoauthApplication {

    public static void main(String[] args) {
        SpringApplication.run(GoogleoauthApplication.class, args);
    }
}

package com.example.googleoauth.Controllers;

package com.example.googleoauth.Controllers;

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.Map;

@RestController
@RequestMapping("/")
public class MainController {

    @GetMapping("/test")
    public String test() {
        return "Success test from Spring Boot";
    }

    @GetMapping("/login")
    public Map<String, Object> login(@AuthenticationPrincipal OAuth2User principal) throws IOException {
        return principal.getAttributes();
    }
}

包com.example.googleoauth.Configuration;

   package com.example.googleoauth.Configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
public class WebConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors().configurationSource(corsConfigurationSource())
                .and()
                .authorizeRequests(a -> a
                        .antMatchers("/", "/error", "/webjars/**", "/test").permitAll()
                        .anyRequest().authenticated()
                )
                .exceptionHandling(e -> e
                        .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
                )
                .oauth2Login().defaultSuccessUrl("/login");
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH", "OPTIONS"));
        configuration.setAllowCredentials(true);
        //the below three lines will add the relevant CORS response headers
        configuration.addAllowedOrigin("http://localhost:8080");
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

> < li>

我的Vue应用

 actions: {
 SIGNIN({commit}) {
     axios.get('http://localhost:8081/oauth2/authorization/google')
         .then((profile) => {
             commit('SET_AUTH_API', profile.data)
             return profile;
         })
         .catch((error) => {
             console.log(error)
             return error;
         })
 },

我可以访问http://localhost:8081/oauth 2/authorization/google,并使用Google成功进行身份验证,获取用户数据

但是我从端口8080通过Vue应用程序访问此链接时遇到问题,我在下面收到错误

在“中”访问XMLHttpRequesthttps://accounts.google.com/o/oauth2/v2/auth?response_type=code

在我向axios GET请求添加了标题:{}之后,这篇文章的回答对我有所帮助

在Chrome CORS扩展的帮助下,我摆脱了“已被CORS策略阻止”的消息,但当我发送时似乎什么都没有发生http://localhost:8081/oauth2/authorization/google“请求

    actions: {
    SIGNIN({commit}) {
        console.log("store-SIGNIN")
        const options = {
            method: 'GET',
            url: 'http://localhost:8081/oauth2/authorization/google',
            headers: {}
        };
        axios(options)
            .then((profile) => {
                // console.log(resp)
                console.log(1)
                commit('SET_AUTH_API', profile.data)
                console.log(2)
                return profile;
            })
            .catch((error) => {
                console.log(error)
                return error;
            })
    }

在我得到的开发控制台输出中

请给我指出正确的方向

共有1个答案

养振濂
2023-03-14

回复我的帖子:

我应该把整件事反过来做。

我在这个回购中找到了答案https://github.com/bmstefanski/spring-vue-rest-oauth2我需要一个完整的解决方案

解决方案看起来像

    < li>Vue登录组件具有

就是这样,没有CORS或选项错误(尽管我们需要后端的CORS配置)

 类似资料:
  • 问题内容: 我的php文件位于端口80(默认端口),而我的ajax调用位于端口8080上。 我在端口8080上的index.html 我的PHP 我有点google,JSONP大多出来了。知道如何将其转换为JSONP吗? 有什么办法可以使其工作? 问题答案: 实施JSONP服务非常简单,您只需要一个 回调 GET参数,最后,打印一个包含与以JSON数据作为参数的函数调用等效的字符串: 然后,您可以

  • 问题内容: 我想更改mysql docker容器的默认公开端口,但是如果我尝试使用此命令: 这没用。 如果我使用标准端口3306:3306,则工作正常,但我想更改端口。有可能吗? 我已经尝试过-p 52000:3600,但是我总是得到: 问题答案: 您需要在(服务器的)首选TCP端口上映射容器端口3306: 所以对于你的mysql

  • 本文向大家介绍Vue前后端不同端口的实现方法,包括了Vue前后端不同端口的实现方法的使用技巧和注意事项,需要的朋友参考一下 前端Vue 8080端口,后端Node.js 8085端口 主要记录下前后端不同端口遇到的问题 1、写服务器端程序,我的在(node_proxy/index.js)下 这段代码很重要,要是没有的话会出现 No 'Access-Control-Allow-Origin' hea

  • 在我的Spring Boot应用程序中,Hystrix与Feign一起工作。 我在使用: 如有任何帮助,不胜感激,谢谢!

  • 我在不同的端口(80008001)上运行后端和前端,无法从express服务器生成res.redirect(…),并且浏览器显示CORS错误(访问XMLHttpRequest at…)。 这是MEVN(Mongo,Express,Vue,Nodejs)应用程序,Vue前端和Express(nodejs)后端在不同的端口上运行。我在后端实现了cors(),它使我的前端可以发出请求(get,post)

  • 让我们假设一个后端应用程序,它公开了一些Rest API,运行在地址192.168.1.10:8889的Jetty网络服务器上。 我希望有一个前端应用程序(仅限于html/javascript,在apache2 Web服务器上)在相同的IP上运行,但在不同的端口(例如8000)上运行,它应该使用后端应用程序公开的API。 我怎样才能让这个架构工作而不进入“No'Access-Control-All