授权标头不适用于角度2 [英] Authorization header not working for angular 2

查看:155
本文介绍了授权标头不适用于角度2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在使用带有Angular的Ionic 2框架,我想使用授权标头发出http请求,但似乎它没有发送标头。我做错了什么?

Hello I am using the Ionic 2 framework with Angular and I want to make a http request with the authorization header but it appears it is not sending the header. What have I done wrong?

    @Injectable()
export class UserServiceProvider {
  private loginSuccess: any;
  constructor(public http: Http) {
    console.log('Hello UserServiceProvider Provider');
  }

  login(username, password)
  {
     var token = btoa(username + ':' + password);
     alert(token);
     this.loginSuccess = false;
     let headers = new Headers();
     headers.append('Authorization', 'Basic ' + token);
     this.http.get('http://localhost:8080/HelloWorld/api/login/try', {
         headers: headers
     })
     .subscribe(function success(response) {
        this.loginSuccess = true;
     }, function error(response) {
        this.loginSuccess = false;
     });

     return this.loginSuccess;
  }
}

以下是浏览器控制台中的响应

Here is the response in the browser console

polyfills.js:3 OPTIONS http://localhost:8080/HelloWorld/api/login/try 401 ()
s @ polyfills.js:3
t.scheduleTask @ polyfills.js:3
onScheduleTask @ polyfills.js:3
t.scheduleTask @ polyfills.js:3
r.scheduleTask @ polyfills.js:3
r.scheduleMacroTask @ polyfills.js:3
(anonymous) @ polyfills.js:3
o.(anonymous function) @ polyfills.js:2
(anonymous) @ http.es5.js:1275
Observable._trySubscribe @ Observable.js:171
Observable.subscribe @ Observable.js:159
webpackJsonp.197.UserServiceProvider.login @ user-service.ts:29
webpackJsonp.196.AccountPage.login @ account.ts:21
(anonymous) @ AccountPage.html:25
handleEvent @ core.es5.js:12022
callWithDebugContext @ core.es5.js:13486
debugHandleEvent @ core.es5.js:13074
dispatchEvent @ core.es5.js:8615
(anonymous) @ core.es5.js:9226
(anonymous) @ platform-browser.es5.js:2651
t.invokeTask @ polyfills.js:3
onInvokeTask @ core.es5.js:3881
t.invokeTask @ polyfills.js:3
r.runTask @ polyfills.js:3
e.invokeTask @ polyfills.js:3
p @ polyfills.js:2
v @ polyfills.js:2




(index):1无法加载
http:// localhost:8080 / HelloWorld / api / login / try :预检的响应
有无效的HTTP状态代码401

(index):1 Failed to load http://localhost:8080/HelloWorld/api/login/try: Response for preflight has invalid HTTP status code 401


推荐答案

以下是我项目的示例代码,我是用于登录。请参考相同的登录信息。请检查Web服务中的登录功能是GET还是POST。

Below is the sample code of my project which I am using for login. Please refer the same for login. please check whether the login function in web service is GET or POST.

public postOAuthRequest(login:Login):Promise<any> {
    // Parameters obj-

    let params:URLSearchParams = new URLSearchParams();
    let headersvar = new Headers();

    params.set('username', login.userId.toString());
    params.set('password', login.password.toString());
    params.set('grant_type', 'password');
    params.set('scope', 'read write');
    params.set('client_secret', '123456');
    params.set('client_id', 'prithivi');
    var authdata = 'Basic ' + btoa('clientapp' + ':' + '412589');

    headersvar.append('accept', 'application/json');
    headersvar.append('Authorization', authdata);

    let requestOption:RequestOptionsArgs = {
        search: params,
        headers: headersvar,
        body: JSON.stringify({clientapp: 412589})
    };


    return this.http
        .post(OauthUrl, JSON.stringify({clientapp: 412589}), requestOption)
        .toPromise()
        .then(this.extractData)
}

在Web服务中添加CORS过滤器方法克服CORS问题。下面的代码是在JAVA中

Add a CORS filter method in web service to overcome CORS issue. Below code is in JAVA

 @Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT,DELETE");
        response.setHeader("Access-Control-Max-Age", "3628800");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, X-XSRF-TOKEN");
        if (!"OPTIONS".equals(request.getMethod())) {
            chain.doFilter(req, res);
        } else {
            response.setStatus(200);
        }
}

这篇关于授权标头不适用于角度2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆