首页 > 解决方案 > 使用 OAuth2.0 进行身份验证后,谷歌身份验证页面未重定向

问题描述

我正在使用 Spring Boot 应用程序使用 OAuth2.0 设置弹簧安全性。身份验证页面与已经登录的谷歌用户一起出现,但在选择一个后,它再次加载相同的身份验证页面。

家庭控制器.java

import java.security.Principal;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
public class HomeController {


    @RequestMapping("/")
    public ModelAndView home() {
        System.out.println("inside home");
        ModelAndView model = new ModelAndView("home");
        return model;
    }

    @RequestMapping("/login")
    public ModelAndView loginPage() {
        System.out.println("inside login");
        ModelAndView model = new ModelAndView("login");
        return model;
    }

    @RequestMapping("user")
    @ResponseBody
    public Principal user(Principal principal) {
        System.out.println("inside userrrrrrrrr");
        return principal;
    }
}

AppSecurityConfig.java

@Configuration
@EnableWebSecurity  
@EnableOAuth2Sso
public class AppSecurityConfig extends WebSecurityConfigurerAdapter{

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

       // System.out.println(httpSecurity.);
        try {
            System.out.println("inside configure");
            httpSecurity
            .csrf().disable()
            .authorizeRequests().antMatchers("/login").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin().disable();
        }catch(Exception e) {
            System.err.println("exception caught:"+e);
        }   

    }
}

这是我用于 OAuth 配置的 application.properties 文件:我正在更改客户端 ID 和客户端密码。

security.oauth2.client.client-id = 434559791042-642qk4agcs32g1rajsssss62ilrd86s4.apps.googleusercontent.com
security.oauth2.client.client-secret = 1l4jqw7lBailpuVgWobvcxwo 
security.oauth2.client.access-token-uri = https://www.googleapis.com/oauth2/v3/token
security.oauth2.client.user-authorization-uri = https://accounts.google.com/o/oauth2/auth
security.oauth2.client.tokenName = oauth_token
security.oauth2.client.authenticationScheme = query
security.oauth2.client.clientAuthenticationScheme = form
security.oauth2.client.scope = profile email

security.oauth2.resource.user-info-uri = https://www.googleapis.com/userinfo/v2/me
security.oauth2.resource.preferTokenInfo = false

在我的 google api 应用程序中,我给出了以下重定向。

授权的 JavaScript 来源:http://localhost:8080 授权的重定向 URI:http://localhost:8080/login

谷歌身份验证框架与我已经登录的帐户一起提供,但是当我选择它时,它再次显示相同的身份验证框架。它应该在身份验证后重定向到我的本机应用程序。

标签: spring-bootoauth-2.0spring-security-oauth2

解决方案


检查 redirect_uri Spring 正在发送给 Google。您可以在浏览器中通过右键单击并选择检查来执行此操作,然后选择网络选项卡。因此,当您在 web 应用程序中选择登录 google 时,您应该会看到 spring 向您的浏览器发送重定向响应,它将发送给 Google,并且它将包含一个参数 redirect_uri,这是 Google 会将重定向发送到的。确保它是正确的。并确保它与您在 API 页面中提供给 Google 的 URI 匹配,因为 Google 会阻止任何它不知道的内容。


推荐阅读