thinkphp5 프레임워크 API 토큰 인증 기능 [예제]
다음 튜토리얼 칼럼인 thinkphp에서는 [예제] thinkphp5 프레임워크 API 토큰 인증 기능이 필요한 친구들에게 도움이 되길 바랍니다!
사용 지침: 로그인 시 토큰과 새로 고침 토큰을 생성하고 이를 클라이언트에 반환합니다. 클라이언트는 로컬 localStorage 등을 받아 저장합니다. 각 액세스 인터페이스는 토큰을 가져오고 백엔드는 토큰이 존재하는지 확인합니다. 다음 작업은 만료된 토큰을 반환하는 것입니다. 클라이언트는 새로 고침 인터페이스를 호출하여 토큰을 전달하고 서버는 새 토큰을 재생성하여 이를 확인합니다. 클라이언트가 로컬 토큰 액세스를 새로 고치면 계속할 수 있습니다. Refresh_token 확인에 실패하면 데이터베이스 토큰, 만료 시간 및 기타 정보를 지웁니다.
간단한 토큰 생성 기능(공용 함수 파일 공통)
function create_token($id,$out_time){ return substr(md5($id.$out_time),5,26); }
인증 로그인 방법(모델)
public function checkLogin($username,$passwd){ $driver = self::field('driver_id,passwd')->where('zhanghao',$username)->whereOr('phone',$username)->find(); if (empty($driver)){ $this->error = '账号不存在'; return false; } if ($driver['passwd'] != md5($passwd)){ $this->error = "密码不正确"; return false; } //$out_time = strtotime('+ 1 days'); $out_time = strtotime('+ 1 minutes'); $token = create_token($driver['driver_id'],$out_time); if(false===self::save(['token'=>$token,'time_out'=>$out_time],['driver_id'=>$driver['driver_id']])){ $this->error = '登陆失败'; return false; } $refresh_token_out_time = strtotime('+ 5 days'); $refresh_token = create_token($driver['driver_id'],$refresh_token_out_time); Cache::set("token",$token,60); Cache::set("driver_id",$driver['driver_id'],$refresh_token_out_time);//设置ID的过期时间和更新token的token时间一样用于更新的时候获取用户信息 Cache::set('refresh_token',$refresh_token,$refresh_token_out_time); return ['token'=>$token,'refresh_token'=>$refresh_token,'in_expire'=>$out_time]; }
token 새로고침 방법(모델)
public function refreshToken($refresh_token,$token){ if (!isset(Cache::get('refresh_token')) or Cache::get('refresh_token')!=$refresh_token){ $this->error = '刷新token失败'; return false; } $cache_driver_id = Cache::get('driver_id'); $driver = self::field('driver_id,passwd')->where('driver_id',$cache_driver_id)->where('token',$token)->find(); if (empty($driver)){ $this->error = '参数错误'; return false; } $out_time = strtotime('+ 1 days');//新的过期时间 $token = create_token($driver['driver_id'],$out_time);//更新token if(false===self::save(['token'=>$token,'time_out'=>$out_time],['driver_id'=>$driver['driver_id']])){ Cache::clear($token); $this->error = '刷新失败'; return false; } Cache::set("token",$token,864000); return ['token'=>$token,'in_expire'=>$out_time]; }
종료 방법(모델)
public function logout($token,$refresh_token=''){ $driver = self::field('driver_id,passwd')->where('token',$token)->find(); self::save(['token'=>'','time_out'=>''],['token'=>$token]); Cache::clear('token'); Cache::clear('refresh_token'); }
위 내용은 thinkphp5 프레임워크 API 토큰 인증 기능 [예제]의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Pagoda에 thinkphp5를 배포할 때 보고된 오류에 대한 해결 방법: 1. Pagoda 서버를 열고 php pathinfo 확장을 설치하고 활성화합니다. 2. "RewriteRule ^(.*)$ index.php 콘텐츠로 ".access" 파일을 구성합니다. ?s=/$1 [QSA ,PT,L]”; 3. 웹사이트 관리에서 thinkphp의 pseudo-static을 활성화하면 됩니다.

thinkphp5 URL 재작성이 작동하지 않는 해결 방법: 1. mod_rewrite.so 모듈이 httpd.conf 구성 파일에 로드되었는지 확인합니다. 2. AllowOverride None에서 None을 All로 변경합니다. 3. Apache 구성 파일 .htaccess를 "RewriteRule ^ (.*)$ index.php [L,E=PATH_INFO:$1]" 하고 저장하세요.

요청된 URL을 얻는 thinkphp5의 방법: 1. 현재 URL 정보를 얻기 위해 "\think\Request" 클래스의 "$request = Request::instance();" 방법을 사용합니다. 도메인 이름을 포함한 전체 URL 주소를 얻으려면 "$request-> url()" 함수를 사용하세요.

thinkphp5 제목 표시줄 아이콘을 제거하는 방법: 1. thinkphp5 프레임워크 공개에서 favicon.ico 파일을 찾습니다. 2. 파일을 삭제하거나 다른 사진을 선택하여 이름을 favicon.ico로 바꾸고 원본 favicon.ico 파일을 대체합니다.

thinkphp5 게시물은 TP5가 strpos 함수를 사용하여 헤더의 콘텐츠 유형 값에서 app/json 문자열을 찾기 때문에 값을 얻을 수 없습니다. 해결 방법은 헤더의 콘텐츠 유형 값을 app/json으로 설정하는 것입니다.

컨트롤러가 존재하지 않는다고 메시지를 표시하는 thinkphp5에 대한 해결 방법: 1. 해당 컨트롤러의 네임스페이스가 올바르게 작성되었는지 확인하고 올바른 네임스페이스로 변경합니다. 2. 해당 tp 파일을 열고 클래스 이름을 수정합니다.

ThinkPHP5에서 어제의 데이터를 쿼리하는 방법: 1. ThinkPHP5 관련 파일을 엽니다. 2. "db('table')->whereTime('c_time', 'yesterday')->select();" 표현식을 통해 어제의 데이터를 쿼리할 수 있습니다. .

thinkphp5에서 오류 프롬프트를 설정하는 방법: 1. 프로젝트 루트 디렉터리에 있는 public 폴더를 입력하고 index.php 항목 파일을 엽니다. 2. 디버그 모드 스위치에 대한 설명을 봅니다. 3. "APP_DEBUG" 상수 값을 조정합니다. 오류 메시지 프롬프트를 표시하려면 true로 설정합니다.
