AXIOS url is case sensitive - vue.js

I have worked on an Application that uses ASP.NET Core and VueJs. VueJs calls asp.net core controller using AXIOS. Everything is working fine. I was able to publish the site on IIS.
The problem starts when I type url of my web site in lower case.
The url of my web site is
http://10.131.XXX.XXX:94/MyWeb.
Internally axios calls the controller method on the same url.
for example internally in vue js component, I have written something like this
this.API_URL="http://10.131.XXX.XXX:94/MyWeb
axios.post(this.API_URL + '/UserManagement/GetAllUser', postData);
But if type the following url of my web site
http://10.131.XXX.XXX:94/myweb
then axios is not able to call the controller method and return status code 400 -Bad Request.
I am updating my question. because found a few more hint on issues.
[1] Bad Request error gone if I remove ValidateAntiForgeryToken attribute from asp.net core controller method.I add RequestVerificationToken in axios header. but If my request is to myweb this is not avaliable.
[2] My asp.net core controller calls Web API and I am using token authentication there. I keep token in Claim but that Claim is not available when i do request from axios to myweb instead of MyWeb.
Two things on web side using cookie based authentication and for web api using token authentication.
I FIGURE OUT THAT POST REQUEST IS FAILING FROM AXIOS JUST BECAUSE OF ANTIFORGERY TOKEN IN ASP.NET CORE. ALSO WHEN I LOGIN USING LOWERCASE WEBSITE NAME AUTHORIZE ATTRIBUTE REJECTS REQUEST.
I am setting correct token in axios
headers: {
'RequestVerificationToken': xshrfToken,
'Content-Type': 'application/json;charset=utf-8;'
}
so my question is that if I change the website name to lower case why POST request fails.
Any suggestion?

You could use axios interceptor as a hook:
axios.interceptors.request.use(function(response) {
response.url = response.url.toLowerCase();
return response;
});

Related

enable basic auth at api gateway

I've set up an express basic auth using the express-basic-auth module.
const basicAuthFunc = basicAuth({
challenge: true,
users: { 'admin': s.BASIC_AUTH.ADMIN_PASS }
})
it works on localhost. I'm prompted with a popup js challenge.
i'm deploying to lambda function and using AWS API gateway.
the page does not present me with the challange. I just get the 401 directly.
I tried removing the basic auth and the page loads so it's just related to the basic auth.
what headers should I add to api gateway ?
tried this one :
https://medium.com/#Da_vidgf/http-basic-auth-with-api-gateway-and-serverless-5ae14ad0a270
adding WWW-Authenticate and 'Basic' to 401 response.
didn't work

Auth0 access token to API works in postman but not when calling from Vue

I have 2 items set up in Auth0:
Application - Single Page Application
API - Custom API, machine to machine
I've followed the instruction in the link below to call the custom API:
https://auth0.com/docs/quickstart/spa/vuejs/02-calling-an-api
I've downloaded the sample with settings configured for both items mentioned above. The Vue app are able to log in correctly, and are able to call the external API by using the downloaded example codes (the external API, "backend", in the example code was written in Node JS).
However, when I change the backend to my Laravel/Lumen app which already set up for item no.2 (custom API), the Vue app received 401 unauthorized error. So, I copied the access token retrieved through Vue:
const accessToken = await this.$auth.getTokenSilently();
console.log(accessToken);
And try to call the Lumen backend with this access token - and it works perfectly fine!
Is there a setting somewhere that I might've missed to enable Vue & Lumen to work with Auth0?
p/s: The custom Lumen API was made following the instruction from:
https://auth0.com/blog/developing-restful-apis-with-lumen/
Ok it turns out I made a mistake in the axios part of the sample code. The sample is using get, while my API is using post. So I ended up sending the header in the wrong axios parameter. Hope this helps someone that encountered the same problem.

Authorization between nuxtjs and the backend API

I have a Vuejs application created using Nuxtjs. I am also using Django as the backend server, and I made an API to interact with the backend server (Django) and front-end app (Vuejs/Nuxtjs). And any API related fetch are done in the AsyncData function of the page to render the data on the server-side using axios. Also, I am using json web token authentication, and the API generates a jwt token after successful login which is stored in the cookie. So on the backend, it will always check for the request's authorization header for the token. If the request is from a logged in user (authorized token) then return authenticated json data, or else return non authenticated data.
The problem:
When the user navigates to the app, I would like to check if the user is authenticated. If the user is authenticated, render the authenticated page. If not then display non authenticated page.
My thoughts:
When the fetch is done from the App on the AsyncData function, I would check whether there is any value for the cookie. If there is then send the token with the request's authorization header. But, since the page will be rendered on the server first, and not on the client side (where the cookie actually is) it will never find the token for the authorization.
How can I check if the user is already logged in or not so that I can get authenticated and non authenticated data respectively from the API?
Update
When I successfully log in (post authorized email and password), I get a json response back with the token, which I set in the cookie like this:
this.$cookie.set('my_auth_token', this.token, {expires: 15})
How can I retrieve client side cookie and into the nuxt server for server side rendering?
Cookies are exposed in the (Express) Nuxt server through middleware.
Specifically, they can be read from the req.headers.cookie property. You can see an example implementation of this in the Nuxt documentation.
Regarding your implementation: fetching the privileged data from your API using Node would seem to be the ideal way to delegate session handling to that single service (rather than both) and provide SSR for your users.
If you've chosen to instead implement your session handling on the Django service then you'll need to "forward" your cookies by passing them into your axios request headers.
I did something similar using Firebase authentication. There is an example project on Github as well as a blog entry outlining the important files and configuration used in the application.

How to include JWT token in page navigation in ASP.NET Core

I am trying out JWT in ASP.NET Core but I am stumped on how to use it in page navigation. I have several controllers marked with Authorize attribute and I need to include the JWT in the header of the request to be able to access them.
I already am generating the token, I just don't know how I would include the token in the request header when navigating to a page marked with Authorize.
My questions are:
How do I add the token to the request so I can access the pages with Authorize upon navigation?
Are JWT tokens typically used in this fashion (page navigation), or mainly for API calls? Is it wrong to use it like this?
I need to be able to store the JWT so I can add them in the request header and I am thinking to store in cookie. Doesn't this give it the problem that cookie-based authentication have regarding CSRF?
JWT Tokes are for webservice/Rest API calls.
For MVC pages you use Cookies, typically done via ASP.NET Core Identity.
You can also use JWT from Controllers, i.e. if you call a remote api. In this case you build your request via HttpClient and SetBearerToken, like this
public async Task<IActionResult> RemoteCall()
{
string accessToken = ...;
using (var client = new HttpClient())
{
client.SetBearerToken(accessToken);
string content = await client.GetStringAsync("https://example.com/api/resource");
return Content(content);
}
}

ASP.NET Core Openiddict throws "An OpenID Connect response cannot be returned from this endpoint"

I follow instruction in openiddict server example using password flow from https://github.com/openiddict/openiddict-samples/tree/master/samples/PasswordFlow
but have no success.
It throws InvalidOperationException: An OpenID Connect response cannot be returned from this endpoint at route /connect/token:
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
Postman params:
Content-Type: application/x-www-form-urlencoded
Params: username=..&password=...&grantType=password&scope=offline_access+profile+email
I spent my day for researching but there is no information about cannot be returned from this endpoint exception. And many people can run openiddict example except me.
Here is apart of Startup.cs:
services.AddEntityFrameworkSqlite()
.AddDbContext<MisapayContext>(options =>
{
options.UseOpenIddict<int>();
});
//....
services.AddOpenIddict<int>()
.AddEntityFrameworkCoreStores<MisapayContext>()
.DisableHttpsRequirement()
.EnableTokenEndpoint("/connect/token")
.EnableLogoutEndpoint("/connect/logout")
.EnableUserinfoEndpoint("/connect/userinfo")
.UseJsonWebTokens()
.AllowPasswordFlow()
.AllowRefreshTokenFlow()
.AddEphemeralSigningKey();
services.AddMvc(config =>
{
config.Filters.Add(new ApiExceptionFilter());
}).AddJsonOptions(options =>
{
options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
});
Edited: I think problem is OpenIdConnectRequest, it can not be binded if use:
OpenIddictBuiler.AddMvcBinders()
Will throws The OpenID Connect request cannot be retrieved from the ASP.NET context.`
Otherwise, remove it, OpenIdConnectRequest in AuthorizationController can get properly. And I can get request information such as username, password grantType etc... Strange... right?
Some other information:
Asp.net Core SDK 1.1
Project.json : https://gist.github.com/trinvh/47f29468887c209716098bc4c76181a7
Startup.cs: https://gist.github.com/trinvh/75b7a12fbee754d0ea8cf251f2da9fe9
AuthorizationController.cs: https://gist.github.com/trinvh/089015b2573cae550856631e72b81374
Any help will be appreciated!
Okay, here's what's happening:
You've configured OpenIddict to use /connect/token as the token endpoint address.
The token request you send via Postman points to /connect/token/, which is actually a totally different URL (/connect/token != /connect/token/).
Since the address differs from the registered endpoint path, OpenIddict doesn't handle the request and refuses to consider it as a token request.
For some reasons, MVC accepts to handle your /connect/token/ request and invokes the Exchange action, even though the route doesn't match the requested URL.
Since you haven't registered the OpenIddict MVC binder in the MVC options, MVC uses its default binder to construct the OpenIdConnectRequest object, which allows the OpenIdConnectRequest.GrantType parameter to be resolved from the invalid grantType parameter (it wouldn't happen with the dedicated OpenIddict binder).
Your token endpoint action ends up calling SignIn to return a token response.
Under the hood, OpenIddict detects that you called SignIn outside the normal token request processing - since it didn't consider the request as a token request, due to the paths difference - and aborts this unsafe operation by throwing an InvalidOperationException.
I'll ping the MVC folks to make sure they are aware of this bug.
Edit: after some research, it looks like this behavior is "by design" and was inherited from ASP.NET MVC. I opened a feature request in the aspnet/Mvc repository to add a new way to use "strict comparison" for routes matching.