Spring Security 4 and Angular login authentication - angularjs

I've a problem with seend good post to login authentication.
This is my security configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").access("hasRole('USER')")
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login/authentication").successHandler(securityHandler)
.usernameParameter("s_username").passwordParameter("s_password")
.and().csrf()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
Spring controller:
#Controller
#RequestMapping("/login")
public class AuthController {
#RequestMapping(value="", method = RequestMethod.GET)
public String getLoginPage(){
return "login/layout";
}
}
My login page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login</title>
<link href="resources/css/bootstrap/css/bootstrap.css" rel="stylesheet"/>
<script src="resources/js/angular.min.js"></script>
<script src="resources/scripts/auth/Auth.js"></script>
<script src="resources/js/angular-route.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body ng-app="appAuth">
<div class="col-md-6 col-md-offset-3" ng-controller="LoginController as login">
<h2>Login</h2>
<form name="form" ng-submit="Login()" role="form">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" ng-model="login.username" required />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" ng-model="login.password" required />
</div>
<div class="form-actions">
<button type="submit" ng-disabled="form.$invalid" class="btn btn-primary">Login</button>
</div>
</form>
</div>
</body>
</html>
And Angular Controller:
(function (angular) {
'use strict';
var App = angular.module('appAuth', ['ngRoute'])
App.controller("LoginController", function ($scope, $http, $window) {
var encode4form = function(data){
var result="";
var first = true;
for(var key in data)
{
if(first){
first=false;
}
else{
result+="&"
}
result+=(key + "=" + data[key]);
}
return result;
};
$scope.Login = function () {
var mycsrf = $("input[name='_csrf']").val();
$http(
{
url: "/login/authentication",
method:"POST",
data: encode4form({
s_username: $scope.login.username,
s_password: $scope.login.password,
_csrf: mycsrf
}),
headers:
{
"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
}
}
);
//$http({
// method: 'POST',
// url: 'http://localhost:8080/login/authentication',
// data: data,
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
// }
//$http.post('/login/authentication', loginData), {
// headers: {
// 'X-CSRF-TOKEN': $('input[name="_csrf"]').val(),
// //'Content-Type': "application/x-www-form-urlencoded"
// 'Content-Type': 'application/json'
// }
//});
};
});
})(window.angular);
Console log:
2016-02-27 11:11:27 INFO AuthController:24 - Login
2016-02-27 11:11:31 WARN PageNotFound:1136 - No mapping found for HTTP request with URI [/Access_Denied] in DispatcherServlet (When I click login)
I tried many ways but no way didn't work. When I click login button chrome show error "POST http://localhost:8080/login/authentication 404 (Not Found)". When I change login page to login.jsp (without angular) then works. Why didn't work on angular?

Related

Cannot pass data to the as.net mvc controller from $http in angularJS

I am Getting null value in action method when i am pass data from angular js to action method. data is coming up to $scope.custmodel and i debug and see it hit to the AddCutomer method but data is null. can anyone help me to fix this issue
Admin.js code
var app = angular.module("adminmdl", [])
app.controller("admincontroller", function ($scope,AdminService) {
$scope.Action = 'Add';
$scope.data = {
cus_code: '',
cus_name: ''
}
$scope.savecu = function () {
AdminService.saveCustomerDdetails($scope.cusmodel).then(function (data) {
if (data != null) {
alert('Insert successfully');
} else {
alert('error in inerting data');
}
});
}
})
.factory("AdminService", function ($http) {
var fact = {};
fact.saveCustomerDdetails = function (d) {
return $http({
url: '/Admin/AddCutomer',
method: 'POST',
data: JSON.stringify(d),
headers: { 'content-type': 'application/json' }
});
};
return fact;
});
ASP MVC Method
[HttpPost]
public JsonResult AddCutomer(Customer customer) {
te.Customers.Add(customer);
te.SaveChanges();
string message = "Success";
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
html code
<form class="form-horizontal" method="post" action="#" name="basic_validate" id="basic_validate" novalidate="novalidate">
<div class="control-group">
<label class="control-label">Customer Code</label>
<div class="controls">
<input type="text" ng-model="cusmodel.Customercode" name="required" id="required" >
</div>
</div>
<div class="control-group">
<label class="control-label">Customer Name</label>
<div class="controls">
<input type="text" ng-model="cusmodel.Customername" name="name" id="name" >
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" value="Save" ng-click="savecu()" class="btn btn-success">
<input type="submit" value="Clear" class="btn btn-success" />
</div>
</div>
add [FromBody] attribute to the controller as shown below
public JsonResult AddCutomer([FromBody] Customer customer)

how to redirect to other page when request is made using angularjs to spring controller

#MY Login page code snippet
--------------------------------
<div class="login-container">
<form ng-submit="onLogin()" name="form" class="pure-form login-form"
ng-controller="LoginCtrl as vm">
<fieldset class="pure-group">
<legend>Log In</legend>
<label for="inputUsername" class="sr-only">Username</label> <input type="text" id="inputUsername" class="form-control"
placeholder="Username" required autofocus ng-model="vm.username">
<label for="inputPassword" class="sr-only">Password</label> <br>
<input type="password" id="inputPassword" class="form-control"
placeholder="Password" required ng-model="vm.password">
</fieldset>
<button type="submit"
class="pure-button pure-input-1 pure-button-primary">Log In</button>
<div class="alert alert-danger" role="alert" ng-show="errorMsg">{{errorMsg}}</div>
</form>
</div>
<div id="content" class="col-lg-10 col-sm-10">
<div class="row">
<div class="box col-md-12">
<div class="box-inner"></div>
</div>
</div>
</div>
# login.js
-----------------
angular.module('loginApp', [])
.controller('LoginCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.onLogin = function () {
var encodedString = '?username=' +
encodeURIComponent($scope.vm.username) +
'&password=' +
encodeURIComponent($scope.vm.password);
var url = "http://localhost:8080/servicesummary/employees/view"+encodedString;
$http({
method: 'GET',
url: url
})
.success(function(data) {
//alert(JSON.stringify(data));
var container = 'box-inner';
$('.' + container).html(response);
})
.error(function(data) {
$scope.$error = 'Unable to submit form';
})
};
}]);
# Spring Controller-
--------------------------
#RequestMapping(value = "/view", method = RequestMethod.GET, produces = "application/json")
public ModelAndView getEmployeeInJSON(#RequestParam("username") String username, #RequestParam("password") String password) {
final ModelAndView mv = new ModelAndView();
try {
AppUserDTO appUserdb = userService.getObject(username);
if (null != appUserdb && (appUserdb.getPassword() != null)) {
String decodedPass = UtilityService.decode(appUserdb.getPassword());
if (decodedPass.equals(password)) {
System.out.println("Database Match.............");
mv.setViewName(VIEWNAME_HOME);
} else {
mv.setViewName(VIEWNAME_LOGIN);
}
} else {
mv.addObject("uNameNotValid", false);
mv.setViewName(VIEWNAME_LOGIN);
}
} catch (Exception e) {
logger.error("ERROR handleGetLogin() {}", e);
System.out.println("Exception is occured.....");
return new ModelAndView("redirect:/home-exception");
}
return mv;
}
Hi i have user input username and password which i trying to validate from database using spring controller (TestController.java) from angularjs. i am bale to call controller using login.js written, but not able to process the ModelAndView object returned using angularjs. please see my login.js for reference.
You can update your $http method as below
$http({
method: 'GET',
url: url
})
.success(function(data) {
//alert(JSON.stringify(data));
$window.location.href = 'SuccessUrl';
})
.error(function(data) {
$scope.$error = 'Unable to submit form';
})

Uploading Multiple files from Angular JS to SQL DB using MVC Web API

<!DOCTYPE html>
<html ng-app="messageBoardApp" class="page-header">
<head>
<title></title>
<link href="../libs/bootstrap.min.css" rel="stylesheet" />
<!--<script src="Scripts/angular-route.min.js"></script>-->
<script src="../libs/angular.min.js"></script>
<script src="../libs/angular-file-upload.min.js"></script>
<script src="../libs/console-sham.min.js"></script>
<script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
<script src="MessageBoardModule.js"></script>
<script src="MessageBoardController.js"></script>
<script src="MessageBoardService.js"></script>
</head>
<body ng-controller="messageBoardController" class="container">
<div>
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="titleText" ng-model="message.title" class="form-control" />
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea name="contentText" ng-model="message.content" rows="5" cols="40" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="file">File</label>
<input type="file" nv-file-select="" uploader="uploader" multiple>
</div>
<div class="form-group">
<label for="fileList">These are your selected files</label>
<br/>
<ul>
<select name="files" ng-model="selectedFile" ng-options="option.file.name for option in uploader.queue" size="4" class="form-control"></select>
</ul>
</div>
<br/>
<div class="col-sm-offset-0 col-sm-6">
<input type="button" value="Remove File" ng-click="remove()" />
<button ng-click="uploader.clearQueue()" ng-disabled="!uploader.queue.length">Remove all</button>
</div>
<br/>
<br/>
<br/>
<div class="col-sm-offset-4 col-sm-6">
<button ng-click="uploader.uploadAll()">Upload All</button>
<!--<input type="submit" value="Add Message" ng-click="submitForm()"/>-->
<input type="button" value="Exit" ng-click="Close()" />
</div>
</form>
</div>
</body>
</html>
Controller:
messageBoardApp.controller('messageBoardController', ['$scope', 'FileUploader', 'MessageBoardService',
function ($scope, FileUploader, MessageBoardService) {
var uploader = $scope.uploader = new FileUploader({});
$scope.remove = function (selectedItem) {
$scope.uploader.queue.splice(uploader.queue.indexOf(selectedItem), 1);
};
//$scope.message=messageBoardService.SaveMessage();
$scope.submitForm = function () {
alert("Controller");
var message = $scope.message;
MessageBoardService.SaveMessage(message);
//MessageBoardService.SaveMessage($scope.message);
};
// FILTERS
uploader.filters.push({
name: 'customFilter',
fn: function (item /*{File|FileLikeObject}*/, options) {
return this.queue.length < 10;
}
});
// CALLBACKS
uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
console.info('onWhenAddingFileFailed', item, filter, options);
};
uploader.onAfterAddingFile = function (fileItem) {
console.info('onAfterAddingFile', fileItem);
};
uploader.onAfterAddingAll = function (addedFileItems) {
console.info('onAfterAddingAll', addedFileItems);
};
uploader.onBeforeUploadItem = function (item) {
console.info('onBeforeUploadItem', item);
};
uploader.onProgressItem = function (fileItem, progress) {
console.info('onProgressItem', fileItem, progress);
};
uploader.onProgressAll = function (progress) {
console.info('onProgressAll', progress);
};
uploader.onSuccessItem = function (fileItem, response, status, headers) {
console.info('onSuccessItem', fileItem, response, status, headers);
};
uploader.onErrorItem = function (fileItem, response, status, headers) {
console.info('onErrorItem', fileItem, response, status, headers);
};
uploader.onCancelItem = function (fileItem, response, status, headers) {
console.info('onCancelItem', fileItem, response, status, headers);
};
uploader.onCompleteItem = function (fileItem, response, status, headers) {
console.info('onCompleteItem', fileItem, response, status, headers);
};
uploader.onCompleteAll = function () {
console.info('onCompleteAll');
};
console.info('uploader', uploader);
// -------------------------------
}]);
Service:
messageBoardApp.factory('MessageBoardService', function () {
var SaveMessage = function (newMessage) {
alert(newMessage.content);
alert(newMessage.title);
return true;
};
return {
SaveMessage: SaveMessage
};
});
Module:
var messageBoardApp = angular.module("messageBoardApp", ['angularFileUpload']);
Am using below file-upload js from this link
https://github.com/nervgh/angular-file-upload/
I understand all the files which i have selected are in queue. Am not sure how to pass this files(more than 1) to .net mvc wep api call controller and then pass value to SQL DB.
Am stuck up with passing all the form values to service and then to wep api controller.
When you initialize your FileUploader you have to say to which url you would like to post your files. For example:
var uploader = $scope.uploader = new fileUploader({
url: window.location.protocol + "//" + window.location.host + window.location.pathname + "/api/Upload/UploadFile"
});

Angularjs list not refreshing on form submit using MEAN

Some what new to the MEAN stack. Currently I'm reworking an small app I did through codeschool to be full MEAN stack.
The app created can be seen here
Code School app
In rewriting the app using the MEAN stack after submitting the form I must refresh the page to see the city added to the list. What do I need to fix so I don't need to refresh the page for the new Item to be added to the list?
If I'm missing any relevant code below here is my git hub link
git hub link
Here is my code:
angular.module('Cityapp').controller('CityIndexController', function(City, $scope){
$scope.cities = City.query();
window.sc = $scope;
});
angular.module('Cityapp').controller('CityCreateController', function(City, $scope, $http){
$scope.city = new City();
$scope.saveCity = function(city){
$http({
method: 'POST',
url: '/city',
data: city})
.success( function(data, status, headers, config){
console.log($scope.city);
console.log(data);
console.log($scope.city);
}).
error(function(data,status,headers,config){
jQuery('.alert').show();
console.log('nope');
});
};
});
<form ng-controller="CityCreateController">
<legend> New City</legend>
<input for="City-group" name="City" id="City" type="text" ng-model="city.city" placeholder="City Name">
<input for="City-group" name="desc" id="desc" type="text" ng-model="city.desc" placeholder="Description">
<input type="submit" class="btn btn-default" ng-click="saveCity(city)"/>
</form>
<ul ng-controller="CityIndexController" class="city-list">
<li ng-repeat="city in cities">
<a href="#">
{{city.city}}</a></li>
</ul>
It should looks something like that
;(function() {
function Cities($http) {
function City() {
}
City.prototype.save = function() {
return $http.post('/api/city', this);
};
City.cities = [];
City.add = function(city) {
city.save().then(function() {
City.cities.push(city);
});
};
City.getAll = function() {
$http.get('/api/cities').then(function(response) {
City.cities = response.data.map(function(data) {
return new City(data);
});
return cities;
});
};
return City;
}
function CityCreateController(Cities) {
var mv = this;
mv.city = new Cities();
mv.saveCity = function() {
Cities.add(mv.city);
};
}
function CityIndexController($scope, Cities) {
var mv = this;
$scope.$watchCollection(function() {
return Cities.cities;
}, function(cities) {
mv.cities = cities || [];
});
Cities.getAll();
}
angular
.module('app', [])
.factory('Cities', ['$http', Cities])
.controller('CityCreateController', ['Cities', CityCreateController])
.controller('CityIndexController', ['$scope', 'Cities', CityIndexController]);
})();
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<meta charset="utf-8">
</head>
<body ng-app="app">
<form ng-controller="CityCreateController as mv">
<legend> New City</legend>
<input for="City-group" name="City" id="City" type="text" ng-model="mv.city.city" placeholder="City Name">
<input for="City-group" name="desc" id="desc" type="text" ng-model="mv.city.desc" placeholder="Description">
<input type="submit" class="btn btn-default" ng-click="mv.saveCity()"/>
</form>
<ul ng-controller="CityIndexController as mv" class="city-list">
<li ng-repeat="city in mv.cities">
<a href="#">
{{city.city}}</a></li>
</ul>
</body>
</html>
Found a simple fix
angular.module('Cityapp').controller('CityCreateController', function(City, $scope, $http){
$scope.cities = City.query();
$scope.city = new City();
$scope.saveCity = function(city){
$http({
method: 'POST',
url: '/city',
data: city})
.success( function(data, status, headers, config){
$scope.cities.push({city: $scope.city.city,
desc: $scope.city.desc});
}).
error(function(data,status,headers,config){
jQuery('.alert').show();
console.log('nope');
});
};
});
Just added the
$scope.cities.push({city: $scope.city.city,
desc: $scope.city.desc});
to the .success. Works like it should. Now on to my next issue.

Angular JS form data post to Jersey method is giving null on Query Parameter

I was just playing around doing some testing, here is some Javascript, that uses Angular JS to post some form data:
<!DOCTYPE html>
<html>
<head>
<title>Add a course</title>
<script type="text/javascript" src="../angular.js"></script>
</head>
<body ng-app="form">
<div ng-controller="formController">
<form class="course-form">
Name: <input type="text" ng-model="course.name" /><br />
Duration: <input type="text" ng-model="course.duration" /><br />
Fee: <input type="text" ng-model="course.fee" /><br />
<input type="button" ng-click="add(course)" value="Add course" />
</form>
</div>
<script>
angular.module('form', [])
.controller('formController', ['$scope', '$http', '$log', function($scope, $http, $log) {
$scope.add = function(courseData) {
var url = "http://localhost:8080/CourseService/courseService/newcourse";
var request = $http({method: 'POST', url: url, data:{name: courseData.name, duration: courseData.duration, fee: courseData.fee}});
request.success(
function(html) {
alert("it succeeded");
}
);
request.error(
function(html) {
alert("it didn't work");
}
);
};
}]);
</script>
</body>
</html>
here is the method that the data is posted to:
#POST
#Path("/newcourse")
#Consumes(MediaType.APPLICATION_JSON)
public Response newCourse(#QueryParam("name") String name, #QueryParam("duration") String duration, #QueryParam("fee") int fee) {
System.out.println(name+""+duration+""+fee);
return Response.status(200).build();
}
The problem is that When I print the values, they are all null except for the fee which is 0, is there a reason why this is? I have checked the values being posted and they are fine and populated.
I did have other ways or writing the above service method, such as using #FormData, I could also have changed the path to be: `("/newcourse/{name}/{duration}/{fee}"), and URI encoding the values in, but this is just the way I ended up testing it.
If you want the data to be received as query params, (i.e. the requested URL will be like http://localhost:8080/CourseService/courseService/newcourse?name=123&duration=456&fee=789) you have to send them using the params option, instead of the data, which specifies the request body:
var request = $http({method: 'POST', url: url,
params:{name: courseData.name, duration: courseData.duration, fee: courseData.fee}});

Resources