Enabling WebAPI CORS for Angular 2 authentification - asp.net-web-api

I've seen a few answers on stackoverflow and I'm lost.
I have webapi 2 + standalone angular 2
webapi project is from template. the only thing i've changed is that i added CORS
and following line to IdentityConfig.cs > ApplicationUserManager Create()
context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost:3000" });
here I've all standard from template:
[Authorize]
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
On the client side I have function to get access token, that works properly:
authenticate(loginInfo: Login): boolean {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post(this.baseUrl + 'Token', 'grant_type=password&username=alice2#example.com&password=Password2!',
{
headers: headers
})
.subscribe(
data => this.saveAuthToken(<AccessToken>(data.json())),
err => this.handleError(err),
() => console.log('authentication Complete')
);
return true;
}
And get function, that works ok without authentication (commented code) :
get(url: string) {
var jwt = sessionStorage.getItem(this.idTokenName);
var authHeader = new Headers();
if (jwt) {
authHeader.append('Authorization', 'Bearer ' + jwt);
}
return this.http.get(this.apiUrl + url, {
headers: authHeader
})
.map(res => res.json())
.catch(this.handleError);
//return this.http.get(this.apiUrl + url)
// .map(res => res.json())
// .catch(this.handleError);
}
But when i try to add Authorization header server returns:
XMLHttpRequest cannot load http://localhost:3868/api/values. Response for preflight has invalid HTTP status code 405
How to allow user to authenticate through Angular properly?

Install-Package Microsoft.Owin.Cors
Add to App_Start > Startup.Auth.cs > ConfigureAuth(IAppBuilder app)
app.UseCors(CorsOptions.AllowAll);
Only one line. That's all.

You could explicitly add the needed headers and methods:
context.Response.Headers.Add(
"Access-Control-Allow-Headers",
new[] { "Content-Type, Authorization" }
);
context.Response.Headers.Add(
"Access-Control-Allow-Methods",
new[] { "GET, POST, OPTIONS" }
);

I had to add the following to the globalasax.cs:
protected void Application_BeginRequest()
{
var req = HttpContext.Current.Request;
var res = HttpContext.Current.Response;
var val = res.Headers.GetValues("Access-Control-Allow-Origin");
if (val == null)
{
if (!req.Url.ToString().ToLower().Contains("token") || (req.Url.ToString().ToLower().Contains("token") && req.HttpMethod == "OPTIONS"))
{
res.AppendHeader("Access-Control-Allow-Origin", "http://localhost:4200");
}
}
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
res.AppendHeader("Access-Control-Allow-Credentials", "true");
res.AppendHeader("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name");
res.AppendHeader("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");
res.StatusCode = 200;
res.End();
}
}

When talking to webapi angular and using a http post that either contains non-standard body contents (i.e json) or authentication then a pre-flight request is set that basically says 'am i okay to send the actual request'. Now there are several ways around this that essentially involve short cuts - use IE (if the server is on the same machine as IE ignores the port when deciding what the same machine is) or open CORS up to permit all (which is dangerous as the granting permission to an authenticated user opens your system up to all manner of hacks).
Anyway the solution we used was to add a method to the Globals.asax.cs on the server
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
var origin = HttpContext.Current.Request.Headers["Origin"];
Response.Headers.Add("Access-Control-Allow-Origin", origin);
Response.Headers.Add("Access-Control-Allow-Headers", "content-type, withcredentials, Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
Response.Headers.Add("Access-Control-Allow-Credentials", "true");
Response.Headers.Add("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT, DELETE");
Response.Flush();
}
}
Now the above is checking for the pre-flight very specifically and if it finds it it adds permissions to send the next request. On your system you may need to tweek the Allow_Headers request (easiest way is to use your browser f12 to look at what headers your pre-flight request is actually sending out.
Note that the above just deals with the pre-flight CORS will still apply for the actual http POST which will need correctly handling. For this we added the server we wanted to allow in to settings and then added the System.Web.Http.Cors to the WebApiConfig Register method as follows
var cors = new EnableCorsAttribute(Properties.Settings.Default.CORSOriginPermittedSite, "*", "GET, HEAD, OPTIONS, POST, PUT, DELETE");
cors.SupportsCredentials = true;
config.EnableCors(cors);
This avoids hard coding the site which a production system really wants to avoid.
Anyway hopefully that will help.

Related

NuxtJs Page Redirection With Backend

I am building a website that include payment option with NuxtJs. But I am getting CORS error when i want to rediect to payment page of virtual POS integrator.
On backend side I am using Golang/Echo like this:
func startPaymentProcess(c echo.Context) {
header := c.Response().Header()
header.Add("Access-Control-Allow-Origin", "*")
header.Add("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
header.Add("Access-Control-Allow-Headers", "Content-Type, Authorization")
//...
// do some controls
//..
c.Redirect(http.StatusSeeOther, "https://web-test.vercel.app/workplace/payment/success")
}
On frontend axios call like this
export const SetSubscription = async () => {
try {
return await axios({
method: "GET",
url: API_URL + `/workplaces/payment-test`,
headers: {
"Authorization": shared.getAuthorizationHeader()
}
});
} catch (error) {
return error
}
}
On developer console error like this:
Access to XMLHttpRequest at 'https://web-test.vercel.app/workplace/payment/success' (redirected from 'https://api.test.domain.tech/workplaces/payment-test') from origin 'https://web-test.vercel.app' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
688030a.js:2
GET https://web-test.vercel.app/workplace/subscription/success net::ERR_FAILED
On developer console network error like this:
enter image description here
Which point that I'm missing?
Try adding withCredentials: true to the axios request's options

Ionic HTTP request POST (works on postman) not working but GET works

I was working with localhost and my IONIC app is almost done until I decided to host it on 000webhost. I uploaded my Laravel API which is very basic (I used CORS middleware) then when I tested the app, the GET request works but POST and PUT doesn't.
Notes:
The URL is 100% correct because I'm using it on GET method
Data 100% compatible because I test it on Postman and it works
This.http is the http service:
this.http.getData().subscribe(s => {
console.log('Get Works');
this.data = s[0];
this.http.postData(this.data).subscribe(inf => {
console.log('Post works');
}, err => {
console.log(err)
console.log('Post dont work');
})
})
the http service
postData(data: any) {
let headers: HttpHeaders = new HttpHeaders();
headers.append("Access-Control-Allow-Origin", '*');
headers.append("Access-Control-Allow-Methods", 'POST, GET, OPTIONS, DELETE');
headers.append("Access-Control-Allow-Headers", '*');
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json,text/plain');
let requestOptions = { headers: headers }
return this.http.post(url, data)}
getData() {
let headers: HttpHeaders = new HttpHeaders();
headers.append("Access-Control-Allow-Origin", '*');
headers.append("Access-Control-Allow-Methods", 'POST, GET, OPTIONS, DELETE');
headers.append("Access-Control-Allow-Headers", '*');
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json,text/plain');
let requestOptions = { headers: headers }
return this.http.get(url, requestOptions)}
1
console
solution :
for some reason it works on localhost but not in 000webhost ...
it doesn't accept body/row request maybe changing the 'content-type' will make it work thought
however my solution is using HttpParams from angular :
postData(data: any) {
let headers: HttpHeaders = new HttpHeaders();
headers.append("Access-Control-Allow-Origin", '*');
headers.append("Access-Control-Allow-Methods", 'POST, GET, OPTIONS, DELETE');
headers.append("Access-Control-Allow-Headers", '*');
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json,text/plain');
const params = new HttpParams()
.set('type', data.type)
.set('email', data.email)
.set('uid', data.uid)
.set('lat', data.lat)
.set('lng', data.lng)
.set('city', data.city)
.set('municipality', data.municipality)
.set('subject', data.subject)
.set('description', data.description)
.set('image', data.image)
.set('upvote', data.upvote)
let requestOptions = { headers: headers, params: params }
return this.http.post(url, null, requestOptions)
}
return this.http
.post(url, data, { headers })

Adding multiple headers to graphql client (apollo-boost)

const client = new ApolloClient({
uri,
onError: (e: any) => {
console.log('error: ', e); // Failed to fetch
console.log(e.operation.getContext()); // it does show it has x-abc-id
},
request: operation => {
const headers: { [x: string]: string } = {};
const accessToken = AuthService.getUser()?.accessToken;
const activeClientId = UserService.getActiveClientId();
headers['x-abc-id'] = activeClientId;
if (accessToken) headers['Authorization'] = `Bearer ${accessToken}`;
operation.setContext({ headers });
}
});
The problem here is when i just add Authorization header it makes the POST call and shows the expected error.
But when i add x-abc-id header which is also expected by backend it only makes OPTIONS call (no post call)
P.S. On postman adding both headers works completely fine.
Found what the issue was, thought to share if it help.
Postman does not perform OPTIONS call before sending request to backend.
In OPTIONS call, 👇represents what client call contains: [authorization, content-type, x-abc-id]
BUT what does server expects: 👇
Just authorization, content-type
So it's a calls headers mismatch (nothing related to Apollo).
x-abc-id header explicitly has to be allowed in CORS configuration on backend.
Thanks to Pooria Atarzadeh

How to set authorization header in vue.js

I'm making an axios post call with the JWT token generated after successful login. For all the requests I need to attach JWT token in header and in the back-end which is developed on spring -boot I have logic to get the token from header and validate it.
From the browser, first the OPTIONS request goes to back-end where it gives me 403 error and in the back-end If I sysout headers, I can't find the header name X-XSRF-TOKEN
axios.post("http://localhost:8004/api/v1/auth", { "username": "test", "password" : "test"})
.then((response) => {
let token = response.data.token;
axios.defaults.headers.common["X-XSRF-TOKEN"] = token;
axios.post("http://localhost:8004/api/v1/getdata", {"action" : "dashboard"})
.then((response) => {
console.log(response.data);
}, (error) => {
console.log(error);
})
}, (error) => {
console.log(error);
})
Spring boot part
#Controller
#CrossOrigin(origins = "*", allowedHeaders = "*")
#RequestMapping(path = "/api/v1")
public class ApplicationController {
#PostMapping(path = "/getdata")
#ResponseBody
public SessionData getData(#RequestBody ProfileRequest profileRequest) {
try {
return profileService.getData(profileRequest);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Setting Authorization Header is not something to do with vue, but it
is something to do with axios.
axios.post("http://localhost:8004/api/v1/getdata", {"action" : "dashboard"}, {
headers: {
Authorization: 'Bearer ' + token,
}
})
When you get the auth token you can configure the axios instance with:
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
common means applying the header to every subsequent request, while you can also use other HTTP verb names if you want to apply a header to only one request type:
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
You will find more info in https://github.com/axios/axios#config-defaults
...
axios.post('http://localhost:8004/api/v1/auth',
{ "username": "test", "password" : "test"}, {headers: { X-XSRF-TOKEN: `${token}`}})
...
the issue might not be axios but the cors policy set by spring security.
If you are using spring security check out this answer
I had the same issue, that answer helped solve my problem.

Angular POST request's header is null

I am developing an Ionic 3 Mobile Application, I have problem with Angular's POST method.
In login page, I created a form and tried send data to server with Angular HTTP POST method. But in server (.NET WEB API) I see request's header is null.
Here is the Angular side codes;
login(username, password):Observable<Object>{
let url : string = this.apiUrl+"/login";
let headers = new HttpHeaders();
headers.append('Authorization', btoa(username+":"+password).toString());
return this.http.post(url,JSON.stringify({username,password}), {headers: headers});
}
Here is the .NET side codes for controller;
[EnableCors(origins: "http://localhost:8100", headers: "*", methods: "*")]
public Response Post()
{
return _mobileUserService.Login();
}
Here is the part of .NET side codes for catch request;
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
try
{
var token = request.Headers.GetValues("Authorization").FirstOrDefault();
}
catch (Exception ex)
{
}
return base.SendAsync(request, cancellationToken);
}
When request catched by .NET (in running), I see these values for "request" variable;
request = {Method: POST, RequestUri: 'http://localhost:41582/api/login', Version: 1.1, Content: System.Web.Http.WebHost.HttpControllerHandler+LazyStreamContent, Headers:
{
Connection: keep-alive
Accept: application/json
Accept: text/plain
Accept: */*
...
In normally, request's url is localhost:8100, so I think server accepted CORS
How can I solve that?
In Web api you have to tell which method is post or get based on how you have setup your route.
[EnableCors(origins: "http://localhost:8100", headers: "*", methods: "*")]
[HttpPost] // Decorate post this attribute in your controller
public Response Post()
{
return _mobileUserService.Login();
}

Resources