简体   繁体   中英

How can I use this code for ntlm sso in laravel?

<?php
$headers = apache_request_headers();
if (!isset($headers['Authorization'])){
  header('HTTP/1.1 401 Unauthorized');
  header('WWW-Authenticate: NTLM');
  exit;
}
$auth = $headers['Authorization'];
if (substr($auth,0,5) == 'NTLM ') {
  $msg = base64_decode(substr($auth, 5));
  if (substr($msg, 0, 8) != "NTLMSSP\x00")
    die('error header not recognised');
  if ($msg[8] == "\x01") {
    $msg2 = "NTLMSSP\x00\x02\x00\x00\x00".
        "\x00\x00\x00\x00". // target name len/alloc
      "\x00\x00\x00\x00". // target name offset
      "\x01\x02\x81\x00". // flags
      "\x00\x00\x00\x00\x00\x00\x00\x00". // challenge
      "\x00\x00\x00\x00\x00\x00\x00\x00". // context
      "\x00\x00\x00\x00\x00\x00\x00\x00"; // target info len/alloc/offset
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: NTLM '.trim(base64_encode($msg2)));
    exit;
  }
  else if ($msg[8] == "\x03") {
    function get_msg_str($msg, $start, $unicode = true) {
      $len = (ord($msg[$start+1]) * 256) + ord($msg[$start]);
      $off = (ord($msg[$start+5]) * 256) + ord($msg[$start+4]);
      if ($unicode)
        return str_replace("\0", '', substr($msg, $off, $len));
      else
        return substr($msg, $off, $len);
    }
    $user = get_msg_str($msg, 36);
    $domain = get_msg_str($msg, 28);
    $workstation = get_msg_str($msg, 44);
    // print "You are $user from $domain/$workstation";
    print "$user";
  }
}

When I use this code I have response - user Login and I need to catch it and try to authorize with userLogin, I already use ldap auth in my site and I need just use this login for auth.

But I have a problem, when I use this code if I am not in domain and try to use header request I have alert modal what trying to ask me about login. How to do right?

You'll need to configure a Middleware to validate requests on NTLM network.

On my company we have the Employee table with field 'matricula', same value used to login on windows.

So, I replaced App\User Model for App\Employee and put 'matricula' field as ID in my case, but you can use App\User with ID

Step 1: Configure route Middleware

File app\Http\Kernel.php add at array $routeMiddleware value

protected $routeMiddleware = [
...
'ntlm' => \App\Http\Middleware\NTLMAuth::class,
]

Step 2: Create a Middleware file

Create a Middleware file at 'app\Http\Middleware\NTLMAuth'. (Laravel 5.7)

   //app\Http\Middleware\NTLMAuth.php

<?php

    namespace App\Http\Middleware;

    use Closure;
    use Illuminate\Support\Facades\Auth;

    class NTLMAuth
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */

        public function handle($request, Closure $next)
        {

            $auth = $request->header("Authorization");
            $user = ' ';

            if ($auth == null || strlen($auth) < 4 ){
                header('HTTP/1.1 401 Unauthorized');
                header('WWW-Authenticate: NTLM');
                exit;
            }

            if (substr($auth,0,5) == 'NTLM ') {

              $msg = base64_decode(substr($auth, 5));

              if (substr($msg, 0, 8) != "NTLMSSP\x00"){
                    header('HTTP/1.1 401 Unauthorized');
                    header('WWW-Authenticate: NTLM');
                    exit;
              }

              if ($msg[8] == "\x01") {

                  $msg2 = "NTLMSSP\x00\x02\x00\x00\x00".
                      "\x00\x00\x00\x00". // target name len/alloc
                      "\x00\x00\x00\x00". // target name offset
                      "\x01\x02\x81\x00". // flags
                      "\x00\x00\x00\x00\x00\x00\x00\x00". // challenge
                      "\x00\x00\x00\x00\x00\x00\x00\x00". // context
                      "\x00\x00\x00\x00\x00\x00\x00\x00"; // target info len/alloc/offset

                    header('HTTP/1.1 401 Unauthorized');
                    header('WWW-Authenticate: NTLM '.trim(base64_encode($msg2)));
                    exit;

              }else if ($msg[8] == "\x03") {

                  function get_msg_str($msg, $start, $unicode = true) {
                      $len = (ord($msg[$start+1]) * 256) + ord($msg[$start]);
                      $off = (ord($msg[$start+5]) * 256) + ord($msg[$start+4]);
                      if ($unicode)
                          return str_replace("\0", '', substr($msg, $off, $len));
                      else
                          return substr($msg, $off, $len);
                  }

                    $user = get_msg_str($msg, 36);
                    $domain = get_msg_str($msg, 28);
                    $workstation = get_msg_str($msg, 44);
              }

              $employee = \App\Model\Employee::where('matricula', $user)->first();

              if( $employee != null ){
                Auth::loginUsingId( $employee->matricula );
              }

              $user = ( Auth::check() )? Auth::user()->nome : 'Not Found';

              $request->attributes->set('user', $user);

              return $next($request);

            }
        }
    }

Basically, I extract the user on NTLM, search on Employee table and set in Auth::loginUsingId

$employee = \App\Model\Employee::where('matricula', $user)->first();
Auth::loginUsingId( $employee->matricula );

After configured you can use on controllers

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Employee;
use Auth;

class HomeController extends Controller
{

    public function __construct()
    {
        $this->middleware('ntlm');
    }

    public function index()
    {
        return view('home');
    }

    public function welcome()
    {
        $employees = Employee::take(5)->get();
        return view('welcome', compact('employees') );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM