1. 程式人生 > >框架中的RESTful api快速領悟(中):token認證

框架中的RESTful api快速領悟(中):token認證

我們講一下RESTful api中很重要的環節—token認證。本課程主要演示如何快速藉助YII2配置出簡單的token認證方法,並給出擴充套件的思路
1.建立一個用來作許可權驗證的表

CREATE TABLE `clients` (
  `client_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `client_appid` varchar(255) NOT NULL DEFAULT '',
  `client_appkey` varchar(255) NOT NULL DEFAULT '',
  `client_token`
varchar(255) DEFAULT NULL, PRIMARY KEY (`client_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;

然後需要建立一個Clients模型,以備後用:

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Clients extends ActiveRecord
{
    //指定表名稱
    static public function tableName()
    {
        return 'clients'
; } }
<?php

namespace app\controllers;

use yii\filters\auth\QueryParamAuth;
use yii\rest\ActiveController;
use yii\web\Response;


class UserController extends ActiveController
{
    public $modelClass = 'app\models\Users';

    public function init()
    {
        parent::init();
        //關掉csrf
$this->enableCsrfValidation = false; //關掉session \Yii::$app->user->enableSession = false; } public function behaviors() { $behaviors = parent::behaviors(); //設定響應格式 $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON; //授權認證 $behaviors['authenticator'] = [ 'class' => QueryParamAuth::className(), //我們使用的是QueryParamAuth ]; return $behaviors; } }

主要是initbehaviors那2句。

3.設定整個專案的驗證
config/web.php

        'user' => [
//            'identityClass' => 'app\models\User',
//            'enableAutoLogin' => true,
            'identityClass' => 'app\models\Clients', //驗證的時候呼叫這個類
        ],

4.完善Clients模型

<?php
<?php

namespace app\models;

use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

class Clients extends ActiveRecord implements identityInterface
{
    //指定表名稱
    static public function tableName()
    {
        return 'clients';
    }

    /**
     * Finds an identity by the given ID.
     * @param string|integer $id the ID to be looked for
     * @return IdentityInterface the identity object that matches the given ID.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentity($id)
    {
        // TODO: Implement findIdentity() method.
    }

    /**
     * Finds an identity by the given token.
     * @param mixed $token the token to be looked for
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
     * @return IdentityInterface the identity object that matches the given token.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        // TODO: Implement findIdentityByAccessToken() method.
        return self::findOne(['client_token'=>$token]);
    }

    /**
     * Returns an ID that can uniquely identify a user identity.
     * @return string|integer an ID that uniquely identifies a user identity.
     */
    public function getId()
    {
        // TODO: Implement getId() method.
    }

    /**
     * Returns a key that can be used to check the validity of a given identity ID.
     *
     * The key should be unique for each individual user, and should be persistent
     * so that it can be used to check the validity of the user identity.
     *
     * The space of such keys should be big enough to defeat potential identity attacks.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @return string a key that is used to check the validity of a given identity ID.
     * @see validateAuthKey()
     */
    public function getAuthKey()
    {
        // TODO: Implement getAuthKey() method.
    }

    /**
     * Validates the given auth key.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @param string $authKey the given auth key
     * @return boolean whether the given auth key is valid.
     * @see getAuthKey()
     */
    public function validateAuthKey($authKey)
    {
        // TODO: Implement validateAuthKey() method.
    }
}
{"name":"Unauthorized","message":"Your request was made with invalid credentials.","code":0,"status":401,"type":"yii\\web\\UnauthorizedHttpException"}

沒有訪問許可權了

相關推薦

框架RESTful api快速領悟():token認證

我們講一下RESTful api中很重要的環節—token認證。本課程主要演示如何快速藉助YII2配置出簡單的token認證方法,並給出擴充套件的思路 1.建立一個用來作許可權驗證的表 CREATE TABLE `clients` ( `cl

【實踐筆記】Spring MVCRestful API使用 Swagger2 構建

1、Swagger2是什麼? Swagger 是一款RESTFUL介面的文件線上自動生成+功能測試功能軟體。 Swagger 是一個規範和完整的框架,用於生成、描述、呼叫和視覺化 RESTful 風格的 Web 服務。總體目標是使客戶端和檔案系統作為伺服器以同樣的速度來更新。檔案的方法,引數和模型緊密

[CI] 使用CodeIgniter框架搭建RESTful API服務

解釋 valid 源碼 stat target 面向服務 prot 多次 1.0 在2011年8月的時候,我寫了一篇博客《使用CodeIgniter框架搭建RESTful API服務》,介紹了RESTful的設計概念,以及使用CodeIgniter框架實現RESTful

Flask框架開發RESTful API

web框架選擇 Django,流行但是笨重,還麻煩,人生苦短,肯定不選 web.py,輕量,但據說作者仙逝無人維護,好吧,先pass tornado,據說倡導自己造輪子,雖然是facebook開源的吧,但聽到這個,就算了吧 flask,輕量,流行,可以自己定義 安裝flask

Go實戰--通過gin-gonic框架搭建restful api服務(github.com/gin-gonic/gin)

users .post sage 事先 eat mas routes pac 操作mysql 生命不止,繼續 go go go !!! 先插播一條廣告,給你堅持學習golang的理由: 《2017 軟件開發薪酬調查:Go 和 Scala 是最賺錢的語言》 言歸正傳!

Go實戰--通過httprouter和redis框架搭建restful api服務(github.com/julienschmidt/httprouter)

生命不止,繼續 go go go !!! httprouter HttpRouter is a lightweight high performance HTTP request router (also called multiplexer or ju

flask框架RESTful API的請求及返回引數探索

先提一下RESTful API設計原則GET 用來獲取資源POST 用來新建資源(也可以用於更新資源)PUT 用來更新資源DELETE 用來刪除資源在一個註冊到RESTful API的物件中,可以通過特定的成員函式來匹配對應的http請求方法,程式碼如下:class User

如何快速地在java使用Restful API

什麼是Restful API?REST(英文:Representational State Transfer,簡稱REST),它是一種軟體架構風格、設計風格,而不是標準,只是提供了一組設計原則和約束條件。它主要用於客戶端和伺服器互動類的軟體。基於這個風格設計的軟體可以更簡潔,

3.Spring Boot使用Swagger2構建強大的RESTful API文檔

pack 效果 type 現象 業務邏輯 blank depend imp any 原文:http://www.jianshu.com/p/8033ef83a8ed 由於Spring Boot能夠快速開發、便捷部署等特性,相信有很大一部分Spring Boot的用戶會用來構

Yii2框架RESTful API教程(一) - 快速入門

比較 exp values cnblogs -- restful extends .cn pat 前不久做一個項目,是用Yii2框架寫一套RESTful風格的API,就去查了下《Yii 2.0 權威指南 》,發現上面寫得比較簡略。所以就在這裏寫一篇教程貼,希望幫助剛接觸Yi

SSM框架RESTful風格的實現

層次 article delet 註解 服務器 ppi ble req variable REST這個詞,是Roy Thomas Fielding在他2000年的博士論文中提出的。 如果一個架構符合REST原則,就稱它為RESTful架構。 REST,即Representa

Spring Boot使用Swagger2構建強大的RESTful API文檔

TP app 接口 ear tro 參數 stc 業務邏輯 schema 由於Spring Boot能夠快速開發、便捷部署等特性,相信有很大一部分Spring Boot的用戶會用來構建RESTful API。而我們構建RESTful API的目的通常都是由於多終端的原因,這

使用Swagger2構建SpringMVC項目Restful API文檔

部署 success 直接 資源 路徑 ng- extends 信息 org 使用Swagger自動生成API文檔,不僅增加了項目的可維護性,還提高了API的透明度更利於快速測試等工作,便於更快地發現和解決問題。 本篇文章只記錄整合過程,關於Security Configu

springMvcrestful風格的api路徑把小數點當參數,SpringMvcurl有小數點

pub springmvc line name object ews mapping html 兩種 在springMvc web項目中restful風格的api路徑中有小數點會被過濾後臺拿不到最後一個小數點的問題, 有兩種解決方案:

Java架構-SOAspringmvcrestful服務動態重新整理token資訊

因為要考慮服務端token的動態重新整理,而且還要單獨啟動定時排程任務去重新整理token資訊,保證token的時效及安全問題,直接分享動態重新整理token的程式碼: Java程式碼 我這邊會將近期研發的spring cloud微服務雲架構的搭建過程和精髓記

SpringBoot使用Restful API

現在前後端分離這麼流行,後端採用Restful API來設計也是大勢所趨吧。下面介紹一下在Spring boot中使用RestFul API的基本方式吧。 PS:不去說什麼是Restful服務,只是說說它在程式碼中的實際使用。 首先,定義兩個model: 其一:User實體類

springMvcrestful風格的api路徑把小數點當引數

在springMvc web專案中restful風格的api路徑中有小數點會被過濾後臺拿不到最後一個小數點的問題, 有兩種解決方案: 1:在api路徑中加入:.+ @RequestMapping("/findByIp/{ip:.+}") public Object t

SpringCloud工作筆記048---RESTful API HTTP 狀態碼的定義_以及把RESTFul版本號_放到http協議header_以及RestFul設計時的兩個誤區

------------------------- RESTful架構有一些典型的設計誤區。 最常見的一種設計錯誤,就是URI包含動詞。因為"資源"表示一種實體,所以應該是名詞,URI不應該有動詞,動詞應該放在HTTP協議中。 舉例來說,某個URI是/posts/s

Spring Boot使用Swagger2構建強大的RESTful API文件【轉】

由於Spring Boot能夠快速開發、便捷部署等特性,相信有很大一部分Spring Boot的使用者會用來構建RESTful API。而我們構建RESTful API的目的通常都是由於多終端的原因,這些終端會共用很多底層業務邏輯,因此我們會抽象出這樣一層來同時服務於多個移動端或者Web前端。

Spring Boot 使用 Swagger2 構建 RESTFUL API 文件

由於Spring Boot能夠快速開發、便捷部署等特性,相信有很大一部分Spring Boot的使用者會用來構建RESTful API。而我們構建RESTful API的目的通常都是由於多終端的原因,這些終端會共用很多底層業務邏輯,因此我們會抽象出這樣一層來同時服務於多個移動端或者Web前端。