显示{"错误":"未经身份验证。"},同时使用ajax调用在Laravel 5.4和护照版本:v1.0.9中调用larvel API。
从路线api呼叫: Route :: get(' category / get_tree_data',' CategoryApiController @ getTreeData') - >中间件(' auth:api');
答案 0 :(得分:1)
如果您正确设置了Laravel Passport,则应在视图中显示:
您需要创建一个客户端,该客户端具有客户端ID和客户端密钥。
现在您需要打开您的消费者应用程序,其中包含您的客户端ID和您的客户端密码。
看起来像这样(您必须将令牌和ID更改为您的特定身份):
class OAuthController extends Controller
{
public function redirect()
{
$query = http_build_query([
'client_id' => 3,
'redirect_uri' => 'http://localhost/app/public/callback',
'response_type' => 'code',
'scope' => '',
]);
return redirect('http://localhost/app/public/oauth/authorize?' . $query);
}
public function callback(Request $request)
{
$http = new Client;
$response = $http->post('http://localhost/app/public/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => 3, // from admin panel above
'client_secret' => 'BcTgzw6YiwWUaU8ShX4bMTqej9ccgoA4NU8a2U9j', // from admin panel above
'redirect_uri' => 'http://localhost/app/public/callback',
'code' => $request->code // Get code from the callback
]
]);
return json_decode((string) $response->getBody(), true);
}
}
现在您需要调用该消费者应用程序并授权您的应用程序。
如果有效,您将获得访问令牌+刷新令牌。
它应该是这样的:
现在你可以使用像邮递员这样的程序来测试它。
你基本上调用你的get路由并添加访问令牌,这样你就可以访问api,如下所示:
如果您还有其他问题,建议您阅读docs。
因此,我强烈建议您观看Taylor Otwell的video。
当然,如果您有任何疑问,也可以给我一个评论。
答案 1 :(得分:0)
在public class MainActivity_Second extends android.support.v4.app.ListFragment {
View v;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
FloatingActionButton fab;
ProgressBar progressBar;
public static String TITLE = "title";
public static String TIME = "time";
public static String LIVE = "live";
public static String LANGUAGE = "language";
public static String LOCATION = "location";
//static String FLAG = "flag";
// URL Address
String url = "url_address.html";
public MainActivity_Second(){
}
//Internet connection checking
private boolean isNetworkAvailable() {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
} catch (NullPointerException e){
e.printStackTrace();
}
return Boolean.parseBoolean(null);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.activity_main_activity__second, container, false);
fab = (FloatingActionButton) v.findViewById(R.id.refresh);
setRetainInstance(true);
progressBar = (ProgressBar) v.findViewById(R.id.progressBar1);
//Hiding and show the floating button
if (isNetworkAvailable()) {
listview = (ListView) v.findViewById(android.R.id.list);
listview.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
fab.show();
}
@Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
fab.hide();
}
});
}
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isNetworkAvailable()) {
new JsoupListView().execute();
} else {
Toast.makeText(MainActivity_Second.this.getActivity(), "No internet connection. Please check the connection",
Toast.LENGTH_LONG).show();
}
}
});
// Execute DownloadJSON AsyncTask
new JsoupListView().execute();
return v;
}
@Override
public void onDestroy() {
super.onDestroy();
if (mProgressDialog != null) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
}
// Title AsyncTask
private class JsoupListView extends AsyncTask<Void, Void, Void> {
ArrayList<HashMap<String, String>> arraylist;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
//doInBackground Starts here
@Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
// Connect to the Website URL
Document doc = Jsoup.connect(url).get();
// Identify Table Class "worldpopulation"
for (Element table : doc.select("table[class=ongoingclasses]")) {
// Identify all the table row's(tr)
for (Element row : table.select("tr:gt(0)")) {
HashMap<String, String> map = new HashMap<String, String>();
// Identify all the table cell's(td)
Elements tds = row.select("td");
// Retrive Jsoup Elements
// Get the first td
map.put("title", tds.get(0).text());
// Get the second td
map.put("time", tds.get(1).text());
// Get the third td
map.put("live", tds.get(2).text());
map.put("language", tds.get(3).text());
map.put("location", tds.get(4).text());
// Set all extracted Jsoup Elements into the array
arraylist.add(map);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
try {
// Locate the listview in listview_main.xml
listview = (ListView) v.findViewById(android.R.id.list);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity_Second.this.getActivity(), arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
progressBar.setVisibility(View.GONE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
listview.setNestedScrollingEnabled(true);
}
if (isNetworkAvailable()) {
listview = (ListView) v.findViewById(android.R.id.list);
listview.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
fab.show();
}
@Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
fab.hide();
}
});
}
} catch (IndexOutOfBoundsException e) {
Toast.makeText(MainActivity_Second.this.getActivity(), "No internet connection. Please check the connection",
Toast.LENGTH_LONG).show();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
}
文件
FATAL EXCEPTION: AsyncTask #1
Process: com.aocproject.mmfahrymohammed.aocproject, PID: 6457
java.lang.RuntimeException: An error occured while executing
doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.ExceptionInInitializerError
at org.a.c.f$a.<init>(Unknown Source)
at org.a.c.f.<init>(Unknown Source)
at org.a.d.m.b(Unknown Source)
at org.a.d.m.a(Unknown Source)
at org.a.d.b.a(Unknown Source)
at org.a.d.g.a(Unknown Source)
at org.a.a.b.a(Unknown Source)
at org.a.a.c$c.e(Unknown Source)
at org.a.a.c.a(Unknown Source)
at com.aocproject.b.b$a.a(Unknown Source)
at com.aocproject.b.b$a.doInBackground(Unknown Source)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.IllegalStateException: Could not read resource entities-xhtml.properties. Make sure you copy resources for org.a.c.i
at org.a.c.i.b(Unknown Source)
at org.a.c.i.a(Unknown Source)
at org.a.c.i$b.<init>(Unknown Source)
at org.a.c.i$b.<clinit>(Unknown Source)
at org.a.c.f$a.<init>(Unknown Source)
at org.a.c.f.<init>(Unknown Source)
at org.a.d.m.b(Unknown Source)
at org.a.d.m.a(Unknown Source)
at org.a.d.b.a(Unknown Source)
at org.a.d.g.a(Unknown Source)
at org.a.a.b.a(Unknown Source)
at org.a.a.c$c.e(Unknown Source)
at org.a.a.c.a(Unknown Source)
at com.aocproject.b.b$a.a(Unknown Source)
at com.aocproject.b.b$a.doInBackground(Unknown Source)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
完美地工作......
答案 2 :(得分:0)
超出护照集成并附加CSRF标题问题。
一种可能的解决方案是将中间件定义从Route
声明移动到控制器构造函数。
这样:
Route::middleware('auth:api', 'throttle:60,1')->group(function () {
Route::get('tasks', 'Api\TasksController@index')->name('tasks');
});
然后删除auth
中间件:
Route::middleware('api', 'throttle:60,1')->group(function () {
Route::get('tasks', 'Api\TasksController@index')->name('tasks');
});
并在控制器构造函数上进行设置:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
class TasksController extends Controller
{
function __construct()
{
$this->middleware('auth');
}
public function index() { // ...
}
抱歉,我无法解释此调整的工作原理或原因。希望我稍后会更新这个以便更好地解释..
答案 3 :(得分:0)
在/api/user
中间件上调用auth:api
时,我在Laravel 5.8上也遇到了同样的问题,我尝试使用Postman调用API url,但收到了unauthenticated
消息
我可以通过将hash
文件中的false
值更改为config/auth.php
来修复它
// routes/api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
// config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false, // <-- change this to false
],
],
答案 4 :(得分:0)
我遇到了同样的问题。
就我而言,我在用户登录后缓存生成的令牌。
$token = $user->createToken('API'.'-'.strtoupper($user->username).'-'.'-X-AUTH-TOKEN', [$this->scope]);
Cache::add(strtoupper($user->username).'-'. 'X-TOKEN', $token->accessToken, $expiresAt);
调试后,尝试清除缓存
Cache::clear();
现在可以使用了。