授权标头不适用于角度2

时间:2017-11-01 09:59:23

标签: angular ionic-framework cors http-authentication preflight

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

    @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;
  }
}

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

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

2 个答案:

答案 0 :(得分:0)

以下是我用于登录的项目示例代码。请参考相同的登录信息。请检查Web服务中的登录功能是GET还是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

 @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);
        }
}

答案 1 :(得分:-1)

Prithivi Raj帮助解决了我的问题,但它还没有完成。 我用他的代码

@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);
        }
}

您必须创建一个实现Filter的过滤器,然后在您的Web XML add

中创建
<filter>
     <filter-name>FilterName</filter-name>
        <filter-class>FilterPackage.FilterClass</filter-class>
</filter>
<filter-mapping>
    <filter-name>FilterName</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

最后,我假设正在使用基本安全配置,因此在您的WebSecurityConfigurerAdapter中,您的configure方法应如下所示。基本上,在激活BasicAuthenticationFilter解决问题之前添加过滤器。如果你不这样做,你的登录页面使用身份验证,那么你的过滤器只会在身份验证后被调用,到那时为时已晚

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(new CorsFilter(), BasicAuthenticationFilter.class);
        http
                .authorizeRequests()
                .antMatchers("/api/login/try").access("hasRole('ROLE_USER')")
                .antMatchers("/api/vehicles/manage/update").access("hasRole('ROLE_USER')")
                .antMatchers("/api/vehicles/manage/create").access("hasRole('ROLE_USER')")
                .antMatchers("/api/proposals/create").access("hasRole('ROLE_USER')")
                .antMatchers("/api/proposals/cancel").access("hasRole('ROLE_USER')")
                .antMatchers("/api/proposals/update").access("hasRole('ROLE_USER')")
                .antMatchers("/api/proposals/accept").access("hasRole('ROLE_USER')")
                .antMatchers("/api/upload").access("hasRole('ROLE_USER')")
                .anyRequest().permitAll()
                .and()
                .csrf().disable()
                .httpBasic()
                .and()
                .logout()
                .permitAll();

    }

感谢Prithivi Raj的帮助!