Spring Security with Angular2 - spring

I'm trying to authenticate my user from an Angular2 form using Spring Security, but its not working. I've looked all over the web, but seem to find no right answer to it, could someone point out where I am going wrong -
Here's a snippet from my spring-security.xml -
<security:form-login login-page="/"
authentication-failure-url="/security/login"
default-target-url="/"/>
<security:access-denied-handler error-page="/security/denied"/>
<security:logout invalidate-session="true"
logout-success-url="/security/logout/success"
logout-url="/security/logout"/>
Here's my angular2 form -
<form (ngSubmit)="onLogin(f.value)" class="form-horizontal" role="form" #f="ngForm">
<div class="form-group">
<label class="col-sm-3 control-label" for="j_username">Username:</label>
<div class="col-sm-8">
<input type="text" class="form-control" placeholder="Username" name="j_username" [(ngModel)]="user.userName"
maxlength="50" id="j_username" required >
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="j_password">Password:</label>
<div class="col-sm-8">
<input type="password" class="form-control" placeholder="Password" name="j_password" [(ngModel)]="user.password"
maxlength="50" id="j_password" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-8 col-sm-10">
<input type="submit" class="btn btn-default" value="Login">
</div>
</div>
</form>
And here's the component code -
onLogin(f) {
this.userService.makeHttpCall(f);
}
And finally the service which calls the spring security -
makeHttpCall(f): void {
let userName = f['j_username'];
let password = f['j_password'];
let data = 'j_username='+userName+'&j_password='+password;
console.log(data);
let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({headers: headers}
);
this.http.post('/j_spring_security_check', data, options)
.map(this.extractData)
.catch(this.handleError);
}
Could someone point out where i am going wrong? the http call, does not make it to the AuthenticationManager defined in my spring security configuration.

In Angular2, HTTP calls are triggered as soon as you subscribe to them. Adjust the code like this:
this.http.post('/j_spring_security_check', data, options)
.map(this.extractData)
.catch(this.handleError).
.subscribe(data => {
// do something here with the response
})

Related

Creating an update page in Spring using Thymeleaf

I'm trying to create an update page for my spring project, When I try to open my edit page using localhost:8080/edit/1 I get
There was an unexpected error (type=Internal Server Error, status=500).
Could not parse as expression: "/edit/{stockNumber}" (editItem:78)
What can I do to solve this issue?
#GetMapping(path="edit/{stockNumber}")
public String editItemForm(#PathVariable Long stockNumber, Model model){
model.addAttribute("item",itemRepository.findOne(stockNumber));
return "editItem";
}
#PostMapping(path="edit/{stockNumber}")
public String editItem(#ModelAttribute Item item){
itemRepository.save(item);
return "redirect:/item";
}
<form action="#" th:object="${item}" th:action="/edit/{stockNumber}" method="post">
<div class="form-group">
<label for="txtItemDesc">Item Description</label>
<input type="text" th:field="*{itemDesc}" class="form-control" id="txtItemDesc" placeholder="item Description" />
</div>
<div class="form-group">
<label for="txtUnit">Unit</label>
<input type="text" th:field="*{unit}" class="form-control" id="txtUnit" placeholder="Unit" />
</div>
<div class="form-group">
<label for="txtAbc">ABC</label>
<input type="text" th:field="*{abc}" class="form-control" id="txtAbc" placeholder="ABC" />
</div>
<button type="submit" value="Submit" class="btn btn-default">Submit</button>
</form>
Your expression in th:action is incorrect. It should be
th:action="'/edit/'+ ${stockNumber}"

While form submitting using ajax..getting Post not supported error ...don't know what is the error?

I am using form submission using AJAX in Spring MVC and Thymeleaf. When I try to submit it it shows
Post method is not supported
I can't figure out the mistake in my code:
<form class="form-horizontal" action="#" th:action="#{/teacher/teacherProfileUpdation}" th:object="${teacherProfileDetailsList}"
id="saveTeacherForm" method="POST" >
<br />
<div class="row">
<div class="col-lg-14 col-md-12">
<br />
<h5 style="margin-left: 15%;">Personal Details</h5>
<hr />
<div class="form-group">
<label class="col-sm-3 control-label">Name</label>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher first name" id="txtTeacherFname" th:field="*{firstName}" type="text" class="form-control" />
</div>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher middle name" id="txtTeacherMname" th:field="*{middleName}" type="text" class="form-control" />
</div>
<div class="col-md-3 col-sm-4 col-xs-4">
<input placeholder="Teacher last name" id="txtTeacherLname" th:field="*{lastName}" type="text" class="form-control" />
</div>
</div>
</div>
<div class="col-lg-14 col-md-12">
<div class="form-actions">
<input type="hidden" id="hdnStudentByIdInSchoolAdmin" value="0" />
<input type="button" class="btn btn-info pull-right" id="btnUpdateTeacherProfile" value="Save" />
</div>
</div>
</div>
JS:
saveTeacherProfile :function(){
$("#saveTeacherForm").ajaxForm({
success : function(status) {
alert("success");
},
}).submit();
}
Controller:
#RequestMapping(value = "/updateTeacherProfile", method = RequestMethod.POST)
public String updateTeacherProfile( TeacherProfileDetails teacherProfileDetails){
System.out.println("-----------"+teacherProfileDetails.getFirstName()+"-------------");
System.out.println("-----------"+teacherProfileDetails.getLastName()+"-------------");
System.out.println("-----------"+teacherProfileDetails.getMiddleName()+"-------------");
return "success";
}
You are posting the form, but most likely your Spring controller is not configured to accept POST requests. Try this in your server-side Controller class for this page:
#RequestMapping(..., method = { RequestMethod.GET, RequestMethod.POST }, ...)
public void myControllerMethod()
{
#RequestMapping(..., method = { RequestMethod.GET, RequestMethod.POST }, ...)
public String updateTeacherProfile( TeacherProfileDetails teacherProfileDetails){
//ur Logic
}

Cannot submit a form on SpringMVC

I am fairly new to SpringMVC and have a form that can not submit to the back-end. I created the form as following and when I submit it error 404 will be returned. I changed action to /MyProject/contact but did not work.
<form class="form-horizontal" role="form" method="post"
action="/contact">
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Name
</label> <input type="text" class="form-control" id="name"
name="name" placeholder="Your name" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Email
Address</label> <input type="email" class="form-control" id="email"
name="email" placeholder="Your email" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Phone
Number</label> <input type="number" class="form-control" id="phone"
name="phone" placeholder="Phone number" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Enquiry</label>
<textarea class="form-control" rows="4" name="message"
placeholder="Please enter your enquiry"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-2 " style="float: right;">
<input id="submit" name="submit" type="submit" value="Send"
class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<! Will be used to display an alert to the user>
</div>
</div>
</form>
Controller
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
Error
HTTP Status 404 - /contact
type Status report
message /contact
description The requested resource is not available.
Its beacuse spring does not know how to pass the param Contact contact to your controller method. You need to do couple of things to make it work. Change your form to like below.
<form class="form-horizontal" role="form" method="post" modelAttribute="contact" action="/contact">
Your controller to take contact as model attribute.
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(#ModelAttribute Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
For a better understanding of what a model attribute does, there are plenty of samples and explanation online. Hope this helps.
I could solve the problem by help of minion's answer, following this tutorial and adding following link
#RequestMapping(value = "/contact", method = RequestMethod.GET)
public ModelAndView contactForm() {
System.err.println("here in GET");
return new ModelAndView("contact", "command", new Contact());
}

CasperJs, how to fill a form that only have a class, not a name and not an id?

I want to fill this form, but i dont know how to do it since it only have a classname.
All the examples i saw have an id or a name, to fill the form and submit it, please help.
<form class="header_form" method="post" action="">
<div class="lgn-items">
<div class="login_item">
<label>Email</label>
<input type="text" name="email" tabindex="1" class="inputtext" id="email" />
</div>
<div class="login_item" >
<label>Password</label>
<input type="password" name="password" tabindex="2" class="inputtext" id="pass" />
</div>
<div class="lgn-add">
Registration <span>|</span>
Forgot your password ?
<div class="rembo">
<input type="checkbox" name="remember" value="1" /> Remember me
</div>
</div>
</div>
<div class="login_item lgn-btn" >
<input type="submit" name="login_button" value="Login" tabindex="3" class="login" />
</div>
</form>
You can access to your form using any selector. In your case you to it like this.
casper.then(function () {
casper.fill('form.header_form', {
/** Your parameters here **/
}, true);
});

How to collect form data and convert them json format and send back to server in spring mvc

I have form and I want to grab the data inserted by users and then convert them json format.
So first here is my form—
<form id="patient_form" action="#" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="firstName"> First Name<em>*</em></label>
<div class="controls">
<input type="text" id="firstName" class="required" maxlength="100"
placeholder="First Name" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="middleNameInitial">
Middle Name Initial</label>
<div class="controls">
<input type="text" id="middleNameInitial"
placeholder="Middle Name Initial" class="input-small"
maxlength="1" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="lastName"> Last Name <em>*</em></label>
<div class="controls">
<input type="text" id="lastName" placeholder="Last Name"
class="required" maxlength="100" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="dateOfBirth"> Date Of
Birth</label>
<div class="controls">
<input type="text" id="dateOfBirth" class="required" />
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="button" class="btn btn-primary"
onclick="savePatientInfo()">Save Changes</button>
<button type="button" class="btn"
onclick="cancelPatientInfoForm()">Cancel</button>
</div>
</div>
</form>
And then I want to send back them to server. And for server side code, I’m using spring mvc and client side I’m using JQuery.
Now how can I do it? I need two things basically,
Ajax call (JavaScript function to which will basically do 3 things, one- grab the form data and convert them into json and then ajax call)
Sever side method to consume ajax call (Controller method as I’m
suing spring mvc.)
Any help is much appreciated.
First of all you need to perform ajax call from the JSP as below:
$.post("${pageContext.servletContext.contextPath}/ajaxTestData",
{
firstName:$("#firstName").val(),
middleNameInitial:$("#middleNameInitial").val(),
<other form data>
},
function(j)
{
<j is the string you will return from the controller function.>
});
Now in the controller you need to map the ajax request as below:
#RequestMapping(value="/ajaxTestData", method=RequestMethod.POST)
#ResponseBody
public String calculateTestData(#RequestParam("firstName") String firstName, #RequestParam("middleNameInitial") String middleNameInitial, HttpServletRequest request, HttpServletResponse response){
<perform the task here and return the String result.>
return "xyz";
}
I have not used the JSON input and result in this way but I think if you return the Pojo then it might converts the same in the json format automatically. Just check that.
Hope this helps you. Cheers.

Resources