【问题标题】:Vue + Google oAuth2 + Spring Boot Rest Api + different portsVue + Google oAuth2 + Spring Boot Rest Api + 不同的端口
【发布时间】:2021-06-05 00:39:31
【问题描述】:

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

  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);
    }
}

包 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;
    }
}
  • 我的 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/oauth2/authorization/google 并成功使用 Google 进行身份验证并获取用户数据

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

访问的XMLHttpRequest在“https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=964744021349-cvsr63lt5gvb8dgatihgegr4d1hcqqsc.apps.googleusercontent.com&scope=openid%20profile%20email&state=Vk2BoAfzU7xY7a00SXjzLWn2dW6WThgaNsDVrY_9m3I%3D&redirect_uri= http://localhost:8081/login/oauth2/code/google&nonce=ziJzRyteq-DSKN7MUHcFy918PJK9PNGQdU5jp4_kMsI'(重定向自'http://localhost:8081/oauth2/authorization/google')来自来源'http://localhost:8080'已被 CORS 政策阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

然后this post 回答对我有一点帮助,在我将标头:{} 添加到 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;
            })
    }

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

请指点我正确的方向

【问题讨论】:

    标签: spring-boot rest vuejs2 spring-security-oauth2


    【解决方案1】:

    回答我的帖子:

    我应该反过来做。

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

    解决方案看起来像

    1. Vue登录组件有href="/api/fwd">登录
    2. 后端 rest api 重定向到 "response.sendRedirect("/oauth2/authorization/google");"
    3. 然后谷歌身份验证表单打开,身份验证过程完成,然后根据安全采用者在 spring 成功登录将我们重定向到这里 defaultSuccessUrl("/api/logged-user")
    4. 然后我们通过重定向 "response.sendRedirect("http://localhost:8080/login%22);" 回到前端
    5. 最后,在使用 axios 创建的钩子的前端,我们从 spring rest api - ResponseEntity.ok(principal) 获取用户配置文件数据

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

    【讨论】:

    • 在完全相同的问题上运行,谢谢!
    猜你喜欢
    • 2017-02-12
    • 2016-12-31
    • 2020-11-05
    • 2018-03-30
    • 2017-05-28
    • 1970-01-01
    • 2018-05-07
    • 2017-09-26
    • 2020-08-27
    相关资源
    最近更新 更多