Freigeben über


Requesting a Token from Access Control Service in PHP

[UPDATE 2/11: Updated to use new STS V0.9 instead of V0.8]

 

Following demonstrates requesting a token from the .NET Services Access Control Services using a Shared Secret and another using a Simple Web Token.

 

 

<?php

$stsUrl="https://[service namespace].accesscontrol.windows.net/WRAPv0.9/";

$rpUrl="[scope applies_to]";

$issuerKey="[issuer key]";

$issuerName="[issuer name]";

$claims = array("sample_in_claim_type"=>"sample_in_claim_value");

echo("<b>Shared Secret</b>: " . GetTokenBySharedSecret($stsUrl,$claims,$issuerName,$issuerKey,$rpUrl) . "<br/>");

echo("<b>Simple Web Token</b>: " . GetTokenBySimpleWebToken($stsUrl,$claims,$issuerName,$issuerKey,$rpUrl) . "<br/>");

function GetTokenBySharedSecret($stsUrl, $claimSet, $issuerName, $issuerKey, $rpUrl)

{

$claimSet["wrap_name"]=$issuerName;

$claimSet["wrap_password"]=$issuerKey;

$claimSet["wrap_scope"]=$rpUrl;

$stringResponse = MakeSTSRequest($claimSet,$stsUrl);

return ExtractTokenFromResponse($stringResponse);

}

function GetTokenBySimpleWebToken($stsUrl, $claimSet, $issuerName, $issuerKey, $rpUrl)

{

$claimSet["Issuer"]=$issuerName;

$claimSet["Audience"]=$stsUrl;

$claimSet["HMACSHA256"]=CreateSignature($claimSet,$issuerKey);

$requestSet=array();

$requestSet["wrap_assertion"]=http_build_query($claimSet);

$requestSet["wrap_assertion_format"]="SWT";

$requestSet["wrap_scope"]=$rpUrl;

$stringResponse = MakeSTSRequest($requestSet,$stsUrl);

return ExtractTokenFromResponse($stringResponse);

}

function MakeSTSRequest($claimSet, $stsUrl)

{

// encode the claimset

$tokenRequestBody=http_build_query($claimSet);

// make the request to the STS

$options = array(

"http"=>array(

"method"=>"POST",

"header"=>"Content-Type: application/x-www-form-urlencoded",

"content"=>$tokenRequestBody));

$context=stream_context_create($options);

$fp = fopen($stsUrl,'r',false,$context);

// capture the response into a string

return stream_get_contents($fp);

}

function ExtractTokenFromResponse($stringResponse)

{

parse_str($stringResponse,$Values);

return $Values["wrap_token"];

}

function CreateSignature($claimSet, $key)

{

$hmacFreeClaimSet=http_build_query($claimSet);

$key64Encoded=base64_decode($key);

return base64_encode(hash_hmac("sha256",$hmacFreeClaimSet,$key64Encoded,true));

}

?>