Spring Security configuration with the login form - spring-boot-configuration

It showing me the defult Login form and my login form i use the defult User name und passowrd to login to time. in the first time it sowing me my login form and when i try to login in the same default username and password it rturn alwas to the second login form with code stat:302. (i saved employee in the database but it givs me alwas err)
#EnableWebSecurity
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
EmployeeDao employeeDao;
#Autowired
private DataSource dataSource;
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("select username,password
from employees where username=?")
.authoritiesByUsernameQuery("select username, authority from employees where username=?")
.passwordEncoder(bCryptPasswordEncoder);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").failureUrl("/login?error=true").defaultSuccessUrl("/home", true)
.and()
.logout().logoutSuccessUrl("/login?logout=true") ;
}
}
My Controller:
#GetMapping({"/","/login"})
public String LoginForm() { return "login";}
#GetMapping("/home")
public String showhome(Model model) { return "index";}
My Entity:
#Entity
#Getter
#Setter
#Table(name = "employees")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#Column(name = "username", nullable = false)
private String username;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "fullname", nullable = false)
private String fullname;
#Column(name = "authority", nullable = false)
private String authority;
#OneToMany(mappedBy = "employee", fetch = FetchType.EAGER)
#Cascade(CascadeType.ALL)
private List<Role> roles;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
}
My Login form:
<div class="divLogin" align="center">
<h1 clase="text-center">Login Page</h1>
<form class="addForm" th:action="#{/login}" method="post">
<fieldset>
<legend lase="text-center">Please Login</legend>
<input class="inputForm" type="text" id="username" name="username" placeholder="Username"/>
<input class="inputForm" type="password" id="password" name="password" placeholder="Passowrd"/>
<div class="divBottonLogin" align="center">
<button class="botten" type="submit">Log in</button>
</div>
</fieldset>
</form>
</div>

Related

How to build a Simple search page using Spring MVC?

I have created webapp using Spring MVC and i have done the CRUD operations and now stuck with the search page.
I have already have coded below jsp and the controller.
JSP page body
<div align="center">
<h1>Search Items</h1>
<form action="search_1" method="get" modelAttribute="search">
<table>
<tr>
<td>Category:</td>
<td>
<select type="text" name="category_id">
<option value="Book">Book</option>
<option value="Audio Books">Audio Books</option>
<option value="Videos">Videos</option>
<option value="Music">Music</option>
</select>
</td>
</tr>
<tr>
<td>Publisher ID:</td>
<td>
<select type="text" name="publisher_id">
<option value="Harper Collins">Harper Collins</option>
<option value="Penguins">Penguins</option>
<option value="Franciscan Media">Franciscan Media</option>
<option value="Orbis">Orbis</option>
</select>
</td>
</tr>
<tr>
<td>Price Range:</td>
<td>Min: <input type="text" name="price_1"/> Max:
<input type="text" name="price_2"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="search"></td>
</tr>
</table>
</form>
</div>
Controller
#RequestMapping(value ="/search_1",method = RequestMethod.GET)
public ModelAndView search_1(HttpServletRequest request, HttpServletResponse response) {
String category_id = request.getParameter("category_id");
String publisher_id = request.getParameter("publisher_id");
int price = Integer.parseInt(request.getParameter("price"));
ModelAndView model = new ModelAndView();
model.setViewName("searchResult");
return model;
}
Items bean
package com.jwt.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "items")
public class Items implements Serializable {
private static final long serialVersionUID = -3465813074586302847L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column
private String ISBN;
#Column
private String title;
#Column
private String category_id;
#Column
private String Author;
#Column
private String publisher_id;
#Column
private float price;
#Column
private int stock;
#Column
private int photo_id;
public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
public String getISBN() {
return ISBN;
}
public void setISBN(String ISBN) {
this.ISBN = ISBN;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getcategory_id() {
return category_id;
}
public void setcategory_id( String category_id) {
this.category_id = category_id;
}
public String getAuthor() {
return Author;
}
public void setAuthor(String Author) {
this.Author = Author;
}
public String getpublisher_id() {
return publisher_id;
}
public void setpublisher_id(String publisher_id) {
this.publisher_id = publisher_id;
}
public float getprice() {
return price;
}
public void setprice(float price) {
this.price = price;
}
public int getstock() {
return stock;
}
public void setstock(int stock) {
this.stock = stock;
}
public int getphoto_id() {
return photo_id;
}
public void setphoto_id(int photo_id) {
this.photo_id = photo_id;
}
}
The search has to be done as per the search criteria on the JSP page. The results view can be on the same page. It really doesn't matter,
I am not sure why are you confused, but let's see if I can help.
In your controller, you have to extract all of the criteria correctly then retrieve the list of items using these criteria from your database. Create a method in a service class that takes these criteria as parameter and returns a list of items. Attached that item in model and display in "searchResult.jsp" page.
Here is a rough controller method that should handle your search
#RequestMapping(value = "/search_1", method = RequestMethod.GET)
public ModelAndView search(HttpServletRequest request) {
String categoryId = request.getParameter("category_id");
String publisherId = request.getParameter("publisher_id");
int minPrice = Integer.parseInt(request.getParameter("price_1"));
int maxPrice = Integer.parseInt(request.getParameter("price_2"));
List<Item> items = someService.getItems(categoryId, publisherId, minPrice, maxPrice);
ModelAndView model = new ModelAndView();
model.addObject("items", items);
model.setViewName("searchResult");
return model;
}

save data to the database using spring boot

when I post the data using the postman, the server replies with error code 500. the NetBeans terminal show:(java.sql.SQLIntegrityConstraintViolationException: Column 'email' cannot be null)
bellow my entityclass:
#Entity(name="user")
public class UserEntity {
#Id
#GeneratedValue
private long id;
#Column(nullable = true)
private String userId;
#Column(nullable = true)
private String FirstName;
#Column(nullable = true)
private String LastName;
#Column(nullable = true)
private String Email;
#Column(nullable = true)
private String Password;
#Column(nullable = true)
private String encryptedPassword;
#Column()
private String emailVerificationToken;
#Column()
private Boolean emailVerificationStatus=false;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
public String getEmail() {
return Email;
}
public void setEmail(String Email) {
this.Email = Email;
}
public String getPassword() {
return Password;
}
public void setPassword(String Password) {
this.Password = Password;
}
public String getEncryptedPassword() {
return encryptedPassword;
}
public void setEncryptedPassword(String encryptedPassword) {
this.encryptedPassword = encryptedPassword;
}
public String getEmailVerificationToken() {
return emailVerificationToken;
}
public void setEmailVerificationToken(String emailVerificationToken) {
this.emailVerificationToken = emailVerificationToken;
}
public Boolean getEmailVerificationStatus() {
return emailVerificationStatus;
}
public void setEmailVerificationStatus(Boolean emailVerificationStatus) {
this.emailVerificationStatus = emailVerificationStatus;
}
}
bellow is my service implementation class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.mobile.demo.impl;
import com.example.mobile.demo.DTo.UserDto;
import com.example.mobile.demo.Entity.UserEntity;
import com.example.mobile.demo.repository.UserRepository;
import com.example.mobile.demo.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* #author iphone
*/
#Service
public class UserserviceImpl implements UserService{
#Autowired
UserRepository userRepository;//it is in the data layer so we need the repository to save in the database
#Override
public UserDto createuser(UserDto user) {
UserEntity userentity=new UserEntity();
BeanUtils.copyProperties(user, userentity);
System.out.println("the properties has been copied to the entity");
userentity.setEncryptedPassword("test");
userentity.setUserId("testID");
System.out.println("encryptef passwird and user id has been set");
UserEntity stotedValue=userRepository.save(userentity);
UserDto returnValue=new UserDto();
BeanUtils.copyProperties(stotedValue, returnValue);
return returnValue;
}
}
my model class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.mobile.demo.modoel;
/**
*
* #author iphone
*/
public class Model {
private String FirstName;
private String LastName;
private String Email;
private String Password;
public String getFirstName() {
return FirstName;
}
public void setFistName(String FirstName) {
this.FirstName = FirstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
public String getEmail() {
return Email;
}
public void setEmail(String Email) {
this.Email = Email;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
this.Password = password;
}
}
bellow is what Iam sending in the post request in the postman:
{
"FirstName":"jack",
"LastName":"testjack",
"Password":"124",
"Email":"emailTest#gmail.com"
}
The issue is in json to java Model mapping.
You need to rename your Model.java properties in this way:
Email -> email
FirstName -> firstName
Or add #JsonProperty("name"):
#JsonProperty("email")
private String Email;
Don't forget json changes, if you choose properties renaming:
{
"firstName":"jack",
"lastName":"testjack",
"password":"124",
"email":"emailTest#gmail.com"
}

Want to automatically insert current Date in the table When a post Request is made

I have a User Entity and an Order Entity.
One of the field in order entity is date.
Till now i have the user enter the date.
Now i want that at the time post request is made the date is automatically set to the current date and stored in the database.
Tried using #Prepersist annotation But since this is my first API that i am developing using springBoot , I don't really know how to use it.
User Entity
#Entity
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private BigInteger id;
#NotEmpty(message = "Name is compulsory")
#Pattern(regexp="^[A-Za-z]*[A-Za-z-'. ]*[A-Za-z]*$",message = "Name has invalid characters")
private String username;
//#NotEmpty(message = "Phone Number is compulsary")
#Range(min = 6400000000L ,max=9999999999L)
private Long phoneNumber;
#NotEmpty(message = "Address is compulsary")
private String address;
public User(){}
public User(BigInteger id, String username, Long phoneNumber, String address) {
super();
this.id = id;
this.username = username;
this.phoneNumber = phoneNumber;
this.address = address;
}
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Order Entity
#Entity
public class Orders {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private BigInteger id;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
private Date date;
#ManyToOne
private User user;
public Orders(){}
public Orders(BigInteger id, Date date,BigInteger userId) {
super();
this.id = id;
this.date = date;
this.user=new User(userId," ",0000000000L," ");
}
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Order Controller
#RestController
public class OrdersController {
#Autowired
private OrdersService ordersService;
#ApiOperation(value="Show all orders")
#RequestMapping("/orders")
public Iterable<Orders> getAllOrders()
{
return ordersService.getAllOrders();
}
#ApiOperation(value="Show a particular Order")
#RequestMapping("/orders/{orderId}")
public Orders getOrderById(#PathVariable BigInteger orderId)
{
return ordersService.getOrderById(orderId);
}
#ApiOperation(value="Show all orders of a particular User")
#RequestMapping("/users/{id}/orders")
public List<Orders> getOrders(#PathVariable BigInteger id) {
return ordersService.getOrders(id);
}
#ApiOperation(value="Show an order for a User")
#RequestMapping("/users/{userId}/orders/{id}")
public Orders getOrder(#PathVariable BigInteger id){
return ordersService.getOrder(id);
}
#ApiOperation(value="Adds a new Order")
#RequestMapping(method = RequestMethod.POST,value = "/users/{userId}/orders")
public Orders addOrder(#PathVariable BigInteger userId,#RequestBody Orders orders) {
orders.setUser(new User(userId," ",0000000000L," "));
return ordersService.addOrder(orders);
}
#ApiOperation(value="Alter an Order")
#RequestMapping(method = RequestMethod.PUT, value="/users/{userId}/orders/{id}")
public Orders updateOrder(#RequestBody Orders order,#PathVariable BigInteger id,#PathVariable BigInteger userId)throws Exception {
order.setUser(new User(userId," ",0000000000L," "));
return ordersService.updateOrder(order, id);
}
#ApiOperation(value="Delete an Order")
#RequestMapping(method = RequestMethod.DELETE, value="/orders/{id}")
public void deleteOrder(#PathVariable BigInteger id){
ordersService.deleteOrder(id);
}
}
#PrePersist is a JPA annotation and therefore should work in all compatible persistence frameworks. It indicates a method that should be invoked on particular entity lifecycle event. (Other events are well documented in the Hibernate user guide here).
Add this to your entity:
#Temporal(TemporalType.TIMESTAMP)
#Column(nullable = false)
private Date timestamp;
#PrePersist
private void onCreate() {
timestamp = new Date();
}
As for assigning/creating the entity in the controller, it is a good practice to use DTO (data transfer objects) in your controller (#RequestBody OrderDto orderDto) and then use some method to populate a new entity instance with those values. Most common options are
modelmapper
manually
...
Order o = new Order();
o.user = userDao.findById(orderDto.getUserId());
...
// persist o

Postgres DDL error: 'syntax error at or near "user"' [duplicate]

This question already has answers here:
Cannot create a database table named 'user' in PostgreSQL
(5 answers)
Unable to use table named "user" in postgresql hibernate
(6 answers)
Closed 3 years ago.
i am trying to setup spring boot project by using postgres database. my entities are : -
USER
#Entity
public class User implements UserDetails {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id", nullable = false, updatable = false)
private Long id;
private String username;
private String password;
private String firstName;
private String lastName;
#Column(name="email", nullable = false, updatable = false)
private String email;
private String phone;
private boolean enabled=true;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JsonIgnore
private Set<UserRole> userRoles = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorites = new HashSet<>();
userRoles.forEach(ur -> authorites.add(new Authority(ur.getRole().getName())));
return authorites;
}
#Override
public boolean isAccountNonExpired() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isCredentialsNonExpired() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isEnabled() {
return enabled;
}
}
ROLE
#Entity
public class Role {
#Id
private int roleId;
private String name;
#OneToMany(mappedBy = "role", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private Set<UserRole> userRoles = new HashSet<>();
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
USER_ROLE
#Entity
#Table(name="user_role")
public class UserRole {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long userRoleId;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="user_id")
private User user;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="role_id")
private Role role;
public UserRole(){}
public UserRole(User user, Role role) {
this.user = user;
this.role = role;
}
public Long getUserRoleId() {
return userRoleId;
}
public void setUserRoleId(Long userRoleId) {
this.userRoleId = userRoleId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
and my application.properties file looks like:-
server.port=5060
spring.thymeleaf.cache=false
spring.datasource.url=jdbc:postgresql://localhost:5432/pcms
spring.datasource.data-username=sagar
spring.datasource.password=sagar
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQL94Dialect
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
so whenever i run this application. user_role and role tables are created successfully on postgresql database. but user entity throws an exception.
the error says:-
2018-05-07 15:44:15.847 WARN 23619 --- [ restartedMain] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:424) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:375) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:155) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:312) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:460) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.0.1.RELEASE.jar:2.0.1.RELEASE]
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "user"
Position: 108
as you can see the error points on USER entity. but the same entity runs fine when the application is connected to mysql database. i could not quite figure out what is the real error behind it.
User is actually a reserved keyword that Spring JPA doesn't "escape" as-is. However, you can do the keyword escape like so in your entity declaration:
#Entity
#Table(name = "\"User\"")
public class User implements UserDetails { ... }
Spring is likely escaping it for you in your MySql database or taking care of it for you in some other way; not the case for your PostgreSQL DB.

In spring security 3,how to customize my # PreAuthorize annotation?

these days I meet a problem, I can not figure it out,so please help me...
My entity: Utilisateur this is a french word means user
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
public class Utilisateur implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected int id;
protected String login;
protected String password;
protected String nom;
protected String prenom;
protected String email;
protected String username;}
#OneToOne(mappedBy="user", cascade={CascadeType.ALL})
private Role role;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return login;
}
public void setUsername(String username) {
this.username = username;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
and a Role entity.
In my web app, there is a controller to show for example the information about a student(Etudiant in french)
#EJB(mappedName = "Etudiant.EtudiantFacade")
EtudiantFacade etudiantF;
// Affiche le detail d'un Etudiant (show the infomations of the student)
#RequestMapping(value = "/Etudiant/{idEtudiant}/info")
public ModelAndView detail(#PathVariable String idEtudiant, Model m) {
m.addAttribute("etudiant",
etudiantF.trouver(Integer.parseInt(idEtudiant)));
return new ModelAndView("EtudiantInformation", "null", null);
}
I implemented my own CustomUseDetailService using the entity Utilisateur directly.
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
// TODO Auto-generated method stub
System.out.println("!!!!!!!!!!!!!!!!!");
System.out.println(username);
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
Utilisateur etudiant = etudiantF.trouverParLogin(username);
return new User(etudiant.getLogin(), etudiant.getPassword(), enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,getAuthorities(etudiant.getRole().getRole()));
}
and my security.xml is below:
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/app/Login" access="permitAll"/>
<intercept-url pattern="/app/*" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')"/>
<form-login login-page="/app/Login"
authentication-success-handler-ref="authenticationSuccessHandler"/>
<logout logout-url="/app/Logout" logout-success-url="/"/>
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="customUserDetailsService"/>
</authentication-manager>
Last my question is:
for a student, his id is 1, his username is stu1,to control this student with id 1 can only access his own page information /ProjetName/Student/{studentId}/Info
how do I write the code with #PreAuthorize, I have see the document in form spring, there is example like #PreAuthorize(#contract.name = principal.username), because there is a attribute username in principal, but here,what I need is Id, I use #RequestMapping(value = "/Etudiant/{idEtudiant}/info") to match the student not the username. So how can I solve it? Many thanks... I can not find the tutorial.
You can provide your own implementation for User class (just extend org.springframework.security.core.userdetails.User). Add an identifier field to it. Then set corresponding value in loadUserByUsername method:
#Override
public UserDetails loadUserByUsername(String username)
...
return new CustomUser(etudiant.getId(), etudiant.getLogin(), etudiant.getPassword(), enabled,accountNonExpired,credentialsNonExpired,accountNonLocked,getAuthorities(etudiant.getRole().getRole()));
}
Then you will be able to use it:
#PreAuthorize(#contract.name = principal.id)