简体   繁体   中英

401 Unauthorized Error Angular 5

obtainAccessToken(loginData){
        let params=new URLSearchParams();
        params.append('grant_type','password');
        params.append('username',loginData.username);
        params.append('password',loginData.password);
        params.append('client_id','myid');
        console.log(params.toString());
        let headers = new Headers();
        headers.append('content_type','application/x-www-form-urlencoded');
        headers.append('Authorization','Basic '+btoa("myid:mypaasword"));
        console.log(headers)
        let options=new RequestOptions({headers:headers});
        console.log(options);
        this._http.post('...../oauth/token',params.toString(),options)
            .pipe(map(res=>res.json(),err=>console.log(err)))
            .subscribe(
                data=>this.saveToken(data),
                err=>alert('Invalid Credials')
            );
        }

I always get 401 Unauthorized error when sending post request to get access to my spring app enter image description here

It doesn't come from Spring. It's a Browser security. I suppose your spring server is on another port than your frontend server (or another IP ?).

The browser doesn't allow to do ajax requests to another port/IP (for security reasons). It's called CORS : https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

On the server side, you must add headers to your HttpServletResponse to explicit allow your client domain to request your server.

Add cors plugin to your browser

firefox--> https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/

chrome--> https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

Switch off plugin and again switch on it.

If it works then problem is with your rest api. add @crossorigin() in your controller Follow this links: https://howtodoinjava.com/spring5/webmvc/spring-mvc-cors-configuration/ https://spring.io/guides/gs/rest-service-cors/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM