2017-03-22 51 views
1

我想爲我發展我的移動應用做的登錄認證在Angular2,ionic2,春天的安全性:「代碼」:「401」,「消息」:「全認證才能訪問該資源」

Angular2(final),rc6和ionic2,使用REST API。

我有2層的API,

一個是發送的登錄ID和密碼,

其他

是獲得成功的身份驗證的用戶的用戶詳細信息。

我爲此使用彈簧安全。

我得到一個錯誤說「代碼」:「401」,「消息」:「全認證才能訪問該資源」。

我知道有很多在此基礎上對計算器的職位,但我不能,因爲他們要麼已過時或不寫在typescript.Also所有這些職位基於單HTTP調用使用它們,但我必須打2個電話。我不知道我哪裏會出錯。我知道這應該是我的一個非常簡單的錯誤。

這是login.ts頁面,我從用戶處獲取輸入的參數。然後,我做兩個HTTP調用

  1. 要發送參數
  2. 要獲得用戶的詳細信息。

有當用戶被認證獲取生成一個「代碼」和代碼= 200。我的程序工作正常,直到這裏,但我仍然無法檢索用戶的詳細信息,因爲我得到這個錯誤。

import { Component } from '@angular/core'; 
    import { NavController, NavParams } from 'ionic-angular'; 
    import { FormBuilder, FormGroup, Validators, AbstractControl } from  '@angular/forms'; 
    import { checkFirstCharacterValidator } from '../Validators/customvalidator'; 
    import { EmailValidator } from '../Validators/emailvalidator'; 
    import { Http, Headers, Response, RequestOptions, BaseRequestOptions } from '@angular/http'; 
    import { Observable } from 'rxjs/Observable'; 


    import 'rxjs/add/operator/map'; 
    import 'rxjs/add/operator/do'; 
    import 'rxjs/add/operator/catch'; 

    declare var sha256_digest: any; 
    @Component({ 
     selector: 'page-login', 
     templateUrl: 'login.html' 
    }) 
    export class LoginPage 
    { 
     loginform : FormGroup; 
     constructor(public navCtrl: NavController, public navParams: NavParams, fb: FormBuilder,public http:Http) 
     { 
     this.loginform = fb.group 
     ({ 
      'email' : [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(40),checkFirstCharacterValidator(/^\d/), 
             EmailValidator.isValidMailFormat])], 
      'password': [null, Validators.compose([Validators.required, Validators.maxLength(25),])] 
     }) 
     } 

     private extractData(res: Response) { 
     let body = res.json(); 
     console.log(body); 
     return body || {}; 
     } 

     submitForm(value: any):void 
     { 
     console.log('Form submited!'); 
     value.password = sha256_digest(value.password); 
     console.log(value); 

      var userdata = 
      { 
      login:value.email, 
      password:value.password 
      }; 

      let headers = new Headers({'Content-Type': 'application/json'}); 
      headers.append('Authorization','Basic '); 
      let options = new RequestOptions({headers: headers}); 

      this.http.post('dummy/api/login',userdata,options).map(res=>res.json()).subscribe(resp=> 
     { 
       console.log(resp.data); 
       if(resp.code === 200) 
       { 
        return this.http.get('dummy/api/auth/registration/success',options) 
        .subscribe(resp=>{ 
        console.log(resp); 
       }); 
       } 
     }, 
     err=>{console.log(err);}, 
     ()=>{}); 

     } 

     ionViewDidLoad() { 
     console.log('ionViewDidLoad LoginPage'); 
     } 

    } 

我甚至嘗試這個版本的標題:

let headers = new Headers(); 
    headers.append("Authorization", "Basic " + btoa(userdata.login + ":" + userdata.password)); 
    headers.append("Content-Type", "application/x-www-form-urlencoded"); 

請幫我糾正這種error.These都是我從試過來源:

Spring-Security-Oauth2: Full authentication is required to access this resource

401 full authentication is required to access this resource

Angular 2 Basic Authentication not working

Angular2/Http (POST) headers

+0

嗨!你有沒有設法解決這個問題? –

+0

不,我不能。任何幫助表示讚賞。謝謝:) –

+0

我寫了一個解決方案,爲我工作。 –

回答

0

我有同樣的錯誤。除一個解決方案外,沒有任何解決方案適用於我。問題在於我從位於另一個端口的UI /客戶端訪問我的後端服務,而這並不是整個Spring(在我的情況下是微服務)設置的一部分。最後,這一切都歸結爲CORS。

下面提出的解決方案在這是越來越通過UI或其他服務從另一個端口訪問後端服務(使用Spring Security)實施。

希望它有幫助!

@Component 
@Order(Ordered.HIGHEST_PRECEDENCE) 
public class SimpleCorsFilter implements Filter { 

    Logger log = LoggerFactory.getLogger(this.getClass()); 

    @Override 
    public void init(FilterConfig fc) throws ServletException { 
    } 

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

     HttpServletResponse response = (HttpServletResponse) resp; 
     HttpServletRequest request = (HttpServletRequest) req; 
     // FIXME: this is a temp solution for CORS 
     response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200"); 
     response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 
     response.setHeader("Access-Control-Max-Age", "3600"); 
     response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN"); 

     if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { 
      response.setStatus(HttpServletResponse.SC_OK); 
     } else { 
      chain.doFilter(req, resp); 
     } 

    } 

    @Override 
    public void destroy() { 
    } 

}