I currently have a very simple rest api, wich allows user authentication through basic security. My angular client receives email and password from a login input, and gets the user from the server. email and password are sent in the http headers. The problem is, when my securityfilter (JAX-rs java, jersey backend impl) i get that my auth headers are empty.
Am i sending them empty from angular??
getSecuredUser(email: string, password: string){
let headers: Headers = new Headers();
headers.append("Authorization", "Basic " + email + ":" + password);
headers.append("'Access-Control-Allow-Origin': '*' ", "application/x-www-form-urlencoded");
return this.http.get(DEFAULT_PATH + 'users/' + email, headers).subscribe(
(data: Response) => {
var result = data.json();
return result;
}
);
}
your problem is the headers for the basic auth.
getSecuredUser(email: string, password: string){
let headers: Headers = new Headers();
headers.append("Authorization", "Basic " + btoa(`${email}:${password}`);
headers.append("'Access-Control-Allow-Origin': '*' ", "application/x-www-form-urlencoded");
return this.http.get(DEFAULT_PATH + 'users/' + email, {headers: headers}).subscribe(
(data: Response) => {
var result = data.json();
return result;
}
);
}
Related
I'm struggling to find the solution to my problem with ionic native http.
I tried the answer to this post, but still i am getting the same error
this is my code
switchToggle(){
let url = 'https://io.adafruit.com//api/v2/myusername/feeds/my-feed-id/data/';
const headers = new Headers();
headers.set("Content-Type", "application/json")
headers.set("X-AIO-Key", "PASTED_MY_KEY_HERE");
let data = {
"datum":{
"value" : 1
}
};
this.http.setDataSerializer('json');
this.http.post(url,data,{headers:headers})
.then(data => {
console.log(data);
}).catch(error => {
console.log(error)
});
}
and this is the error I am getting
when I try other post request without headers it is working fine. But for this specific API I need to send the request together with the headers.
set your header like this =>
setHeaders() {
let headers = new Headers();
headers.append("X-AIO-Key", "PASTED_MY_KEY_HERE");
headers.append('Content-Type', 'application/json' );
const requestOptions = new RequestOptions({ headers: headers });
return requestOptions;
}
switchToggle(): Observable<any>{
let data = {
"datum":{
"value" : 1
}
};
return this.http.post(url, data, this.setHeaders())
.map(Response => Response.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
I have angular app version 6 and I'm trying to integrate Azure AD authentication and the micro services are in AWS.
Surprisingly I'm getting same code for access_token and id_token.
are they supposed to be different? my architect thinks so and asked me to tweak library to send responseType as 'id_token+token'.
What am I doing wrong and is there any way I can get access_token for sending as headers for api calls?
I have also attached the screenshot of the console errors of api c
microsoftadal-api fails
alls.
Below is my piece of code where I was trying to read access token for authenticating api calls.
enter code here
export class AppComponent {
loading: boolean;
constructor(private adalSvc: MsAdalAngular6Service, private router: Router,
private http: HttpClient) {
this.adalSvc.acquireToken('https://api.test.test.com/Dev')
.subscribe((resToken: string) => {
console.log(this.adalSvc.userInfo);
console.log('get resToken -->', resToken);
console.log('get oid -->', this.adalSvc.userInfo.profile.oid);
console.log('get accessToken -->', this.adalSvc.accessToken);
localStorage.setItem('accessToken', this.adalSvc.accessToken);
console.log('get token -->', this.adalSvc[enter image description here][1]
.getToken('https://api.test.test.com/test?userId=111111'));
this.configureRoutes();
this.loading = true;
this.http.get('https://api.test.test.com/test?userId=11111', {
headers: {
'Authorization': 'Bearer ' + this.adalSvc.accessToken,
'userid': this.adalSvc.userInfo.profile.oid,
'username': 'username',
'userrole': 'somerole'
}
}).subscribe(console.log);
this.postCall();
},
error => {
console.log(error);
});
}
postCall() {
const data = {
'dealerId': '111111'
};
const headers = new Headers();
headers.append('Authorization', 'Bearer ' + this.adalSvc.accessToken);
headers.append('userid', this.adalSvc.userInfo.profile.oid);
headers.append('username', 'username');
headers.append('userrole', 'somerole');
return this.http.post(
'https://api.test.test.com/test', data, {
headers: {
'Authorization': 'Bearer ' + this.adalSvc.accessToken,
'userid': this.adalSvc.userInfo.profile.oid,
'username': 'username',
'userrole': 'somerole'
}
}).subscribe((response: Response) => {
console.log(response.json());
});
}
configureRoutes() {
this.router.navigate(['/dealer/home']);
}
}
Make sure that you have specified the right resource.
It's the id_token and not the access_token that you need to send to your backend APIs. Then you can get the access_token from the id_token.
It looks like you might be making the same mistake that the user here made.
I have integrated passport-jwt for authentication purpose. It's working like charm but whenever Frontend guy use it from frontend angular 2 its giving Unauthorised 401 . I've tried alot but not getting any clue, it must be a silly mistake though.
my passport strategy file is as
let JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
//let fromHeader = require('passport-jwt').fromHeader
// load up the user model
const User = require('../components/user/model');
const database = require('./database'); // get db config file
const config = require('./config'); // get db config file
module.exports = function(passport) {
//var passportStrategy = function(passport){
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
//opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("JWT");
console.log("opts.jwtFromRequest==",opts.jwtFromRequest);
opts.secretOrKey = config.secret;//config.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
//console.log("opt==",JSON.stringify(opt));
//console.log("jwt_payload===",jwt_payload);
User.findOne({_id: jwt_payload._doc._id}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
};
my route is as
app.get("/api/user/getAll",
passport.authenticate('jwt',{session:false}),
userController.fetchUsers
);
And frontend header append is as follows :
logoutUser(token) {
//const userData = JSON.stringify(userInfo);
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', token); //e.g.token = JWT dasddddasdsda
//headers.append('Authentication', token);
console.log(headers)
return this.http.post('http://localhost:9000/api/user/logout', { headers: headers })
.map((response: Response) =〉 {
return response.json()
})
.catch(this.errorHandler);
}
It would really great if anyone can assist me further to identify the mistake.
Second argument for the post method is payload.
so this code below
this.http.post('http://localhost:9000/api/user/logout', { headers: headers })
has to be
this.http.post('http://localhost:9000/api/user/logout', {}, { headers: headers })
My http call is returning 200 but no response is captured. My code inside subscribe is not being hit. The API is returning data when I test in postman. Here is my code.
getToken(authcode: string) {
var data = 'client_id=InspectWebApp_client&code=' + authcode + '&redirect_uri=http://localhost:3000&grant_type=authorization_code';
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
this.http.post('https://fedloginqa.test.com/as/token.oauth2', data, options)
.subscribe((res: Response) => {
var resultsToken = res.json();
localStorage.setItem("access_token",resultsToken.access_token)
//return this.inspections;
})
}
I was also facing the same problem. The problem was solved using the map function on Observables. Here is my implementation:
login(Username:string, Password:string) : Observable<Response>{
let headers = new Headers();
headers.append("Authorization", "Basic " + btoa(Username + ":" + Password));
headers.append("Content-Type", "application/x-www-form-urlencoded");
return this._http.post(this._baseUrl+"auth/login", " " , {headers: headers} )
.map((response: Response) => {
return response;
}).catch(this.handleError);
}
Here the handleError is a function to catch the excceptions generated. This is a function in login.service.ts that sends the username and password to the api to get data. You can see that I am returning response from the map function in this service. Now, this returned response can be caught in subscribe function in following way:
this._loginService.login(this.username, this.password)
.subscribe(
(response) => {
//Here you can map the response to a type.
this.apiResult = <IUser>response.json();
},
(err) => {
//Here you can catch the error
},
() => {this.router.navigate(['home'])}
);
I have a button redirect to this function
loginGoogle() {
this.cordovaOauthG.login().then((success) => {
console.log("Google Login DONE ");
if (success != null) {
console.log(JSON.stringify(success));
//alert(success.access_token);
if (success.access_token != null && success.access_token != '') {
var params = "google_id=" + success.access_token;
// var token = success.access_token;
// this.postLoginGoogle(params);
this.tesLogin();
}
}
}, (error) => {
alert(error);
});
}
and this is the function for http request
tesLogin(){
// var params = "google_id="+gid;
var params = "google_id="+'ya29.Ci_4ApeVHCD7av30Y82JRZPLG4T9ZUgmU1SNLUGIlVV_ufAcCoBc4ILqsY6Ah55i-g';
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
console.log(params);
this.http.post(Config.base_url + 'api/user-account/login-google', params, {headers: headers})
.map(res => res.json()).subscribe(data => {
console.log(data);
if (data.success) {
this.local.set('access_token', data.message);
this.menu.enable(true);
this.nav.setRoot(HomePage);
}
else {
this.doAlert("Incorrect email or password");
}
});
}
My problem is, whenever I tried to call using success.access_token, it doesnt work
but If I am calling the request without any parameters(just throwing in some random strings) then it works
I tried to debug it using mobile inspector from chrome, either way it is returning a error like this (working post & not working post both returning error)
EXCEPTION: SyntaxError: Unexpected token < in JSON at position 1
I suggest to send the authentication token in the header not in the parameters. Something like that:
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', 'Bearer ' + authToken);