I can get get access token from postman oauth 2. Same way i was
tried to generate token in angular js with redirect url, client id
... etc.
But i not able to do and also i don't know how?
I was created identity server 4 API sample with auth server. Now i
want to get token from my angular app.
But i need this flow in angular js.
I tried this below code
angular.module("trainingApp")
.controller('loginController', ['$scope', function ($scope) {
function login(){
var client_id="testproduct";
var client_secret="test#123";
var scope="testAPI";
var redirect_uri="http://localhost:9000";
var response_type="token";
var url="http://localhost:1215/connect/authorize?scope="+scope+"&client_id="+client_id+"&client_secret="+client_secret+"&redirect_uri=http://localhost:9000"+redirect_uri+"&grant_type=authorization_code"+
"&response_type="+response_type;
window.location.replace(url);
};
login();
}])
Access to XMLHttpRequest at 'localhost:1215/connect/…' from origin 'localhost:9000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
But i am get UI for Login. Help ???? :)
You're on the right track with the authorize endpoint redirect but you're doing it the hard way.
Check out the oidc-client-js library, it does everything you need and there are even samples for Angular.
https://github.com/IdentityModel/oidc-client-js
Related
The web client uses $http.post to communicate with my server to initiate the Twitter authorization. In my asp.net mvc app, I use this LinqToTwitter code:
var auth = new MvcSignInAuthorizer
{
CredentialStore = new SessionStateCredentialStore
{
ConsumerKey = ConfigurationManager.AppSettings["TwitterKey"],
ConsumerSecret = ConfigurationManager.AppSettings["TwitterSecret"],
OAuthToken = null,
OAuthTokenSecret = null,
UserID = 0,
ScreenName = null
}
};
string twitterCallbackUrl = ....; // My server callback here
return await auth.BeginAuthorizationAsync(new Uri(twitterCallbackUrl));
When this goes back to the client, nothing happens and I see an error message in the console:
XMLHttpRequest cannot load
https://api.twitter.com/oauth/authenticate?oauth_token=[...]. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
When using the facebook API, the server was able to get the facebook auth URL and return it with a json response. I could then redirect myself in my angular code. But here I use BeginAuthorizationAsync which returns a 3032 with the auth url put in the headers's Location field.
How can I handle this on the angular side? Can I get the full oauth url with the oauth token from LinqToTwitter to simply return it as json, like with facebook?
PS: I know I can use a form POST to solve this but I'm trying to keep my angular solution to avoid forms in my web page.
Thanks
I'm getting crazy to understand how to handle a basic authentication with an API.
Basically what I need to do is to request a token from an API sending a module-username and module-password (not a user login). The server should return a token that I will need to use for all other request I will make to the server.
Looking on internet I've found solution that involves user logins and angular routing.
I'm not using any routing, the routing is managed server side and I need to consume the API on few pages, before consuming I need to attach the token to every request.
I don't understand exactly how to start properly.
I should need to create an ajax request for the first authentication, save the token somewhere and use it for all other requestes. Keeping in mind that if the token is not valid I should request it again.
I'm quite confused on how to do it, I can not find any good tutorial.
Any help?
I'm still learning Angular myself, but hopefully this basic example helps you. You can use $cookies to save and retrieve a token that is sent back from your server. Then, assuming you are using $http or $resource, you can use an $httpProvider interceptors to add the current token value (retrieved from $cookies) to the header of every outgoing request your app makes.
Here's a simple example of how you might create an $httpProvider interceptor:
authServices.factory('sendTokenInHeader', ['$cookies', function($cookies) {
return {
request: function(config) {
var token = $cookies.getObject('x-my-token');
if(token) {
var updateHeaders = config.headers || {};
updateHeaders['x-my-token'] = token;
config.headers = updateHeaders;
}
return config;
}
};
}]);
Then in your app.config you need to just push this interceptor and now any outgoing $http/$resource request will include the current token!
myApp.config(['$httpProvider', function($httpProvider) {
// do other stuff...
$httpProvider.interceptors.push('sendTokenInHeaders');
}]);
i am try to create a SPA with Angular. I have to consume the a service form different server. It is a java based service. Here i am getting "No 'Access-Control-Allow-Origin' header is present on the requested resource"
angular.module('tableApp', [])
.config(function ($httpProvider) {
//Enable cross domain calls
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";
//Remove the header used to identify ajax call that would prevent CORS from working
delete $httpProvider.defaults.headers.common['X-Requested-With'];
})
.controller('tableCtrl', ['$scope', '$http', '$timeout', function ($scope, $http) {
var bassURL = 'http://[server ip]:8080/ABC/resource/XYZ'
$http.get(bassURL + '/getTypes').success(function (Type) {
$scope.Type = Type;
});
}
])
Please help.
Your browser is using the CORS protocol to verify access to the service, to prevent cross-site scripting attacks. You need to enable CORS support on the server (adding the Access-Control-Allow-Origin header allowing the site where your Angular site is hosted). Alternatively, you need to use one of the pre-CORS hacks for getting JSON cross-site, and your server needs to provide support for it.
Step 1:
Verify that your angular app is actually hitting a valid URL.
Do this through Fiddler or Postman
Step 2:
Verify that your client AngularJS application and server are running at the same URL and port.
If you intend on having them running on different ports / URLs, you'll need to setup CORS on your java application as mentioned in other comments.
Step 3 (if using Step 2):
Specify a append a JSON_CALLBACK parameter to your URL.
SO Example
Example
Suppose I have an angular app called chococalateApp that depends on 3 other modules, namely Product, Sales and LogIn.
Now, my app is building on RESTful API. Upon successful login, the server will respond by sending back an authentication token. I would like to append this token as a custom header X-AUTH whenever $http services are used. Since all my REST API requires the auth token, I would need to append this header in every $http request. This is doable by configuring the $httpProvider, as shown below:
angular.module('chocolateApp',['Product','Sales','Login'])
.config(['$httpProvider', function($httpProvider){
$httpProvider.defaults.headers.common['X-AUTH'] = 'randomkeybyserver'
}
])
My question is, can I inject the value of the auth-token AFTER the module has been bootstrapped?
For example, I have a service in LogIn module that is able to do the authentication, and retrieved the required token. How do I pass the token back to my main chocolateApp module and configure it? Will this result in circular dependency, or is it that my understanding of DI is wrong here?
If this is not achievable, how should this be designed?
You can do it from your Login service after authentication and it will be available across your app.
login: function(...) {
$http.post(...).then(function(response) {
$http.defaults.headers.common['X-AUTH'] = response.data.randomkeybyserver;
});
}
I authenticate my user only through laravel, so angular does not know about it. But I need to do a $http.post on a "before auth" route with angular in order to get some profil info:
laravel route.php
Route::post('profile', array('before' => 'auth', function()
{
// Only authenticated users may enter...
}));
angular app.js
$http.post("/profile").success(function (data) {
$scope.profile = data;
});
For now I get an internal server error (500) with a "Illuminate\Session\TokenMismatchException" because laravel think I'm not logged in.
Could someone help me out with this?
Thanks in advance :)
My mistake, it was a csrf filter that was causing this error, not the auth filter...
For reference to my question:
AJAX Requests are identical with regular requests in regards to session data. Anything that depends on Session or Auth will work with an AJAX call.
link to thread