如何使用Grails

时间:2016-07-21 11:13:09

标签: grails oauth spring-security-oauth2

我正在为我的Grails项目使用OAuth插件,以便用户登录我的页面。我正在将facebook,google和linkedIn集成到我的网络应用程序中。 OAuth插件使用springSecurityOAuth插件以及针对facebook,google和linkedIn的相应OAuth插件。  但是插件只是从社交网站获取userId,而我需要提取其他个人资料信息,如firstname,lastname email等。我怎样才能做到这一点?

我已经从facebook获得了电子邮件和public_profile所需的权限。

UPDATE ::我手动编写代码以从提供者那里获取诸如firstname,lastname等信息。我从谷歌获得所需的数据,但不是从Facebook获得。我在这里做错了吗?

PS:我从SpringSecurityOAuthService复制了相同的代码来获取信息,并为各自的提供者制作了两个代码,如下所示:

def getUserDetailsGoogle(googleAccessToken){

    if (provider=='google'){
        def response = oauthService.getGoogleResource(googleAccessToken, 'https://www.googleapis.com/oauth2/v1/userinfo')
        def googleResponse
        try {
            googleResponse = JSON.parse(response.body)
        } catch (Exception e) {
            log.error "Error parsing response from Google. Response:\n${response.body}"
            throw new OAuthLoginException('Error parsing response from Google', e)
        }

        return googleResponse
    }
}

def getUserDetailsFacebook(facebookAccessToken){
    def response = oauthService.getFacebookResource(accessToken, 'https://graph.facebook.com/me')
    def user
    try {
        facebookResponse = JSON.parse(response.getBody())
    } catch (Exception e) {
        log.error "Error parsing response from Facebook. Response:\n${response.body}"
        throw new OAuthLoginException("Error parsing response from Facebook", e)
    }
    if (! facebookResponse?.id) {
        log.error "No user id from Facebook. Response:\n${response.body}"
        throw new OAuthLoginException("No user id from Facebook")
    }
    return facebookResponse
}

1 个答案:

答案 0 :(得分:0)

在我的Grails 2.5.X应用程序中,我使用pac4j通过将这些依赖项添加到BuildConfig.groovy

来对Facebook,Google等进行身份验证
dependencies {       
    compile 'org.pac4j:pac4j-core:1.6.0',
    compile 'org.pac4j:pac4j-oauth:1.6.0'
}

相关的controller class如下所示。如果你想查看它调用的OauthService的来源(或其他任何内容),请查看我链接到的GitHub存储库。

@Secured(['permitAll'])
class OauthController {

    OauthService oauthService
    GrailsApplication grailsApplication
    SpringSecurityService springSecurityService
    UserRegistrationService userRegistrationService

    /**
     * Starts the OAuth authentication flow, redirecting to the provider's Login URL. An optional callback parameter
     * allows the frontend application to define the frontend callback URL on demand.
     */
    def authenticate(String provider) {
        BaseOAuthClient client = oauthService.getClient(provider)
        WebContext context = new J2EContext(request, response)

        RedirectAction redirectAction = client.getRedirectAction(context, true, false)
        log.debug "Redirecting to ${redirectAction.location}"
        redirect url: redirectAction.location
    }

    /**
     * Handles the OAuth provider callback.
     */
    def callback(String provider, String error) {
        WebContext context = new J2EContext(request, response)

        if (!error) {
            try {
                CommonProfile profile = oauthService.getUserProfile(provider, context)
                User registeredUser = userRegistrationService.socialSignIn(profile, provider)

                if (!registeredUser.isAttached()) {
                    // User is trying to register with an OAuth provider (e.g. Twitter, Yahoo), that doesn't provide their
                    // email address so they need to submit a form to supply us with their email
                    render view: '/register/confirmEmail', model: [user: registeredUser]
                    return
                }
                springSecurityService.reauthenticate(registeredUser.username)
                flashHelper.info 'social.login.success': provider
                redirect uri: '/'
                return
            } catch (ex) {
                log.error "Error occurred during callback from OAuth2 provider '$provider'", ex
            }
        } else {
            // Most likely explanation is that the user denied access on the consent screen which is not really an error
            log.warn "Callback from OAuth2 provider '$provider' failed due to error: $error"
        }

        flashHelper.warn 'social.login.fail'
        redirect uri: '/'
    }
}