You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Grails 3.1.9集成Spring Security OAuth2谷歌登录功能咨询

Getting Google Sign-In Working in Grails 3.1.9 with Spring Security OAuth2

Hey there! Let's walk through getting that Google Sign-In button up and running smoothly with the dependencies you've already added. I'll break this down into actionable, easy-to-follow steps:

1. Core Configuration in application.groovy

First, wire up your Google OAuth2 credentials and configure Spring Security to use them. Add these settings to your grails-app/conf/application.groovy:

// Enable Spring Security OAuth2 functionality
grails.plugin.springsecurity.oauth2.active = true

// Google OAuth2 Credentials (copy these from your Google Cloud Console)
grails.plugin.springsecurity.oauth2.google.clientId = "YOUR_GOOGLE_CLIENT_ID"
grails.plugin.springsecurity.oauth2.google.clientSecret = "YOUR_GOOGLE_CLIENT_SECRET"

// Scopes to fetch essential user data (required for login logic)
grails.plugin.springsecurity.oauth2.google.scope = "openid,email,profile"

// Callback URL (must match exactly what you entered in Google's "Authorized redirect URIs")
grails.plugin.springsecurity.oauth2.google.redirectUri = "http://localhost:8080/oauth2/google/callback"

// Base Spring Security settings
grails.plugin.springsecurity.auth.loginFormUrl = "/login"
grails.plugin.springsecurity.successHandler.defaultTargetUrl = "/"
// Allow unauthenticated access to login and OAuth2 endpoints
grails.plugin.springsecurity.securityConfigType = "InterceptUrlMap"
grails.plugin.springsecurity.interceptUrlMap = [
    "/login": ["permitAll"],
    "/oauth2/**": ["permitAll"],
    "/**": ["isAuthenticated()"]
]

Critical Check: The redirectUri must match the value in your Google Cloud Console exactly—even a missing trailing slash or wrong port will break the authorization flow!

2. Add the Google Sign-In Button to Your Frontend

You have two flexible options here:

Option 1: Use the Built-in OAuth2 Taglib

The spring-security-oauth2 plugin provides a taglib to generate the sign-in link automatically. Drop this into your login page (e.g., grails-app/views/login/index.gsp):

<oauth2:connect provider="google" class="btn btn-danger">
    Sign in with Google
</oauth2:connect>

This renders a pre-built link that directly triggers Google's authorization flow.

If you want full control over styling, create a custom anchor tag:

<a href="${createLink(uri: '/oauth2/google/auth')}" class="btn btn-danger">
    <i class="fab fa-google"></i> Sign in with Google
</a>

Add your own CSS or Google's official sign-in styling here to match your app's design.

3. Handle User Mapping & Authentication

Once a user authorizes via Google, your app needs to map their Google profile to a local user account. Customize this logic with a service:

Create grails-app/services/com/yourapp/CustomOAuth2UserService.groovy:

import grails.plugin.springsecurity.SpringSecurityService
import grails.plugin.springsecurity.oauth2.user.DefaultOAuth2UserService
import grails.plugin.springsecurity.oauth2.user.OAuth2User
import org.springframework.security.core.userdetails.UserDetails

class CustomOAuth2UserService extends DefaultOAuth2UserService {

    SpringSecurityService springSecurityService

    @Override
    UserDetails loadUser(OAuth2User oAuth2User) {
        // Extract data from Google's response
        String googleId = oAuth2User.id
        String email = oAuth2User.email
        String fullName = oAuth2User.displayName

        // Check if user already exists in your local database
        def user = User.findByEmail(email) ?: User.findByGoogleId(googleId)

        if (!user) {
            // Create a new user if they're signing in for the first time
            user = new User(
                email: email,
                username: email, // Use email as username if your setup requires it
                fullName: fullName,
                googleId: googleId,
                enabled: true
            ).save(flush: true, failOnError: true)
        }

        // Return a valid UserDetails instance (use your custom implementation if needed)
        springSecurityService.loadUserByUsername(user.username)
    }
}

Register this custom service in application.groovy to replace the default:

grails.plugin.springsecurity.oauth2.userService = 'customOAuth2UserService'

Note: Ensure your User domain class has fields for googleId, email, etc., and is configured to work with Spring Security's user lookup.

4. Test the Flow

  1. Start your Grails app
  2. Navigate to the login page
  3. Click the "Sign in with Google" button
  4. Authenticate with your Google account and authorize the app
  5. You should be redirected back to your app's landing page as a logged-in user

Quick Troubleshooting Tips

  • Redirect URI Mismatch: Double-check that the redirectUri in application.groovy matches the value in Google Cloud Console exactly.
  • Missing User Data: Ensure you included the openid, email, and profile scopes in your configuration.
  • Button Not Rendering: Confirm the OAuth2 taglib is auto-loaded (it should be with the plugin dependency).

内容的提问来源于stack exchange,提问作者Filip Boroš

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:36:59