对于开发者来说,获取Github或者Google的第三方登陆权限相对于国内的很多方式要来的更加简单一些,毕竟国内诸如微信等方式都要经过复杂的审核,尴尬。
目录
Github
Demo
Github的获取方式相对简单,我们打开下面的网址:
https://github.com/settings/developers
按照操作一点点来就行,注意
Homepage URL:
开发就是本地的地址加端口,生产就不用说了
Authorization callback URL:
开发就是本地的回调,这个概念不理解的话去学一下Oauth
接着就会生成:
Client ID:
***
CLient Secret:
***
因为CSDN传图片又抽风了,只能这样写了。
Google的选项会稍微多一点:
https://console.developers.google.com
我们打开之后选择凭据,之后会有创建Oauth客户端ID的选项,选择这个之后,我们会进入一个选项页面,里面会发现有web应用的选项,点击之后,剩下的步骤同Github描述。
等回国之后会把图补上。
简单说一个后端Google Oauth的demo,使用的是nest.js,以及Node中比较流行的passport:
npm i --save @nestjs/passport passport passport-google-oauth20
首先我们创建一个验证的模块,一个控制器,还有一个模板文件:
nest generate module auth
nest generate controller auth
cd auth
touch google.auth.ts
首先是模板文件:
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-google-oauth20';
import 'dotenv/config'
const ID = process.env.ID
const SECRECT = process.env.SE
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
constructor() {
super({
clientID: ID,
clientSecret: SECRECT,
callbackURL: 'http://localhost:3000/auth/google/callback',
passReqToCallback: true,
scope: ['profile']
})
}
async validate(request: any, accessToken: string, refreshToken: string, profile, done: Function) {
try {
console.log(profile);
const jwt: string = 'placeholderJWT'
const user = {
jwt
}
done(null, user);
} catch (err) {
done(err, false);
}
}
}
关于验证部分我们不必太过在意,最主要的是clientID和clientSecret,这里使用dotenv从环境变量里面读取,记得要换成你自己的东西,然后是回调的callbackURL也要换成你设置的。
接着在module中写入:
import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { GoogleStrategy } from './google.strategy';
@Module({
controllers: [AuthController],
providers: [
GoogleStrategy
]
})
export class AuthModule {}
最后在控制器中添加endpoint:
import { Controller, Get, UseGuards, Res, Req } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Controller('auth')
export class AuthController {
@Get('google')
@UseGuards(AuthGuard('google'))
googleLogin() {
// initiates the Google OAuth2 login flow
}
@Get('google/callback')
@UseGuards(AuthGuard('google'))
googleLoginCallback(@Req() req, @Res() res) {
const jwt: string = req.user.jwt;
if (jwt) {
res.redirect('http://localhost:3000' + jwt);
} else {
res.redirect('http://localhost:3001');
}
}
}
这样我们在访问http://localhost:3000/auth/google的时候,就可以看到熟悉的第三方登陆页面。
如果登录成功即可返回 helloworld界面,如果你没有修改app.controler.ts的话。