实际上,我有一个前端(Angular 7)和后端(Symfony 4.2)环境分离的网络应用程序。用户与 Google OAuth2 连接。我想允许用户将他们的游戏平台帐户(如 Battle.net、Steam、XBOX...)链接到他们的网络应用程序帐户(如 Discord Connections)。为此,我使用了授权代码流(https://develop.battle.net/documentation/guides/using-oauth/authorization-code-flow)。我不明白实现这一点的工作流程,我应该将用户从前端直接重定向到 Auth 页面并重定向到 API 吗?但是如果我这样做,我怎样才能从前端部分检索访问令牌?
实际上,用户单击前端应用程序中的按钮,它会将他重定向到构建 oauth URL 的后端路由(使用 client_id、redirect_uri 等参数),然后重定向到授权页面。
战网平台用户认证后,通过代码将用户重定向到后端回调,但我不知道该怎么办,如何重定向或更新前端?
前端 :
<a href="{{ battleNetConnection }}" target="_blank" class="btn">Link your account</a>
<div class="container">
<p *ngIf="!battleNet.account">You need to link your battle.net account first.</p>
<!-- I need to update this part after the user have linked his account. -->
<p *ngIf="battleNet.account">{{ battleNet.account.btag }}</p>
</div>
import { Component, OnInit } from '@angular/core';
import { environment } from '../../../../environments/environment';
@Component({
selector: 'app-manage-platforms',
templateUrl: './manage-platforms.component.html',
styleUrls: ['./manage-platforms.component.scss']
})
export class ManagePlatformsComponent implements OnInit {
public battleNetConnection = `${environment.api.url}/connections/battlenet`;
constructor() {
}
ngOnInit() {}
}
后端:
控制器 :
class BattleNetController extends AbstractController
{
/** @var BattleNetHttpClient $battleNetHttpClient */
private $battleNetHttpClient;
/**
* @param BattleNetHttpClient $battleNetHttpClient
*/
public function __construct(BattleNetHttpClient $battleNetHttpClient)
{
$this->battleNetHttpClient = $battleNetHttpClient;
}
/**
* @Route("/connections/battlenet", name = "connections_battlenet")
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function authorize()
{
return $this->redirect($this->battleNetHttpClient->getAuthorizationUrl());
}
/**
* @Route("/connections/battlenet/callback", name = "connections_battlenet_callback")
*
* @param Request $request
*/
public function callback(Request $request)
{
$code = $request->get('code');
// What am I supposed to do there ?
}
}
服务 :
class BattleNetHttpClient extends AbstractHttpClient
{
const BASE_URI = 'https://eu.battle.net';
const AUTH_ENDPOINT = '/oauth/authorize';
/** @var array $config */
private $config;
/**
* @param array $config
* @param HttpClient $httpClient
* @param RequestStack $requestStack
*/
public function __construct(array $config, HttpClient $httpClient, RequestStack $requestStack)
{
parent::__construct($httpClient, $requestStack);
$this->config = $config;
}
/** {@inheritdoc} */
public function getAuthorizationUrl()
{
$params = http_build_query([
'client_id' => $this->config['client_id'],
'redirect_uri' => $this->getBaseUrl() . '/connections/battlenet/callback',
'response_type' => 'code',
]);
$url = self::BASE_URI . self::AUTH_ENDPOINT . '?' . $params;
return $url;
}
}
我想在登录后在链接平台上获取用户信息(如用户名,如果他实际上在这个平台上登录......),然后从平台 API 中检索 access_token 以允许对他们的请求。