defaultSuccessUrl not correctly rendering the html page - angularjs

I'm trying to setup a defaultSuccessUrl using Spring security and AngularJS, but after a success login the html page is loaded in the network but not displayed.
here is my security config
http
.authorizeRequests()
.anyRequest().authenticated().and()
.formLogin()
.loginPage("/")
.loginProcessingUrl("/")
.successHandler(this.authSuccess)
.failureHandler(this.authFailure).permitAll()
.defaultSuccessUrl("/app/components/hello.jsp", true);
http
.authorizeRequests()
.anyRequest().authenticated().and()
.logout()
.logoutSuccessHandler(this.logoutSuccess)
.deleteCookies("JSESSIONID")
.invalidateHttpSession(false).permitAll();
but when I chec the network I can see that post request for the login was redirected with 302 status code and Hello.jsp was loaded with 200 Status
however I still have the login page displayed and not the hello.jsp page.
Angular service for login :
this_.login = function(data) {
return $http.post(_contextPath + '/',
"username=" + data.username + "&password=" + data.password, {
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
}
}).success(function(response) {
return response.status;
}).error(function(response) {
return response.status;
})
};
Any one knows why?

You are using the ajax to post the login form, so the page can't redirect to the success url, you can return the default url and then redirect to the url at the front end. like this

Related

Redirect from React ASP.NET application to SSO login page blocked by CORS Policy

My application is set up as of follows:
Frontend is React (SPA),
Backend is ASP.NET Core 6, and
User will be authenticated via SSO using SAML2 protocol (the SAML code is implemented on the ASP.NET side, not React)
When the React page is loaded, it will send a POST request via fetch API to the ASP.NET server which then will trigger to load the SSO page (I'm actually confused by this as I'm unsure how this would work with React since React handles all the routing piece here). However, I keep getting an error that is saying:
"Access to fetch at 'https://sso.example.com/saml/idp/profile/redirectorpost/sso?SAMLRequest=xxxx&RelayState=ReturnUrl%3D%252Fexample%252Fexampleapp%252FGetLoggedInUser' (redirected from 'https://forms.test.com/test/testapp/GetLoggedInUser') from origin 'https://forms.test.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request."
I attempted to fix this by changing the attributes in the fetch headers by all resulted in the same CORS error.
Here's my fetch api code on the frontend:
fetch("testapp/GetLoggedInUser", {
method: "POST",
headers: {
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: data
}).then((response) => {
const contentType = response.headers.get("content-type");
if (contentType && contentType.indexOf("application/json") !== -1) {
return response.json().then((data) => {
return data;
}).catch((err) => {
console.log(err);
})
}
else {
return response.text().then((data) => {
return data;
}).catch((err) => {
console.log(err);
})
}
});
My backend (ASP.NET Core 6)
//[Authorize] is an attribute from Microsoft.AspNetCore.Authorization.AuthorizeAttribute
[Authorize]
[HttpPost("GetLoggedInUser")]
public string GetLoggedInUserData()
{
this.CheckSession();
Person Person = new ActiveUser(this.ID, GlobalVariables.ProcessCode);
dynamic P = Person.GetSimple();
User User = new User(this.WhitworthID);
P.LastAccess = DateTime.Now;
User.SetLastAccess();
return JsonConvert.SerializeObject(P);
}
Can anyone advise me on how to get past the CORS error when redirecting from React to the SSO page?
Modify your code to check if the response is redirected,if so redirect the browser to the new url.
fetch(url, { method: 'POST', redirect: 'manual'})
.then(response => {
// HTTP 301 response
// HOW CAN I FOLLOW THE HTTP REDIRECT RESPONSE?
if (response.redirected) {
window.location.href = response.url;
}
})
.catch(function(err) {
console.info(err + " url: " + url);
});

Receive response from Instagram API call with AngularJS

To authenticate a user in an app using the Instagram API, you redirect the user to the URL https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code.
Once the user signs in on this page, Instagram then makes a GET request to the redirect URI (REDIRECT-URI in the above URL). This call to the redirect URI contains a code which you must then include in a POST request to https://api.instagram.com/oauth/access_token to exchange for an access token which is sent in a JSON form in the response.
So I'm receiving the redirect call and making the request for the access token with my Express API and this works fine and I get the form with the access token.
app.get('/redirect', function(req, res){
if(req.query.error){
console.log('Error authenticating user');
console.log(req.query.error);
}
else{
request.post(
'https://api.instagram.com/oauth/access_token',
{form:{
client_id: 'my_client_id',
client_secret: 'my_client_secret',
grant_type: 'authorization_code',
redirect_uri: 'http://localhost/redirect',
code: req.query.code
}
},
function(error, response, body){
if(!error && response.statusCode == 200){
console.log(body);
//HOW DO I GET THIS RESPONSE TO ANGULAR?
res.json({
access_token: body.access_token,
full_name: body.full_name,
username: body.username,
profile_picture: body.profile_picture,
id: body.id
});
return;
}
else{
console.log(response);
console.log(body);
}
}
);
};
My question is: how to I send the access token (or error response) back to Angular?
In other words, how does Angular receive the response from a request it did not make (since the response I want to receive is from the request made with NodeJS's request)?
Initially I tried to make the first GET to https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code with Angular but I don't think this can be done because the user should be directed to the Instagram URL to sign in.
Update:
When Instagram makes the GET /redirect?code=xxxxxx, it sends the request to my API but also changes the page URL to http://localhost/redirect?code=xxxxxx. I can receive the access token in my API and send it to my client-side but because of the above URL, the page is just displayed as the text of the response and not my index.html with ng-view. How do I get the page to be my index.html in this situation?
I've tried with angular-router the following ways but neither worked:
.when('/redirect', {
templateUrl: 'views/success.html',
controller: 'Controller'
})
and
.when('/success', {
templateUrl: 'views/success.html',
controller: 'Controller'
})
.when('/redirect', {
redirectTo: '/success'
})
What I ended up doing (and I'm not sure this is optimal):
Once I receive the response from the call made from Node, I store the access token from the response, body.access_token, in the req.session.user object provided by the express-session npm package and then I redirect the user to the home page with res.redirect('/#/home');.
app.get('/redirect', function(req, res){
if(req.query.error){
console.log('Error authenticating user');
console.log(req.query.error);
}
else{
request.post(
'https://api.instagram.com/oauth/access_token',
{form:{
client_id: 'my_client_id',
client_secret: 'my_client_secret',
grant_type: 'authorization_code',
redirect_uri: 'http://localhost/redirect',
code: req.query.code
}
},
function(error, response, body){
if(!error && response.statusCode == 200){
console.log('Success making POST to Insta API for token, making new session object');
console.log('token:', (JSON.parse(body).access_token), '\n');
req.session.user = {};
req.session.user.token = JSON.parse(body).access_token;
req.session.save();
res.redirect('/#/home');
}
else{
console.log(error);
res.redirect('/#/login');
}
}
);
};
This way, Angular doesn't need to receive the access token after redirecting the user to Instagram's authorization page because the access token is saved in the req.session.user object which is then accessible on the backend for the duration of the session.
You can then use the access token in any requests to the Instagram API from your backend (initiated by a call to your API from Angular), e.g. by concatenating it to whatever the endpoint is for your Instagram API call like so:
var endpoint = 'https://api.instagram.com/v1/users/self/follows?access_token=' + req.session.user.token;
This method also works well with the session management functionality of express-session since a session is only created when the user can be authenticated by Instagram. See here for a quick tutorial on how to integrate session management into your app.

Token authorization - Browser throws Login form

I am working on a token implementation into Angular/.Net application. My part is the front-end. What's happening is that when UI sends a request with the expired token and the server replies with 401 I cannot intercept that before the Browser raises the Login form. As the result I cannot send a request to refresh the token. Can someone please give me an idea how that is supposed be managed? I will provide code just don't know what's to show.
Thanks
Adding code:
var response = $http({
method: "GET",
dataType: "json",
params: params,
headers: {
'Content-Type': "application/xml; charset=utf-8",
},
url: someurl
});
response = response.then(function (data) {
return data.data;
});
response.catch(function (data) {
$q.reject(data);
});
// Return the promise to the controller
return response;
The problem is that I cannot redirect on UI because Browser throws Login form before my code is hit when the server returns 401.
Make ajax request, and if you get 401 then redirect to login page.
P.s. for better understanding provide your code how you implement ajax request. Which module do you use for front-end auth? I recommend satellizer
Added:
I guess you need the following configuration on angular
var app = angular.module('App', ['satellizer'])
.config(function() {
/* your config */
}
.run(function($rootScope, $location, $auth) {
// Check auth status on each routing,
// Redirect to login page, if user is not authenticated or if token expired
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (!$auth.isAuthenticated()) {
$location.path('/auth/login');
}
});
});

Status Code 302 found on POST request using Angular, Revel and Go

I am using Revel + angular for my application. The index page is the login interface, and once you are successful, you should be directed to the dashboard.html page. The problem is once I have made a POST request, I get a GET request with my 'response body', however, I am still in the login page. I am using angular to make a post request to my restful server. However, whenever I make a POST request I get status 302 on my POST request but my GET request fetches the response for the page.
My Angular Controller
appMainLogin.controller('MainLoginForm',function($scope, $http){
$scope.user_email = null;
$scope.user_pass = null;
$scope.user_remember = true;
$scope.userLogin = function () {
var val = {
"user_email": $scope.user_email,
"user_pass": $scope.user_pass,
"user_remember": $scope.user_remember,
};
var stringify = JSON.stringify(val);
$http({
url: '/login',
method: 'POST',
data: stringify || '',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
}
}).success($scope.getEmailData).error($scope.httpError);
alert("error");
};
});
My routes
POST /login App.Login
GET /dash Dash.Index
I get this: 302 on the POST request
I get this: 200 OK on the GET request
On the 'response body' of the GET request (firefox debugger) I see my I intended html page but I still remain in the index page.
Why is my app not redirecting to the dashboard.html(index.html->dashboard.html) after the user enters their login credential (based on my code above)?

Angular 404 redirect

I have a http get request from client angular to server
If the request returns a 404, the app gets redirected to the default page which is my home page.
How do I prevent the redirect on the error function handle therE?
$http({
method: 'POST',
url: '/customers/' + customer.id + "/addresses",
data: address
})
.success(function(address){
})
.error(function(data){
//prevent the 404 redirect here
});

Resources