带有Laravel的Azure Active Directory SSO

编程入门 行业动态 更新时间:2024-10-18 08:38:23
本文介绍了带有Laravel的Azure Active Directory SSO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用azure活动目录执行sso.我已经完成了天蓝色的设置,然后进行操作.我正在使用Metrogistics/laravel-azure-ad-oauth( laravel上的packagist/packages/metrogistics/laravel-azure-ad-oauth 软件包即可执行此操作.但是,当我点击url localhost:8000/login/microsoft 时,我被重定向了进入Microsoft登录页面并给出错误消息.

I'm doing sso with azure active directory. I have done the setup on azure and go the keys. I'm using metrogistics/laravel-azure-ad-oauth (packagist/packages/metrogistics/laravel-azure-ad-oauth) package on laravel to do this. However, when I hit the url localhost:8000/login/microsoft , I got redirected to microsoft login page and given an error message.

我已经在env文件中添加了以下配置,并且按照软件包的要求进行了操作.

I have added following configurations to env file and did whatever package has demanded.

AZURE_AD_CLIENT_ID = XXXXXXXXXXXXXXXXXX(这是来自Azure的应用程序ID) AZURE_AD_CLIENT_SECRET = XXXXXXXXX(在天蓝色上创建了新密钥)

AZURE_AD_CLIENT_ID=XXXXXXXXXXXXXXXXXX (this is application id from azure) AZURE_AD_CLIENT_SECRET=XXXXXXXXX (created a new key on azure)

已经两天了,我正在互联网上搜索,但找不到解决方案.我在这里想念什么?

It's been two days I'm searching the internet but could not find a solution. What is it I'm missing here?

谢谢

推荐答案

针对仍在Laravel中使用Azure Active Directory SSO的人们.并且如果您愿意使用SAML. 这是他们可以使用的仓库.

For those people who are still struggling to Azure Active Directory SSO in Laravel. And if you are willing to use SAML. Here is the repo they can use.

github/aacotroneo/laravel-saml2

使用非常简单,前提是您已在Azure门户上正确完成了SSO设置.

这是两步过程

a)转到Azure Active Directory,然后Enterprise Application

b)添加新应用程序并选择Non-gallery Application

b) Add New Application and choose Non-gallery Application

c)单击Set up single sign on,然后单击SAML框

d)编辑basic SAML configuration并添加以下内容

标识符(实体ID)- my-laravel-website/saml2/aad/metadata

答复URL(断言消费者服务URL)- my-laravel-website/saml2/aad/acs

(这些URL将从何处发出,我将在第2步中进行解释.现在,只需保存它即可.)

(From where these urls are coming, I will explain in Step 2. For now just save it.)

e)从系统上的SAML Signing Certificate部分下载Federation Metadata XML

e) Download Federation Metadata XML from SAML Signing Certificate section, on your system

f)接下来,将用户分配到您当前的SAML SSO项目.

f) Next assign users to your current SAML SSO project.

注意-如果您的帐户中没有用户,请输入.然后,您需要创建一个角色并分配一些角色(这是必需的)..

Note- If there is no user exist in your account. Then you need to create one and assign some role(it's necessary).

这是设置步骤1的教程 www.youtube/watch?v=xn_8Fm7S7y8

This is the tutorial to setup step 1 www.youtube/watch?v=xn_8Fm7S7y8

.

a)运行composer require aacotroneo/laravel-saml2

b)运行php artisan vendor:publish --provider="Aacotroneo\Saml2\Saml2ServiceProvider"

c) config/saml2_settings.php

c) config/saml2_settings.php

<?php return $settings = array( /** * Array of IDP prefixes to be configured e.g. 'idpNames' => ['test1', 'test2', 'test3'], * Separate routes will be automatically registered for each IDP specified with IDP name as prefix * Separate config file saml2/<idpName>_idp_settings.php should be added & configured accordingly */ 'idpNames' => ['aad'], /** * If 'useRoutes' is set to true, the package defines five new routes for reach entry in idpNames: * * Method | URI | Name * -------|------------------------------------|------------------ * POST | {routesPrefix}/{idpName}/acs | saml_acs * GET | {routesPrefix}/{idpName}/login | saml_login * GET | {routesPrefix}/{idpName}/logout | saml_logout * GET | {routesPrefix}/{idpName}/metadata | saml_metadata * GET | {routesPrefix}/{idpName}/sls | saml_sls */ 'useRoutes' => true, /** * Optional, leave empty if you want the defined routes to be top level, i.e. "/{idpName}/*" */ 'routesPrefix' => 'saml2', /** * which middleware group to use for the saml routes * Laravel 5.2 will need a group which includes StartSession */ 'routesMiddleware' => ['saml'], /** * Indicates how the parameters will be * retrieved from the sls request for signature validation */ 'retrieveParametersFromServer' => false, /** * Where to redirect after logout */ 'logoutRoute' => '/login', /** * Where to redirect after login if no other option was provided */ 'loginRoute' => '/dashboard', /** * Where to redirect after login if no other option was provided */ 'errorRoute' => '/login', // If 'proxyVars' is True, then the Saml lib will trust proxy headers // e.g X-Forwarded-Proto / HTTP_X_FORWARDED_PROTO. This is useful if // your application is running behind a load balancer which terminates // SSL. 'proxyVars' => true, /** * (Optional) Which class implements the route functions. * If commented out, defaults to this lib's controller (Aacotroneo\Saml2\Http\Controllers\Saml2Controller). * If you need to extend Saml2Controller (e.g. to override the `login()` function to pass * a `$returnTo` argument), this value allows you to pass your own controller, and have * it used in the routes definition. */ 'saml2_controller' => 'App\Http\Controllers\Auth\SAML2LoginController', );

注释-第1步的第 d)部分来自以下

d)创建一个新文件config/saml2/aad_idp_settings.php并将config/saml2/test_idp_settings.php的内容复制到其中.将aad_idp_settings.php中的$this_idp_env_id更改为"AAD" .因此,最终的aad_idp_settings.php将如下所示.

d) Create a new file config/saml2/aad_idp_settings.php and copy the contents of config/saml2/test_idp_settings.php into it. Change $this_idp_env_id in aad_idp_settings.php to 'AAD'. So the final aad_idp_settings.php will look like the following.

<?php // If you choose to use ENV vars to define these values, give this IdP its own env var names // so you can define different values for each IdP, all starting with 'SAML2_'.$this_idp_env_id $this_idp_env_id = 'AAD'; //This is variable is for simplesaml example only. // For real IdP, you must set the url values in the 'idp' config to conform to the IdP's real urls. $idp_host = env('SAML2_'.$this_idp_env_id.'_IDP_HOST', 'localhost:8000/simplesaml'); return $settings = array( /***** * One Login Settings */ // If 'strict' is True, then the PHP Toolkit will reject unsigned // or unencrypted messages if it expects them signed or encrypted // Also will reject the messages if not strictly follow the SAML // standard: Destination, NameId, Conditions ... are validated too. 'strict' => true, //@todo: make this depend on laravel config // Enable debug mode (to print errors) 'debug' => env('APP_DEBUG', false), // Service Provider Data that we are deploying 'sp' => array( // Specifies constraints on the name identifier to be used to // represent the requested subject. // Take a look on lib/Saml2/Constants.php to see the NameIdFormat supported 'NameIDFormat' => 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent', // Usually x509cert and privateKey of the SP are provided by files placed at // the certs folder. But we can also provide them with the following parameters 'x509cert' => env('SAML2_'.$this_idp_env_id.'_SP_x509',''), 'privateKey' => env('SAML2_'.$this_idp_env_id.'_SP_PRIVATEKEY',''), // Identifier (URI) of the SP entity. // Leave blank to use the '{idpName}_metadata' route, e.g. 'test_metadata'. 'entityId' => env('SAML2_'.$this_idp_env_id.'_SP_ENTITYID',''), // Specifies info about where and how the <AuthnResponse> message MUST be // returned to the requester, in this case our SP. 'assertionConsumerService' => array( // URL Location where the <Response> from the IdP will be returned, // using HTTP-POST binding. // Leave blank to use the '{idpName}_acs' route, e.g. 'test_acs' 'url' => '', ), // Specifies info about where and how the <Logout Response> message MUST be // returned to the requester, in this case our SP. // Remove this part to not include any URL Location in the metadata. 'singleLogoutService' => array( // URL Location where the <Response> from the IdP will be returned, // using HTTP-Redirect binding. // Leave blank to use the '{idpName}_sls' route, e.g. 'test_sls' 'url' => '', ), ), // Identity Provider Data that we want connect with our SP 'idp' => array( // Identifier of the IdP entity (must be a URI) 'entityId' => env('SAML2_'.$this_idp_env_id.'_IDP_ENTITYID', $idp_host . '/saml2/idp/metadata.php'), // SSO endpoint info of the IdP. (Authentication Request protocol) 'singleSignOnService' => array( // URL Target of the IdP where the SP will send the Authentication Request Message, // using HTTP-Redirect binding. 'url' => env('SAML2_'.$this_idp_env_id.'_IDP_SSO_URL', $idp_host . '/saml2/idp/SSOService.php'), ), // SLO endpoint info of the IdP. 'singleLogoutService' => array( // URL Location of the IdP where the SP will send the SLO Request, // using HTTP-Redirect binding. 'url' => env('SAML2_'.$this_idp_env_id.'_IDP_SL_URL', $idp_host . '/saml2/idp/SingleLogoutService.php'), ), // Public x509 certificate of the IdP 'x509cert' => env('SAML2_'.$this_idp_env_id.'_IDP_x509', 'MIID/TCCAuWgAwIBAgIJAI4R3WyjjmB1MA0GCS'), /* * Instead of use the whole x509cert you can use a fingerprint * (openssl x509 -noout -fingerprint -in "idp.crt" to generate it) */ // 'certFingerprint' => '', ), /*** * * OneLogin advanced settings * * */ // Security settings 'security' => array( /** signatures and encryptions offered */ // Indicates that the nameID of the <samlp:logoutRequest> sent by this SP // will be encrypted. 'nameIdEncrypted' => false, // Indicates whether the <samlp:AuthnRequest> messages sent by this SP // will be signed. [The Metadata of the SP will offer this info] 'authnRequestsSigned' => false, // Indicates whether the <samlp:logoutRequest> messages sent by this SP // will be signed. 'logoutRequestSigned' => false, // Indicates whether the <samlp:logoutResponse> messages sent by this SP // will be signed. 'logoutResponseSigned' => false, /* Sign the Metadata False || True (use sp certs) || array ( keyFileName => 'metadata.key', certFileName => 'metadata.crt' ) */ 'signMetadata' => false, /** signatures and encryptions required **/ // Indicates a requirement for the <samlp:Response>, <samlp:LogoutRequest> and // <samlp:LogoutResponse> elements received by this SP to be signed. 'wantMessagesSigned' => false, // Indicates a requirement for the <saml:Assertion> elements received by // this SP to be signed. [The Metadata of the SP will offer this info] 'wantAssertionsSigned' => false, // Indicates a requirement for the NameID received by // this SP to be encrypted. 'wantNameIdEncrypted' => false, // Authentication context. // Set to false and no AuthContext will be sent in the AuthNRequest, // Set true or don't present thi parameter and you will get an AuthContext 'exact' 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport' // Set an array with the possible auth context values: array ('urn:oasis:names:tc:SAML:2.0:ac:classes:Password', 'urn:oasis:names:tc:SAML:2.0:ac:classes:X509'), 'requestedAuthnContext' => true, ), // Contact information template, it is recommended to suply a technical and support contacts 'contactPerson' => array( 'technical' => array( 'givenName' => 'name', 'emailAddress' => 'no@reply' ), 'support' => array( 'givenName' => 'Support', 'emailAddress' => 'no@reply' ), ), // Organization information template, the info in en_US lang is recomended, add more if required 'organization' => array( 'en-US' => array( 'name' => 'Name', 'displayname' => 'Display Name', 'url' => 'url' ), ), /* Interoperable SAML 2.0 Web Browser SSO Profile [saml2int] saml2int/profile/current 'authnRequestsSigned' => false, // SP SHOULD NOT sign the <samlp:AuthnRequest>, // MUST NOT assume that the IdP validates the sign 'wantAssertionsSigned' => true, 'wantAssertionsEncrypted' => true, // MUST be enabled if SSL/HTTPs is disabled 'wantNameIdEncrypted' => false, */ );

e)现在,我们需要放入以下ENV变量

e) Now we need to put following ENV vars

SAML2_AAD_IDP_ENTITYID= SAML2_AAD_IDP_SSO_URL= SAML2_AAD_IDP_SL_URL= SAML2_AAD_IDP_x509=

前3个环境变量的值将来自此处.

The value of first 3 env vars will be coming from here.

最后一个Env变量将来自以下

The last Env var will come from following

f)运行php artisan make:provider SAML2ServiceProvider.这将在app/Providers/SAML2ServiceProvider.php中创建一个文件.

f) run php artisan make:provider SAML2ServiceProvider. This will create a file in app/Providers/SAML2ServiceProvider.php.

在启动方法中,粘贴以下代码段

In the boot method paste the following snippet

Event::listen('Aacotroneo\Saml2\Events\Saml2LoginEvent', function (Saml2LoginEvent $event) { $messageId = $event->getSaml2Auth()->getLastMessageId(); // Add your own code preventing reuse of a $messageId to stop replay attacks $user = $event->getSaml2User(); $userData = [ 'id' => $user->getUserId(), 'attributes' => $user->getAttributes(), 'assertion' => $user->getRawSamlAssertion() ]; $inputs = [ 'sso_user_id' => $user->getUserId(), 'username' => self::getValue($user->getAttribute('schemas.xmlsoap/ws/2005/05/identity/claims/name')), 'email' => self::getValue($user->getAttribute('schemas.xmlsoap/ws/2005/05/identity/claims/name')), 'first_name' => self::getValue($user->getAttribute('schemas.microsoft/identity/claims/displayname')), 'last_name' => self::getValue($user->getAttribute('schemas.microsoft/identity/claims/displayname')), 'password' => Hash::make('anything'), ]; $user = User::where('sso_user_id', $inputs['sso_user_id'])->where('email', $inputs['email'])->first(); if(!$user){ $res = PortalUser::store($inputs); if($res['status'] == 'success'){ $user = $res['data']; Auth::guard('web')->login($user); }else{ Log::info('SAML USER Error '.$res['messages']); } }else{ Auth::guard('web')->login($user); } });

并最终在的提供者数组中注册此提供者.

and finally register this provider in providers array of config/app.php.

.

my-laravel-website/saml2/aad/login

更多推荐

带有Laravel的Azure Active Directory SSO

本文发布于:2023-11-15 05:38:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591618.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Azure   Laravel   Active   SSO   Directory

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!