Angular $http post with custom headers - angularjs

I am new to angular and am from .net framework. I need to post a angular request to .net service, where it expects two custom headers from the client.
angular post command:
var request = $http(
{
url: "http://localhost:53585/api/myService/Validate",
method: "POST",
data: JSON.stringify(payload),
headers: { 'first_token': sessionService.first_token, 'second_token': sessionService.second_token }
});
But in the service side, I can see only first_token in the request header and not the second token. What I am missing here?

Issue is with my service. I figured out and restarted the IIS and then service was able to read both the headers token

I found this method in a forum, it works.
return this.http.post<any>('https://yourendpoint', { username, password }, { headers: new HttpHeaders().set('Authorizaion', 'your token')})
.pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// sto`enter code here`re user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
console.log(user);
return user;

Related

How to fetch data from a REST API by using an API-Token

I'm trying to fetch data from the Jira Rest API in my React application by using the Axios library for http requests. An API token is necessary, in order to access data via the Jira API. I generated an API token in my Jira account settings, but I can't figure out, how to include it in my http request to gain access.
This is the endpoint provided by the Jira documentation for getting an issue from the Jira board:
curl -u admin:admin http://localhost:8080/jira/rest/api/2/issue/TEST-10 | python -mjson.tool
This is the React state hook for setting the data to the fetched data:
const [jiraTicket, setJiraTicket] = useState([]);
This is the fetch function for the API request (${} will be filled with user input):
function getJiraTicket() {
axios.get(`${username}:${apiToken}#Content-Type:application/json/https:/${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`)
.then((res) => {
const data = res.data;
setJiraTicket(data);
})
}
The button inside the react component return should invoke the fetch function:
return(
<Container>
<Button onClick{getJiraTicket()}>Fetch Jira Ticket</Button>
</Container>
);
This is the error I'm currently getting, because the authorization is not working the way I did it
(I replaced the provided username, API token etc. for this example):
GET http://localhost:3000/username:apitoken#https:/sitename.atlassian.net/rest/api/2/issue/projectkey-ticketid 404 (not found)
Edit:
My current approach:
function getJiraTicket() {
axios.get(`${userName}:${apiToken}#https://${siteName}.atlassian.net/rest/api/2/issue/${projectId}-${ticketId}`,{
auth: {
username: userName,
password: apiToken,
},
withCredentials: true
})
.then((res) => {
const data = res.data;
console.log(data);
setJiraTicket(data);
})
.catch(err => {
// This error means: The request was made and the server responded with a status code
if(err.res) {
console.log(err.res.data);
console.log(err.res.status);
console.log(err.res.headers);
console.log("request was made and server responded with status");
// The request was made but no response was received
} else if (err.request) {
console.log(err.request);
console.log("request was made, but no response was received");
// Something happened in setting up the request that triggered an error
} else {
console.log("Error", err.message);
console.log("request is note set up correctly");
}
console.log(err.config);
})
Current error, which I defined accordingly to the axios doc: "request was made, but no response was received"
Endpoint that works well in Postman (Basic auth is provided in Postman):
https://sitename.atlassian.net/rest/api/2/issue/projectid-ticketid
Update: CORS access isn't allowed, when an application tries to access the Jira API endpoints directly. This restriction takes place in order to prevent random authenticated requests to the specific Jira site, because the access is based on session based authentication. However the API endpoints can be accessed, if OAuth 2.0 is used instead of Basic auth, because the application will redirect the user to the Jira auth itself via this link:
https://auth.atlassian.com/authorize? audience=api.atlassian.com&
client_id=YOUR_CLIENT_ID&
scope=REQUESTED_SCOPE_ONE%20REQUESTED_SCOPE_TWO&
redirect_uri=https://YOUR_APP_CALLBACK_URL&
state=YOUR_USER_BOUND_VALUE& response_type=code& prompt=consent
Source: https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/#known-issues
Axios uses a headers config for get/post so you should not include them in your URL. Here is a general example of how you should construct the URL and apply headers:
let axiosUrl = `https://${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`
axios({
baseURL: axiosUrl,
method: 'get',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin", "*"
},
//timeout: 2000,
auth: {
username: userName,
password: apiToken,
}
})
.then((res) => {
setJiraTicket(res.data);
})
.catch(function (error) {
console.log(error);
});

Authenticate and Authorise in Both MVC and Http AuthorizeAttribute

I get follow scenario which is working now:
MVC controller using System.Web.Mvc.AuthorizeAttribute to authenticate user is authenticated or not, it will be using cookie.
API controller using System.Web.Http.AuthorizeAttribute to authorise with bearer token.
I do also have angular http interceptor that verify and get bearer token for API purpose that can use among all angular $http request. But I am confusing how to achieve both after user has login?
This is current workflow
User click login, angular verify and store bears token in local storage.
After complete, manually trigger MVC controller so that it will get cookie for MVC authenticate.
This seem to me really double job, or I should focusing on using one AuthorizeAttribute?
You need you use Authorize key to give permission to those functions where authorization is needed. And those functions can only be accessed when authorization token is generated and passed with http request.
module.service('tokenservice', function ($http) {
this.get = function () {
var accesstoken = sessionStorage.getItem('accessToken');
var logged_in = localStorage.getItem('logged_in').toString().trim() === 'false' ? false : true;
var authHeaders = {};
if (accesstoken && logged_in) {
authHeaders.Authorization = 'Bearer ' + accesstoken;
}
return authHeaders;
};
});
module.controller('yourControllerName', function ( $http, tokenservice) {
$http({
method: "POST",
url: '/Controller/MyFucntion',
headers: tokenservice.get(),
});
});
This will help you to get generated token in user login. After that You need to work with your controller
[Authorize]
public JsonResult MyFucntion()
{
//Your logic and calculation
//return
}
Hope that will help

Why angular post does not send jsessionid to redirect_uri

I've downloaded the JWT version of the oauth2 server (https://github.com/spring-guides/tut-spring-security-and-angular-js/tree/master/oauth2) and I've been trying to replace the default login form to another using angularjs.
That I made was:
Create a request mapping for the new login form
`
#RequestMapping(value = {"/login"})
public String redirect(#RequestParam(required = false) String code, #RequestParam(required = false) String state) {
return "redirect:/#/login";
}
`
Call to the login endpoint using $http.post (XSRF-TOKEN has been injected with an interceptor):
`
var params = {username: credentials.username, password: credentials.password};
var config = {
headers: {'content-type': 'application/x-www-form-urlencoded; charset=utf-8'}
};
CoreService.httpPost('login', $httpParamSerializer(params), config)
.then( function(data) {...});
`
All looks ok, Angular send the information, the client info is obtained from our BD, the user is searched in our Data Base or LDAP. When the user is founded and the login process finish ok, the symtem redirect to the zuul server, but the jsessionid it's not present, so the Zuul server can't validate the token.
However, If I refresh the IU page, the token validation works perfectly
So, could you tell me what I have to do or what I'm doing wrong?
Thanks a lot

Token authorization - Browser throws Login form

I am working on a token implementation into Angular/.Net application. My part is the front-end. What's happening is that when UI sends a request with the expired token and the server replies with 401 I cannot intercept that before the Browser raises the Login form. As the result I cannot send a request to refresh the token. Can someone please give me an idea how that is supposed be managed? I will provide code just don't know what's to show.
Thanks
Adding code:
var response = $http({
method: "GET",
dataType: "json",
params: params,
headers: {
'Content-Type': "application/xml; charset=utf-8",
},
url: someurl
});
response = response.then(function (data) {
return data.data;
});
response.catch(function (data) {
$q.reject(data);
});
// Return the promise to the controller
return response;
The problem is that I cannot redirect on UI because Browser throws Login form before my code is hit when the server returns 401.
Make ajax request, and if you get 401 then redirect to login page.
P.s. for better understanding provide your code how you implement ajax request. Which module do you use for front-end auth? I recommend satellizer
Added:
I guess you need the following configuration on angular
var app = angular.module('App', ['satellizer'])
.config(function() {
/* your config */
}
.run(function($rootScope, $location, $auth) {
// Check auth status on each routing,
// Redirect to login page, if user is not authenticated or if token expired
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (!$auth.isAuthenticated()) {
$location.path('/auth/login');
}
});
});

AngularJs optional header param (token)

My app is using token based auth, but a guest can get data too. So for requesting data, I decided to use ngResource lib and write a factory for it.
First, the auth controller gets a token from the server and places it to localstorage. After that $place proceeds to the home page where the home controller requests data through Home factory.
My problem is that if I use guest mode and then authorize with user data, my app can't add the token header to $resource object.
After reload page everything is working properly, but I need do it without reloading. Here is my factory code
.factory('placeResource', ['$resource','$window', function($resource,$window) {
var get_token = function(){
if ($window.localStorage.token){
return 'token '+$window.localStorage.token
}
};
return $resource("/api/:resourceName/place/:placeId",
{ resourceName: '#_resourceName', placeId: '#placeId'},
{
query: {
method: 'GET',
isArray: true,
headers: { 'Authorization': get_token() }}
}
);
}]);

Resources