Login authentication using token error Access-Control-Allow-Origin' - asp.net-mvc

userAuthentication(userName, password) {
let headers = new Headers();
var data = "username=" + userName + "&password=" + password + "&grant_type=password";
// var reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-urlencoded','No-Auth':'True' });
headers.append('Content-Type', 'application/x-www-urlencoded');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('No-Auth','True');
headers.append('Access-Control-Allow-Methods', 'GET, POST, PUT');
return this.http.post(environment.apiUrl + 'token', data, { headers: headers })
.pipe(map(data => data.json()),
catchError((error: any) => {
throw error;
}));
}
}
I am using angular on client side and asp.net mvc on server side.I an facing an error Access-Control-Allow-Origin

The Error you got is because you don't have required permissions to access API
add this line inside your API code
you have to install cors first
Install-Package Microsoft.AspNet.WebApi.Cors
after add this line inside your API
config.EnableCors();
"config" refers to httpconfiguration class
you will now able to access your API

Related

Unable to get auth token from twitter

I am trying to get auth token from twitter api https://api.twitter.com/oauth2/token but getting 403 forbidden issue.
My credentials(API Key and API Secret key) are right and verified.
I tried that on postman by converting online my credentials in base64.
this.twitterTokenURL = "https://api.twitter.com/oauth2/token";
var combined = encodeURIComponent(this.consumerKey) + ":" + encodeURIComponent(this.consumerSecret);
base64Encoded = btoa(combined);
// Get the token
this.http.post(this.twitterTokenURL, { 'Authorization': 'Basic ' + base64Encoded, 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }, "grant_type=client_credentials").
map(res => res.json()).subscribe((data) => {
this.authorization = data;
console.log(data);
if (data && data.token_type && data.token_type === "bearer") {
//resolve(data)
}
resolve(this.data);
})

Spring Security and Angular 5

Right now I'm sending username and password through header from my angular 5 app after successful login to access spring rest api. After Successful I'm getting unique sessionId from spring in response can I use that ID instead of credentials to authenticate
angular code
let d=localStorage.getItem('currentUser');
let headers = new Headers();
var user=JSON.parse(d);
headers.append('Accept', 'application/json');
// creating base64 encoded String from user name and password
var base64Credential: string = btoa(user.principal.username+ ':' + user.principal.password);
headers.append("Authorization", "Basic " + base64Credential);
let options = new RequestOptions({ headers: headers
});
var self = this;
self.greeting = {id:'', content:''};
http.get(this.url,options).map(response => self.greeting = response.json);
You can use jwt token for this.
Store the sessionId in localStorage or a cookie.
Send it inside the request header in each and every request (use httpInteceptor for this)
https://medium.com/#ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8
In the Java application, add filter to all the requests, which need to be protected.

Unable to post to aspnet webapi using angular http

I have created a simple webapi controller.
// POST request api to get a string base64 image, store it and returns its name.
public string Post([FromBody]string image)
{
if (image == null)
return "No image sent";
// Generating random file name using the current date and time and random text
string fileName = "image-" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + Path.ChangeExtension(
Path.GetRandomFileName(),
".jpg"
);
// If the directory does not exist create a new one
if (!Directory.Exists(#".\uploads\"))
{
DirectoryInfo DI = Directory.CreateDirectory(#".\uploads\");
}
File.WriteAllBytes(#".\uploads\" + fileName, Convert.FromBase64String(image));
return "Submitted as File: " + fileName;
}
When I send a post request through postman, it works as fine and returns the string "Submitted as File ..."
But when I try it in Angular I get the following error.
OPTIONS http://example.com/Api/Image/Index 405 (Method Not Allowed)
My angular service:
getResult(base64image) {
//Where base64image is a string.
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post('http://example.com/Api/Image/Index', base64image, options)
.map(res => res);
}
I know that it has something to with cors. But it is just a simple api.

Venmo Oauth 2.0 Using Ionic Framework - 400 Bad Request Error

I am currently trying to login to my app that is built on Ionic Framework using Venmo's Oauth API. I am attempting to use the Server Side Flow so that I can have a longer term access token. I am able to receive a code and set it to a requestToken variable.
However, when I attempt to post to "https://api.venmo.com/v1/oauth/access_token" with my Client Id, Client Secret, and Request Token, I get the following error alert: "ERROR: [object Object]".
In checking my console, I see that the error is a 400 Bad Request error coming on my post request, although it does appear that I have a valid request token. The error message is as follows: "Failed to load resource: the server responded with a status of 400 (Bad Request)".
Below is the code of the login function I am using to login via Venmo's Oauth API:
//VENMO SERVER SIDE API FUNCTION
var requestToken = "";
var accessToken = "";
var clientId = "CLIENT_ID_HERE";
var clientSecret = "CLIENT_SECRET_HERE";
$scope.login = function() {
var ref = window.open('https://api.venmo.com/v1/oauth/authorize?client_id=' + clientId + '&scope=make_payments%20access_profile%20access_friends&response_type=code');
ref.addEventListener('loadstart', function(event) {
if ((event.url).startsWith("http://localhost/callback")) {
requestToken = (event.url).split("?code=")[1];
console.log("Request Token = " + requestToken);
$http({
method: "post",
url: "https://api.venmo.com/v1/oauth/access_token",
data: "client_id=" + clientId + "&client_secret=" + clientSecret + "&code=" + requestToken
})
.success(function(data) {
accessToken = data.access_token;
$location.path("/make-bet");
})
.error(function(data, status) {
alert("ERROR: " + data);
});
ref.close();
}
});
}
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function(str) {
return this.indexOf(str) == 0;
};
}
This function is from this helpful walkthrough article by Nic Raboy (https://blog.nraboy.com/2014/07/using-oauth-2-0-service-ionicframework/). I think that the problem may be in how I am presenting the data array, so if anyone has any experience in successfully implementing a Venmo API in Ionic, your help would be much appreciated!
I was actually able to solve this issue with the method described above. In my original code, I omitted the line used to set the content type to URL encoded (which was included in Nic's example). Once I added this line, the request functioned as expected. The line was as follows:
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Passing authorization bearer token using BreezeJS OData data service

How do I tell Breeze to include an authorization bearer token header when using the OData data service?
//Configured breeze to use OData
breeze.config.initializeAdapterInstance('dataService', 'OData');
//Configured breeze to use AngularJS ajax
var instance = breeze.config.initializeAdapterInstance('ajax', 'angular', true);
//Tried passing authorization bearer token header using setHttp with no success
//NOTE: $http setup with $http.defaults.headers.common['Authorization'] = 'Bearer...'
instance.setHttp($http);
//Tried passing authorization bearer token header using ajax settings with no success
instance.defaultSettings = {
headers: {
'Authorization': 'Bearer...'
},
};
//Fiddler shows no authorization bearer token header for following query
var manager = new breeze.EntityManager('/odata/');
var query = breeze.EntityQuery.from('Customers');
return manager.executeQuery(query).to$q(querySucceeded, queryFailed);
I don't know if you solved your problem. This worked for me:
function configureBreeze() {
// configure to use the model library for Angular
breeze.config.initializeAdapterInstance("modelLibrary", "backingStore", true);
var accessToken = Security.user.access_token;
if (Security.user.access_token) {
// get the current default Breeze AJAX adapter & add header required for the Web API bearer token mechanism
var ajaxAdapter = breeze.config.getAdapterInstance("ajax");
ajaxAdapter.defaultSettings = {
headers: {
'Authorization': 'Bearer ' + accessToken
},
};
}
}
It is a modification of the configureBreeze method found in the datacontext.js script of the Angular/Breeze SPA template for asp.net MVC4.
Hope it helps.
I had the same problem. After looking at breeze dataservice for oData i think that it just ignores ajax provider cause it's using datajs to do requests. So instance.setHttp($http); won't work. I ended up overriding default request method in datajs like that:
var base = window.OData.request;
window.OData.request = function (request, success, error, handler, httpClient, metadata) {
angular.extend(request.headers, { Authorization: $rootScope.token });
return base(request, success, error, handler, httpClient, metadata);
};
There's an sample on the Breeze Website (under OData AJAX): http://www.getbreezenow.com/documentation/controlling-ajax
var oldClient = OData.defaultHttpClient;
var myClient = {
request: function (request, success, error) {
request.headers.Authorization = authorization;
return oldClient.request(request, success, error);
}
};
OData.defaultHttpClient = myClient;
//instance.defaultSettings = {
// headers: {
// 'Authorization': 'Bearer...'
// },
//};
instance.headers['Authorization'] = 'Bearer...';

Resources