Token based auth for aspnet-core web api - asp.net

Dears,
I've followed https://stormpath.com/blog/token-authentication-asp-net-core
to authenticate the user for my web apis
I managed to create a successful access-token when calling api/token
My problem is the use of [Authorize], authorize filter didn't get that my user has a valid token, although HeaderAuthorization and HeaderExpries have been set.
function getValues()
{
$.ajax({
url: "http://localhost:48146/api/values",
headers: { 'Authorization': 'Basic ' + accessToken, Expires: tokenExpires },
method: "GET",
context: document.body,
success: function (data) {
alert(data);
}
});
}
Did I passed a wrong header?

Based on the tutorial you followed you should pass a bearer authorization header, not a basic authorization header:
headers: { 'Authorization': 'bearer' + accessToken, Expires: tokenExpires },

I've figured out 2 problems
as #user1336 said in header I had theaders: { 'Authorization': 'bearer' + accessToken, Expires: tokenExpires },
I had to call ConfigureAuth(app) before app.UseMvc(); in Startup.css

Related

How to implement Wordpress Application Password Authentication in Javascript async fetch?

I'm trying to setup a website using Wordpress as Headless CMS, using the built-in REST API. Using NuxtJS to fetch the data. Now I want to restrict API access so I enabled/created Wordpress Application Password Authentication.
However, I can not seem to find detailed information on how the URL should be assembled with authentication parameters to fetch data from API endpoint.
Credentials have to be added to the URL that's being fetched?
async asyncData ({ $config: { apiUrl, apiUser, apiPassword } }) {
try {
const products = await (await fetch(`${apiUrl}/producten`)).json()
return {
products
}
}
catch (error) {
console.log(error)
}
},
apiUrl, apiUser, apiPassword are currently in nuxtjs.config.js, under publicRuntimeConfig. But 1) they should come in privateRuntimeConfig?
And 2) getting following as return (which is the correct response from the WP Rest API, because I need to pass auth-credentials somewhere, somehow...)
{ "code": "rest_not_logged_in", "message": "You are not currently logged in.", "data": { "status": 401 } }
Solved by adding options to fetch;
const fetchHeaderOptions = {
cache: 'no-cache',
method: 'GET',
credentials: 'omit', //To instead ensure browsers don't include credentials in the request
mode: 'no-cors',
headers: {
'Authorization': 'Basic ' + encode(`${apiUser}` + ":" + `${apiPassword}`),
'Content-Type': 'application/json; charset=UTF-8; application/x-www-form-urlencoded',
},
}
const products = await (await fetch(`${apiUrl}/products`, fetchHeaderOptions)).json()

Using firebase RestApi to signup users using email and password

I'm creating a project where users need to able to log in to their account and see some data. I'm creating a windows application with unity, so from what I understood from researching, I have to use the firebase RestAPI, not the SDK. I managed to use the realTime database but I'm struggling with the authentication side of things.
I followed this tutorial and used the documentation for signing up users into firebase with the RestAPI. I keep getting a 400 (Bad Request) error. I found this post, where the solution was to use a strong password, but that didn't work.
Since I'm using a not so reliable unity c# package as a client, I tested my code with nodeJs as well. Same error.
My code:
C#
private void SignUpUser(string email, string username, string password)
{
string userData = "{\"email\":\"" + email + "\",\"password\":\"" + password + "\",\"returnSecureToken\":true}";
// Content type is json by default
RestClient.Post<SignResponse>("https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=" + AuthKey, userData).Then(
response =>
{
Debug.Log("Success");
}).Catch(error =>
{
Debug.Log(error);
});
}
Javascript
const axios = require("axios");
axios
.post(
'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=' + API_KEY,
{
email: "myEmddail#example",
password: "superStrongzi344##",
returnSecureToken: true,
},
{
'Content-Type': 'application/json',
}
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Part of response:
response:
{ status: 400,
statusText: 'Bad Request',
headers:
{ expires: 'Mon, 01 Jan 1990 00:00:00 GMT',
pragma: 'no-cache',
date: 'Sun, 10 May 2020 21:09:52 GMT',
'cache-control': 'no-cache, no-store, max-age=0, must-revalidate',
vary: 'X-Origin, Referer, Origin,Accept-Encoding',
'content-type': 'application/json; charset=UTF-8',
server: 'ESF',
'x-xss-protection': '0',
'x-frame-options': 'SAMEORIGIN',
'x-content-type-options': 'nosniff',
'alt-svc':
'h3-27=":443"; ma=2592000,h3-25=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"', 'accept-ranges': 'none',
connection: 'close',
'transfer-encoding': 'chunked' },
config:
{ url:
'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=API_KEY',
method: 'post',
data:
'{"email":"myEmddail#example","password":"superStrongzi344##","returnSecureToken":true}',
Is there anything I'm missing?
Thanks
Try enabling registering with e-mail in your firebase console. Also the c# library you're using doesn't seem very reliable and might not be well suited for error handling, I would suggest the native System.net.http library that's built in. An example of a request:
using System.Net.Http;
private static readonly HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();

Get token to call post to firebase database in react-native

I have a firebase database and i need to do a classic post call, but i have a problem with token.
For example, in firebase for get user i use app().auth().currentUser.uid,
for a classic get list i use app().firestore().collection('prizes') and it work.
so, to get user token i do app().auth().currentUser.getIdToken()
and for post i do
export function postData(endpoint: string, data: any, token) {
return fetchJson(ENDPOINT_API + endpoint}, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token ? token : USER_TOKEN}`,
},
})
}
and result is
{"error":"Token invalid","message":"Cannot destructure property type of 'undefined' or 'null'."}
the token comes back to me, but I don't know if it's the correct way
This line:
Authorization: `Bearer ${token ? token : USER_TOKEN}`,
Replace it by:
'Authorization': `Bearer ${token ? token : USER_TOKEN}`,

Verify domain of cloud function for webhook

How can I setup a webhook for the google calendar api?
I'm currently making a post to the api, stating the webhook/ address https://us-central1-pushmessage-bd1eb.cloudfunctions.net/getUsers
axios({
method: "POST",
url:
"https://www.googleapis.com/calendar/v3/calendars/xxx/events/watch",
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json;charset=UTF-8",
Authorization: token.token_type + " " + token.access_token,
"Content-Type": "application/json"
},
data: {
id: "tester",
type: "web_hook",
address: "https://xxx.cloudfunctions.net/getUsers"
}
})
However, I get the error:
code: 401,
message: 'Unauthorized WebHook callback channel: https://us-central1-xxx.cloudfunctions.net/getUsers' }
How can I verify the domain of my cloud function?
I have tried this method but still get the 401:
How to perform domain verification for Firebase functions

Meteor PayPal Payments (using Meteor.http)

Edit: I've fixed my original problem and have shown a metor example in my answer.
I'm getting a error 500 when trying to get the token for my PayPal API app in Meteor:
token = EJSON.stringify(Meteor.http.call "POST", "https://api.sandbox.paypal.com/v1/oauth2/token",
headers:
"Accept": "application/json"
"Accept-Language": "en_US"
auth: "user:pass"
params:
"grant_type":"client_credentials"
);
console.log("Token: "+token);
Output of this code:
Token: {"statusCode":500,"headers":{"server":"Apache-Coyote/1.1","date":"Fri, 15 Mar 2013 05:04:43 GMT","content-length":"0","connection":"close"},"data":null,"error":{}}
Obviously PayPal is returning a error 500 to me. I can't figure out what may be causing this. Of course Auth is actual data, not user:pass.
Why am I getting error 500?
Edit: Compiled Javascript
var token;
token = EJSON.stringify(Meteor.http.call("POST", "https://api.sandbox.paypal.com/v1/oauth2/token", {
headers: {
"Accept": "application/json",
"Accept-Language": "en_US"
},
auth: "user:pass",
params: {
"grant_type": "client_credentials"
}
}));
console.log("Token: " + token);
Here's an example implementation to make paypal API calls with meteor.
In the startup of your program, fetch your token. Always replace clientid and clientsecret with your own.
token = EJSON.parse(Meteor.http.post("https://api.sandbox.paypal.com/v1/oauth2/token",
headers:
"Accept": "application/json"
"Accept-Language":"en_US"
auth: "clientid:clientsecret"
params:
"grant_type":"client_credentials"
#encoding: "base64"
).content).access_token;
Now, create a payment, shown here in a Meteor.methods method (and returning a URL for the client to go to):
buySingleItem: () ->
console.log "Starting new payment, user id: "+Meteor.userId()
result = Meteor.http.post("https://api.sandbox.paypal.com/v1/payments/payment",
headers:
"Authorization":"Bearer "+token
"Content-Type": "application/json"
data:
{
"intent":"sale"
"redirect_urls":
"return_url":"http://mysite.herokuapp.com/done",
"cancel_url":"http://mysite.herokuapp.com/cancel"
"payer":
"payment_method":"paypal"
"transactions":[
{
"amount":
"total":"3.00",
"currency":"USD"
"description":"My item description."
}
]
}
)
payment = result.data
console.log "PayPal redirect: "+payment.links[1].href
return payment.links[1].href
This will create a PayPal checkout style payment, within Meteor.
I would provide sample code, but I'm not familiar with Meteor.
Basically you have 2 issues here:
in your headers, you are not passing the client id or client secret. This should look like:
Authorization: Basic clientid:clientsecret
Also, in your request, your request should look like this:
response_type=token&grant_type=client_credentials
Looks like your in json then stringifying it, so whatever way you need to get the POST request I just put up there, once you get it, you should be good.
[edit]PayPal's doc's dont have you base64 encode the client id or secret[/edit]
Then, when you need to execute the payment you can do as below. See the whole payment process here.
Meteor.methods
'executePaypalPayment': (payerId) ->
payment = PaypalPayments.findOne({ userId: #userId },
{ sort: { 'create_time': -1 } })
token = Meteor.call 'getPaypalToken'
url = 'https://api.sandbox.paypal.com/v1/payments/payment/' +
payment.id + '/execute'
res = Meteor.http.post url,
headers:
Authorization: 'Bearer ' + token.access_token
'Content-Type': 'application/json'
data:
payer_id: payerId
payment = res.data
payment['userId'] = #userId
if payment.state is 'approved'
# we insert the sucessful payment here
PaypalPayments.insert payment
return if payment.state is 'approved' then true else false

Resources