我正在使用DRF作为API服务在Ionic 2中开发应用程序。出于身份验证的目的,我正在使用JWT。我正在为每个请求发送身份验证令牌constructor() { super(); if ( window ) { window.mychatwidget = this; } }
。在Postman中,API工作正常。
现在,当我在浏览器中对它进行测试时,它无法正常工作,我发现它可能无法正常工作,因为JWT身份验证令牌未在Authorization: jwt [token]
请求中作为飞行前发送。那么我该如何解决这个问题。
答案 0 :(得分:0)
在CORS预检OPTIONS响应中,Cross-Origin-Allow-Headers应该与请求的匹配。
@Component
@Order(value = Integer.MIN_VALUE)
public class JsonToUrlEncodedAuthenticationFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
if (Objects.equals(request.getContentType(), "application/json") && Objects.equals(((RequestFacade) request).getServletPath(), "/oauth/token")) {
InputStream is = request.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] json = buffer.toByteArray();
HashMap<String, String> result = new ObjectMapper().readValue(json, HashMap.class);
HashMap<String, String[]> r = new HashMap<>();
for (String key : result.keySet()) {
String[] val = new String[1];
val[0] = result.get(key);
r.put(key, val);
}
String[] val = new String[1];
val[0] = ((RequestFacade) request).getMethod();
r.put("_method", val);
HttpServletRequest s = new MyServletRequestWrapper(((HttpServletRequest) request), r);
chain.doFilter(s, response);
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
}
答案 1 :(得分:0)
如果你使用ionic serve
commnad,那么在Ionic最新版本中你必须使用Proxies来防止预检和CORS问题,
首先在ionic.config.json
文件中添加API路径和网址,如
{
"name": "APP-NAME",
"app_id": "",
"proxies": [
{
"path": "/api",
"proxyUrl": "http://example.com/api"
}
]
}
现在,在从http
调用您的API时,请使用/api
网址而不是http://example.com/api
,
....
this.http.post('/api', data, {headers:headers}).map(res=>res.json()).subscribe(data=>{
console.log(data)
}, err=>{
console.log("Error!:", err.json());
});
....
完成上述更改后,您必须重新运行命令ionic serve
。
但是,如果您遇到问题,请参考Handling CORS Issues In Ionic和https://ionicframework.com/docs/cli/configuring.html
答案 2 :(得分:0)
实际上问题是OPTIONS
api在没有授权令牌的情况下无法读取,因此我们为readonly
和GET api添加了OPTIONS
Auth级别。