我正在尝试使用Laravel中的社交名称设置Google登录。但是当我输入Google凭据时,它会显示:
页面未正确重定向
表示网址http://127.0.0.1:8000/redirect/google
。
我的web.php是:
Route::get('/redirect/google', 'SocialAuthController@redirect');
Route::get('/callback/google', 'SocialAuthController@callback');
services.php:
'google' => [
'client_id' => '-----.apps.googleusercontent.com',
'client_secret' => '---------',
'redirect' => 'http://127.0.0.1:8000/callback/google'
],
SocialAuthController.php:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\SocialAccountService;
use Socialite;
class SocialAuthController extends Controller {
//
public function redirect(){
return Socialite::driver('google')->redirect();
}
public function callback(SocialAccountService $service) {
$user = $service->createOrGetUser(Socialite::driver('google')->user());
auth()->login($user);
return redirect()->back();
}
}
SocialAccount.php:
namespace App;
use Illuminate\Database\Eloquent\Model;
class SocialAccount extends Model {
//
protected $fillable = ['user_id', 'provider_user_id', 'provider'];
public function user() {
return $this->belongsTo(User::class);
}
}
迁移为social_accounts_table
class CreateSocialAccountsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create('social_accounts', function (Blueprint $table) {
$table->increments('user_id');
$table->string('provider_user_id');
$table->string('provider');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists('social_accounts');
}
}
SocialAccountService.php
namespace App;
use Laravel\Socialite\Contracts\User as ProviderUser;
class SocialAccountService {
public function createOrGetUser(ProviderUser $providerUser) {
$account = SocialAccount::whereProvider('google')
->whereProviderUserId($providerUser->getId())
->first();
if ($account) {
return $account->user;
} else {
$account = new SocialAccount([
'provider_user_id' => $providerUser->getId(),
'provider' => 'google'
]);
$user = User::whereEmail($providerUser->getEmail())->first();
if (!$user) {
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
'role' => 'user',
'password' => '',
]);
}
$account->user()->associate($user);
$account->save();
return $user;
}
}
}
答案 0 :(得分:0)
在您的服务中,您有
p
经过身份验证后,Google无法访问您的域'redirect' => 'http://127.0.0.1:8000/callback/google'
(localhost)。您必须使用生产URL
答案 1 :(得分:0)
我已经解决了这个问题,问题是我在回调函数中的redirect() - > back()调用。我仍然需要找到如何重定向回原始源页面,但重定向到home,已经解决了这个问题。