我可能在這里弄錯了我的一些術語,但是經過幾天的反復試驗、谷歌搜索、symfony 檔案、在這里搜索和閱讀各種教程,我的頭可能有點炸了。
我在用什么:
- PHP 8.1.0
- 交響樂 (6)
- 用于 EveOnline 的 Evelabs OAuth2 提供程式
- MySQL 5.7
- 教義
在其他作曲家包中
我想要做的是重定向想要通過 SSO (EveOnline) 登錄到我的網站的用戶,在回傳到我的網站后,存盤相關資料并驗證用戶以訪問我網站上的會員專區。
將來我將代表用戶發出 ESI (EveSwaggerInterface) 請求。
目前我有 SSO 使用 OAuth2,我正在構建 URL,重定向到 Eve,用戶登錄并回傳給我,然后我捕獲回應,填充/更新資料庫或捕獲錯誤,最后重定向成員區域,都在我的控制器中。
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Evelabs\OAuth2\Client\Provider\EveOnline;
use Doctrine\Persistence\ManagerRegistry;
use App\Entity\User;
class SecurityController extends AbstractController
{
#[Route('/login', name: 'page_login')]
public function login_page()
{
return $this->render('login.html.twig');
}
#[Route('/redirect', name: 'app_login')]
public function login(ManagerRegistry $doctrine)
{
session_start();
$provider = new EveOnline([
'clientId' => $this->getParameter('eve.client_id'),
'clientSecret' => $this->getSecret,
'redirectUri' => $this->getParameter('eve.redirect_uri'),
]);
if (!isset($_GET['code'])) {
$options = [
'scope' => ['publicData'] // array or string
];
// If we don't have an authorization code then get one
$authUrl = $provider->getAuthorizationUrl($options);
$_SESSION['oauth2state'] = $provider->getState();
unset($_SESSION['token']);
header('Location: '.$authUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else{ // In this example we use php native $_SESSION as data store
if(!isset($_SESSION['token']))
{
$_SESSION['token'] = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
}elseif($_SESSION['token']->hasExpired()) {
// This is how you refresh your access token once you have it
$new_token = $provider->getAccessToken('refresh_token', [
'refresh_token' => $_SESSION['token']->getRefreshToken()
]);
// Purge old access token and store new access token to your data store.
$_SESSION['token'] = $new_token;
}try{
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getResourceOwner($_SESSION['token']);
//Store eve user data
$userdata = $accessToken->toArray();
//Init Entity Manager
$entityManager = $doctrine->getManager();
//Get Repo
$userobject = $doctrine->getRepository(User::class)->findBy(['userID' => $userdata['CharacterID']]);
//If user exist, update database
if ($accessToken && $userobject != null){
$id = $userobject[0]->getId();
$userobject[0]->setId($id);
$userobject[0]->setUserName($userdata['CharacterName']);
$userobject[0]->setUserID($userdata['CharacterID']);
$userobject[0]->setToken($_SESSION['token']->getToken());
$userobject[0]->setTokenRefresh($_SESSION['token']->getRefreshToken());
$userobject[0]->setExpiry($_SESSION['token']->getExpires());
$entityManager->flush();
//If user exists update tokens
}elseif($accessToken != null){
$userobject = new User();
$userobject->setUserName($userdata['CharacterName']);
$userobject->setUserID($userdata['CharacterID']);
$userobject->setRoles(['ROLE_USER']);
$userobject->setToken($_SESSION['token']->getToken());
$userobject->setTokenRefresh($_SESSION['token']->getRefreshToken());
$userobject->setExpiry($_SESSION['token']->getExpires());
$entityManager->persist($userobject);
$entityManager->flush();
}else{
print_r('You messed it all, go slap undo');
//TODO: Update this error with a real error
}
}catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
// Failed to get the access token or user details.
exit($e->getMessage());
}
}
return $this->redirectToRoute('page_success');
}
#[Route('/success', name: 'page_success')]
public function success()
{
return $this->render('callback.html.twig');
}
}
我的問題是,我無法確定在何處或如何測驗用戶是否已登錄或設定標志以在本地驗證用戶。
我推測如果從 SSO 成功回傳并帶有有效負載,則用戶已通過遠程主機的身份驗證,當我設法設定經過身份驗證的標志時,我可以通過測驗應該重繪 的令牌來移動以使我的身份驗證程序更安全確認它不是虛假的有效載荷 && || 餅干
我的探查器顯示用戶未通過身份驗證,并且即使呼叫 session_start() 也根本沒有活動會話;雖然我可以轉儲($_SESSION['token']); 成功
任何幫助克服這個障礙的幫助將不勝感激
配置\安全.yaml
enable_authenticator_manager: true
# https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: userID
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: app_user_provider
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#the-firewall
# https://symfony.com/doc/current/security/impersonating_user.html
# switch_user: true
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
# - { path: ^/admin, roles: ROLE_ADMIN }
# - { path: ^/profile, roles: ROLE_USER }
# - {path: ^/success, roles: ROLE_USER }
when@test:
security:
password_hashers:
# By default, password hashers are resource intensive and take time. This is
# important to generate secure password hashes. In tests however, secure hashes
# are not important, waste resources and increase test times. The following
# reduces the work factor to the lowest possible values.
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
algorithm: auto
cost: 4 # Lowest possible value for bcrypt
time_cost: 3 # Lowest possible value for argon
memory_cost: 10 # Lowest possible value for argon
物體\用戶 - 以防萬一
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
class User implements UserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 180, unique: true)]
private ?string $userID = null;
#[ORM\Column]
private array $roles = [];
#[ORM\Column(length: 255)]
private ?string $userName = null;
#[ORM\Column(length: 1000, nullable: true)]
private ?string $token = null;
#[ORM\Column(length: 255, nullable: true)]
private ?string $tokenRefresh = null;
#[ORM\Column(nullable: true)]
private ?int $expiry = null;
#[ORM\Column(length: 1000, nullable: true)]
private ?string $scopes = null;
public function getId(): ?int
{
return $this->id;
}
public function setId(?int $id): self
{
$this->id = $id;
return $this;
}
public function getUserID(): ?string
{
return $this->userID;
}
public function setUserID(string $userID): self
{
$this->userID = $userID;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->userID;
}
/**
* @deprecated since Symfony 5.3, use getUserIdentifier instead
*/
public function getUsername(): string
{
return (string) $this->userID;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* This method can be removed in Symfony 6.0 - is not needed for apps that do not check user passwords.
*
* @see PasswordAuthenticatedUserInterface
*/
public function getPassword(): ?string
{
return null;
}
/**
* This method can be removed in Symfony 6.0 - is not needed for apps that do not check user passwords.
*
* @see UserInterface
*/
public function getSalt(): ?string
{
return null;
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function setUserName(string $userName): self
{
$this->userName = $userName;
return $this;
}
public function getToken(): ?string
{
return $this->token;
}
public function setToken(?string $token): self
{
$this->token = $token;
return $this;
}
public function getTokenRefresh(): ?string
{
return $this->tokenRefresh;
}
public function setTokenRefresh(?string $tokenRefresh): self
{
$this->tokenRefresh = $tokenRefresh;
return $this;
}
public function getExpiry(): ?int
{
return $this->expiry;
}
public function setExpiry(?int $expiry): self
{
$this->expiry = $expiry;
return $this;
}
public function getScopes(): ?string
{
return $this->scopes;
}
public function setScopes(?string $scopes): self
{
$this->scopes = $scopes;
return $this;
}
}
我在 v2 中有過一些使用 symfony 防火墻的經驗,但我使用了我的站點處理的登錄表單,但現在我使用的是 6.1,一切都不同了,并且使用了完全不同型別的提供商,我不能打電話默認身份驗證器,因為我沒有使用電子郵件密碼表單。
我必須構建一個自定義身份驗證器來處理它嗎?如果是這樣的話。我的代碼并不聰明,因此不勝感激外行人的解釋。
uj5u.com熱心網友回復:
當令牌過期時,我有一個啟示。
它似乎,
Oauth2 提供程式會在幕后或幕后檢查令牌過期時間,并在令牌過期且未重繪 時默認傳遞 HTTP 狀態 (500)。
symfony 6 防火墻被完全繞過并在其他地方的代碼中處理。
我使用的任何頁面都會session_start()成為“安全”頁面。如果會話資料已過期,Oauth 提供程式將拋出未經授權的例外。
這滿足了我的身份驗證問題,因為只要我需要將頁面視為成員,我只需要啟動一個會話,如果會話無效,則重定向用戶登錄
如果我錯了,請糾正我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535537.html
上一篇:如何僅為特定用戶添加費用?
