如何为ExtJS的DataGridModels Store配置Basic认证请求头?
Hey there! Let's break down how to handle Basic Authentication with your ExtJS Store.
First, a key limitation to note: JsonP proxies can't send custom HTTP headers like the Authorization header required for Basic Auth. That's because JsonP works under the hood by creating dynamic <script> tags to fetch data, and browsers don't allow setting HTTP headers for these types of requests. So we need to adjust your approach a bit to make this work.
Option 1: Switch to an Ajax Proxy (Recommended if CORS is enabled)
If your backend supports CORS (Cross-Origin Resource Sharing), switching to an ajax proxy is the cleanest solution—it lets you set the Authorization header directly. Here's how to modify your store code:
Ext.define('MyApp.store.DataGridModels', { extend: 'Ext.data.Store', alias: 'store.datagridmodels', requires: [ 'MyApp.model.DataGridModel', 'Ext.data.proxy.Ajax' // Update the required proxy type ], constructor: function(cfg) { var me = this; cfg = cfg || {}; me.callParent([Ext.apply({ storeId: 'DataGridModels', autoLoad: true, model: 'MyApp.model.DataGridModel', proxy: { type: 'ajax', // Swap jsonp for ajax proxy url: 'http://example.com/data.php', headers: { // Encode your username:password pair in Base64 'Authorization': 'Basic ' + btoa('yourUsername:yourPassword') }, reader: { type: 'json' // Add a JSON reader for the Ajax proxy } } }, cfg)]); } });
Pro tip: Never hardcode credentials in production! Pull them from secure sources like user input or environment variables, and always use HTTPS to protect the data in transit.
Option 2: Pass Credentials via URL Parameters (If JsonP is mandatory)
If you absolutely have to use JsonP (for example, your backend doesn't support CORS), you can append the encoded authentication credentials to the URL as a query parameter. Your backend will need to be set up to read this parameter and validate the auth:
Ext.define('MyApp.store.DataGridModels', { extend: 'Ext.data.Store', alias: 'store.datagridmodels', requires: [ 'MyApp.model.DataGridModel', 'Ext.data.proxy.JsonP' ], constructor: function(cfg) { var me = this; cfg = cfg || {}; me.callParent([Ext.apply({ storeId: 'DataGridModels', autoLoad: true, model: 'MyApp.model.DataGridModel', proxy: { type: 'jsonp', url: 'http://example.com/data.php', extraParams: { // Send encoded credentials as a URL parameter auth: btoa('yourUsername:yourPassword') } } }, cfg)]); } });
Important: This method is less secure because the credentials will be visible in the URL and server logs. Only use it if you have no other option, and always enforce HTTPS to minimize risk.
To wrap it up: Yes, you can implement Basic Authentication with your ExtJS Store—you just can't do it directly with a JsonP proxy. Pick the option that aligns best with your backend's capabilities.
内容的提问来源于stack exchange,提问作者Shijin TR

