Oauth Authentication server written in PHP-PHP source code

Source: Internet
Author: User
0

Applicable to Kohana3.x

1. [File]Oauth.zip

Oauth.zip

2. [File]Oauth. php
Class Controller_OAuth extends Controller {public function action_index () {$ result = array ('status' => '2013'); $ this-> sendQuery ($ result );} // obtain unauthorized Request Token public function action_request () {$ result = array ('status' => '20140901'); $ provider = new OAuth_Provider (); $ provider-> setRequestTokenQuery (); try {$ provider-> checkRequest (); $ token = $ provider-> generateRequestToken (); $ result ['status'] = 200; $ result = Arr: merge ($ result, $ token);} catch (Exception $ e) {$ result ['code'] = $ e-> getCode (); $ result ['message'] = $ e-> getMessage ();} $ this-> sendQuery ($ result);} // obtain the user-authorized Request Token public function action_authorize () {$ result = array ('status' => '123 '); try {$ oauth_token = Arr: get ($ _ REQUEST, 'Oss _ token'); if (! $ Oauth_token) {throw new Exception ('missing oauth_token');} $ request_token = oauth_token: findByToken ($ OAuth_Token); if (! Is_object ($ request_token) |! $ Request_token-> isRequest () {throw new Exception ('auth _ token error');} $ username = Arr: get ($ _ REQUEST, 'Username '); $ password = Arr: get ($ _ REQUEST, 'password'); if (Auth: instance ()-> login ($ username, $ password )! = TRUE) {throw new Exception ('user name or password error');} $ request_token-> setVerifier (OAuth_Provider: generateVerifier (); $ request_token-> setUserId (Auth:: instance ()-> get_user ()-> id); $ result ['status'] = 200; $ result ['message'] = 'authorization succeeded '; $ result ['callback'] = $ request_token-> getCallback (); $ result ['Oss _ token'] = $ oauth_token; $ result ['Oss _ verifier '] = $ request_token-> getVerifier ();} catch (Exc Eption $ e) {$ result ['message'] = $ e-> getMessage ();} $ this-> sendQuery ($ result );} // use the authorized Request Token in exchange for Access Toke public function action_access () {$ result = array ('status' => '2013'); // xauth $ x_auth_mode = Arr:: get ($ _ REQUEST, 'X _ auth_mode '); if ($ x_auth_mode = 'Client _ auth') {$ username = Arr: get ($ _ REQUEST, 'X _ auth_username '); $ password = Arr: get ($ _ REQUEST, 'X _ auth_password'); if (Auth :: Instance ()-> login ($ username, $ password )! = TRUE) {throw new Exception ('user name or password error');} $ userid = Auth: instance ()-> get_user () -> id; try {// Generate request token $ provider = new OAuth_Provider (); $ provider-> setRequestTokenQuery (); $ provider-> checkRequest (); $ consumer = $ provider-> getConsumer (); if ($ consumer-> getType ()! = 1) {throw new Exception ('apply for XAuth authentication');} $ token = sha1 (OAuthProvider: generateToken (20, true )); $ secret = sha1 (OAuthProvider: generateToken (20, true); $ oauth_token = ORM: factory ('oauth _ token'); $ oauth_token-> type = 2; $ oauth_token-> consumer_id = $ consumer-> getId (); $ oauth_token-> token = $ token; $ oauth_token-> token_secret = $ secret; $ oauth_token-> callback_url = ''; $ oauth_token-> user_id = $ use Rid; $ oauth_token-> verifier = ''; $ oauth_token-> save (); $ result = array ('status' => 200, 'Oss _ token' => $ token, 'Oss _ token_secret '=> $ secret);} catch (Exception $ e) {$ result ['code'] = $ e-> getCode (); $ result ['message'] = $ e-> getMessage ();} $ this-> sendQuery ($ result);} else {$ provider = new OAuth_Provider (); try {$ provider-> checkRequest (); $ token = $ provider-> generateAccessToken (); $ result ['Status'] = 200; $ result = Arr: merge ($ result, $ token);} catch (Exception $ e) {$ result ['code'] = $ e-> getCode (); $ result ['message'] = $ e-> getMessage ();} $ this-> sendQuery ($ result) ;}} public function action_test () {$ result = array ('status' => '2013 '); $ provider = new OAuth_Provider (); try {$ provider-> checkRequest (); $ userid = $ provider-> getUserId (); $ result ['status'] = 200; $ result ['message'] = ''; $ Result ['userid'] = $ userid;} catch (Exception $ e) {$ result ['message'] = $ e-> getMessage ();} $ this-> sendQuery ($ result);} // output JSON public function sendQuery ($ result, $ header = TRUE) {$ body = is_array ($ result )? Http_build_query ($ result): $ result; $ this-> sendBody ($ body);} // output public function sendBody ($ body) {$ this-> response-> body ($ body); echo $ this-> response-> send_headers ()-> body (); exit ;}}
3. [File]Provider. php
 load('oauth');$this->authentification_url = URL::base(TRUE).Arr::get($config, 'authentification_url');/* create our instance */$this->oauth = new OAuthProvider();/* setup check functions */$this->oauth->consumerHandler(array($this, 'checkConsumer'));$this->oauth->timestampNonceHandler(array($this, 'checkNonce'));$this->oauth->tokenHandler(array($this, 'checkToken'));}public function checkRequest() {$this->oauth->checkOAuthRequest();}public function setRequestTokenQuery() {$this->oauth->isRequestTokenEndpoint(true);//$this->oauth->addRequiredParameter("oauth_callback");}public function generateRequestToken() {$token = sha1(OAuthProvider::generateToken(20, true));$token_secret = sha1(OAuthProvider::generateToken(20, true));$callback = $this->oauth->callback;OAuth_Token::createRequestToken($this->consumer, $token, $token_secret, $callback);return array('authentification_url' => $this->authentification_url, 'oauth_token' => $token, 'oauth_token_secret' => $token_secret, 'oauth_callback_confirmed' => 'true');}public function generateAccesstoken() {$access_token = sha1(OAuthProvider::generateToken(20, true));$secret = sha1(OAuthProvider::generateToken(20, true));$token = OAuth_Token::findByToken($this->oauth->token);$token->changeToAccessToken($access_token, $secret);return array('oauth_token' => $access_token, 'oauth_token_secret' => $secret);}public static function generateVerifier() {$verifier = sha1(OAuthProvider::generateToken(20, true));return $verifier;}public function checkConsumer($provider) {$return = OAUTH_CONSUMER_KEY_UNKNOWN;$aConsumer = OAuth_Consumer::findByKey($provider->consumer_key);if (is_object($aConsumer)) {if (!$aConsumer->isActive()) {$return = OAUTH_CONSUMER_KEY_REFUSED;} else {$this->consumer = $aConsumer;$provider->consumer_secret = $this->consumer->getSecretKey();$return = OAUTH_OK;}}return $return;}public function checkToken($provider) {$token = OAuth_Token::findByToken($provider->token);if (is_null($token)) {return OAUTH_TOKEN_REJECTED;} elseif ($token->getType() == 1) {if ($token->getVerifier() != $provider->verifier) {return OAUTH_VERIFIER_INVALID;} else {$provider->token_secret = $token->getSecret();return OAUTH_OK;}} elseif ($token->getType() == 2) {if ($token->getExpires() > 0 && time() - strtotime($token->getCreated()) > (int)$token->getExpires()) {return OAUTH_TOKEN_EXPIRED;}$this->user_id = $token->getUserId();$provider->token_secret = $token->getSecret();return OAUTH_OK;}}public function checkNonce($provider) {if ($this->oauth->timestamp < time() - 5 * 60) {return OAUTH_BAD_TIMESTAMP;} elseif ($this->consumer->hasNonce($provider->nonce, $this->oauth->timestamp)) {return OAUTH_BAD_NONCE;} else {$this->consumer->addNonce($this->oauth->nonce);return OAUTH_OK;}}public function getUserId() {if ($this->user_id) {return $this->user_id;} else {throw new Exception("User not authentificated");}}public function getConsumer() {return $this->consumer;}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.