1

I'm trying to do the login authentication for my mobile app which I'm developing in

Angular2 (final),rc6 and ionic2,using REST APIs.

I've 2 APIs,

one is for sending the login id and password,

the other is to get the user details of the user on successful authentication.

I'm using spring security for this purpose.

I get an error saying "code": "401","message": "Full authentication is required to access this resource".

I know there are a lot of posts on stackoverflow based on this, but I'm not able to use them since they're either deprecated or not written in typescript.Also all those posts are based on single HTTP call but I've to make 2 calls. I don't know where am I going wrong.I know this should be a very simple error on my part.

This is the login.ts page where I take the entered parameters from the user. Then I make two http calls

  1. To send the parameters
  2. To get user details.

There is a "code" that gets generated when the user is authenticated and that code=200. My program works fine till here but I'm still not able to retrieve the user details because I get this error.

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

    }

I even tried this version for headers :

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

Kindly help me rectify this error.These are all the sources I've tried from:

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

Community
  • 1
  • 1
Impromptu_Coder
  • 425
  • 3
  • 7
  • 27

1 Answers1

0

I had the same error. None of the proposed solutions worked for me, except one. The problem was that I was accessing my backend services from UI / client which was located on another port and which was not part of the whole Spring (in my case microservices) setup. In the end it all came down to CORS.

Below proposed solution has to be implemented in the backend service (with Spring Security) which is getting accessed by UI or other service from another port.

Hope it helps!

@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() {
    }

}
Deniss M.
  • 3,617
  • 17
  • 52
  • 100