Spring security 403 error despite CSRF disabled [duplicate] - java

This question already has answers here:
Springboot Security hasRole not working
(3 answers)
Closed 2 years ago.
I've a set rules where it dictates which roles have access to which url. However, I'm getting 403 at urls where the role should have access to. Please refer below for the code and problem
Log
org.springframework.security.access.AccessDeniedException: Access is
denied at
org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84)
~[spring-security-core-5.3.3.RELEASE.jar:5.3.3.RELEASE] at
org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)
~[spring-security-core-5.3.3.RELEASE.jar:5.3.3.RELEASE] at
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:123)
~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
Spring security configuration. Notice admin/** allows admin usage. I've logged in with admin, going to admin/welcome and it gives me 403.
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
// To access the h2 embedded database
#Autowired
DataSource dataSource;
#Autowired
Securityhandler successHandler;
#Autowired
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.jdbcAuthentication()
// To find logins in the h2 database
.dataSource(dataSource)
.usersByUsernameQuery("select email, password, 'true' as enabled from User where email = ?")
.authoritiesByUsernameQuery("select email, role " +
"from User " +
"where email =?");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/*", "/h2-console/**").permitAll()
.antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.antMatchers("/admin/**").hasRole("ADMIN")
// formLogin redirect to login page
.and().formLogin()
.successHandler(successHandler);
// In order to work with spring security csrf protection needs to be disabled
http.csrf().disable();
http.headers().frameOptions().disable();
}
// To encrypt password
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Admin user created with commandlinerunner so it is automatically created upon running the app. Notice the admin role at the end
#Override
public void run(String... args) throws Exception {
// Creates new user upon running the app
String password = securityConfig.passwordEncoder().encode("github");
User user = new User("Billy", "billy", password, password, "sof#gmail.com", "ADMIN");
userRep.save(user);
System.out.println("Saved user:" + user);
}
Entity class
#Entity
#ValidPassword
public class User {
#Pattern(regexp="[a-zA-Z]+", message = "Enter letters only!")
private String firstName;
#Pattern(regexp="[a-zA-Z]+", message = "Enter letters only!")
private String lastName;
private String password;
private String matchingPassword;
private String passportNumber;
private String address;
private String phoneNumber;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#ValidEmail
private String email;
// Mark as primary key
#Id
// Will be auto generated
#GeneratedValue
private long id;
private String role;
public User(String firstName, String lastName, String password, String passportNumber, String address,
String phoneNumber, String email, String role) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.passportNumber = passportNumber;
this.address = address;
this.phoneNumber = phoneNumber;
this.email = email;
this.role = role;
}
#Override
public String toString() {
return "User [firstName=" + firstName + ", lastName=" + lastName + ", password=" + password
+ ", matchingPassword=" + matchingPassword + ", passportNumber=" + passportNumber + ", address="
+ address + ", phoneNumber=" + phoneNumber + ", email=" + email + ", id=" + id + ", role=" + role + "]";
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMatchingPassword() {
return matchingPassword;
}
public void setMatchingPassword(String matchingPassword) {
this.matchingPassword = matchingPassword;
}
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 getPassportNumber() {
return passportNumber;
}
public void setPassportNumber(String passportNumber) {
this.passportNumber = passportNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setId(long id) {
this.id = id;
}
public User() {
}
public User(String firstName, String lastName, String password, String matchingPassword, String email,
String role) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.matchingPassword = matchingPassword;
this.password = password;
this.email = email;
this.role = role;
}
public long getId() {
return id;
}

Use hasAuthority/hasAnyAuthority instead of hasRole/hasAnyRole or add the prefix ROLE_ when you create the user as #matejko219 wrote in his comment.

Related

Roles in Spring Boot application not working when database auth is used but works if in memory is used

I'm trying to set security roles in my Spring Boot application.
If I use in memory users the roles work. My code looks as folows:
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// add users for in memory authentication
UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication()
.withUser(users.username("paul").password("test123").roles("MEMBER", "ADMIN"))
.withUser(users.username("sandra").password("test123").roles("MEMBER", "ADMIN"))
.withUser(users.username("matthew").password("test123").roles("MEMBER"));
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/users/list").hasAnyRole("MEMBER", "ADMIN")
.antMatchers("/events/list").hasAnyRole("MEMBER", "ADMIN")
.antMatchers("/events/showFormForAdd").hasRole("ADMIN")
.antMatchers("/events/listEventAttendeeDetails*").hasRole("ADMIN")
.antMatchers("/resources/**").permitAll()
.and()
.formLogin()
.loginPage("/showMyLoginPage")
.loginProcessingUrl("/authenticateTheUser")
.permitAll();
}
If I use database authentication for configure() the user is not authorised to access any pages. My database method looks like this:
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
As The roles work for in memory and not database I thing the configure(HttpSecurity http) must work fine. I suspect there is some issue getting my roles. My User and Authority(roles) models are as follows:
#Entity
#Table(name="users")
public class User {
public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();
#OneToMany(mappedBy="user",
cascade={CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH,
CascadeType.REMOVE})
private List<Authority> authorities;
// define fields
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="gender")
private String gender;
#DateTimeFormat(pattern="yyyy-MM-dd")
#Column(name="birth_date")
private LocalDate birthDate;
#Column(name="address_line1")
private String addressLine1;
#Column(name="address_line2")
private String addressLine2;
#Column(name="town")
private String town;
#Column(name="county")
private String county;
#Column(name="country")
private String country;
#Column(name="postcode")
private String postcode;
#Column(name="email")
private String email;
#Column(name="phone")
private String phone;
#Column(name="mobile")
private String mobile;
#Column(name="password")
private #JsonIgnore String password;
#Column(name="enabled")
private int enabled;
// define constructors
public User() {
}
public User(List<Authority> authorities, int id, String firstName, String lastName, String gender, LocalDate birthDate,
String addressLine1, String addressLine2, String town, String county, String country, String postcode,
String email, String phone, String mobile, String password, int enabled) {
this.authorities = authorities;
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.birthDate = birthDate;
this.addressLine1 = addressLine1;
this.addressLine2 = addressLine2;
this.town = town;
this.county = county;
this.country = country;
this.postcode = postcode;
this.email = email;
this.phone = phone;
this.mobile = mobile;
this.password = password;
this.enabled = enabled;
}
public List<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(List<Authority> authorities) {
this.authorities = authorities;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
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 String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = PASSWORD_ENCODER.encode(password);
}
public int getEnabled() {
return enabled;
}
public void setEnabled(int enabled) {
this.enabled = enabled;
}
}
#Entity
#Table(name="authorities")
public class Authority {
#ManyToOne(cascade= {CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH})
#JoinColumn(name="email")
private User user;
#Id
#Column(name="id")
private String email;
#Column(name="authority")
private String authority;
public Authority() {
}
public Authority(User user, String email, String authority) {
this.user = user;
this.email = email;
this.authority = authority;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
}
This is the service I'm using to authenticate:
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired private UserRepository userRepository = null;
#Override
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
org.springframework.security.core.userdetails.User user = null;
try {
Optional<User> optional = userRepository.findByEmail(username);
HashSet<GrantedAuthority> set = new HashSet<>();
/*
* Add SimpleGrantedAuthority to set as appropriate
*/
user = new org.springframework.security.core.userdetails.User(username, optional.get().getPassword(), set);
} catch (UsernameNotFoundException exception) {
throw exception;
} catch (Exception exception) {
throw new UsernameNotFoundException(username);
}
return user;
}
}
The Authorities are inserted into the DB as follows:
INSERT INTO `authorities`
VALUES
('john','ROLE_MEMBER'),
('mary','ROLE_MEMBER'),
('mary','ROLE_MANAGER'),
('susan','ROLE_MEMBER'),
('susan','ROLE_ADMIN');
I put some logging around UserDetailsServiceImpl. As you can see, no authorities are granted.
2020-10-21 17:02:17.612 INFO 20363 --- [nio-8080-exec-4] c.p.clubmanager.aspect.LoggingAspect : =====> in #Before: Calling method: UserDetailsServiceImpl.loadUserByUsername(..)
2020-10-21 17:02:17.613 INFO 20363 --- [nio-8080-exec-4] c.p.clubmanager.aspect.LoggingAspect : =====> argument: Paul_carron#hotmail.com
2020-10-21 17:02:17.619 INFO 20363 --- [nio-8080-exec-4] c.p.clubmanager.aspect.LoggingAspect : =====> in #AfterReturning: from method: UserDetailsServiceImpl.loadUserByUsername(..)
2020-10-21 17:02:17.619 INFO 20363 --- [nio-8080-exec-4] c.p.clubmanager.aspect.LoggingAspect : =====> result: org.springframework.security.core.userdetails.User#eefb770b: Username: Paul_carron#hotmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; **Not granted any authorities**
Is there anything I've done wrong, or may be missing in terms of getting my roles?
In UserDetailsServiceImpl it seems that you are setting Roles/Authority passing only new HashSet<>(). You can try this:
try {
Optional<User> optional = userRepository.findByEmail(username);
List<SimpleGrantedAuthority> authorities = set = new ArrayList<>();
if(optional.isPresent()) {
authorities = optional.get().getAuthorities().stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName()))
.collect(Collectors.toList()))
}
user = new org.springframework.security.core.userdetails.User(username, optional.get().getPassword(), authorities);
} catch (UsernameNotFoundException exception) {
throw exception;
} catch (Exception exception) {
throw new UsernameNotFoundException(username);
}

Spring mvc getting user id from logged user

I am using spring security to login and logout, eveything works fine.
I can get username from logged user fine, however i need userID,
I would like to know how can i get user as an object from logged in user or how could i get userID
#RequestMapping("/contato")
public String contato(Model model, Principal principal ){
String userName = principal.getName();
model.addAttribute("userName",userName);
System.out.println(userName);
return "contato";
}
Bean
import java.sql.Date;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
public class Users {
private int user_id;
#NotBlank
#Size(min=1, max=100, message="Name must be between 1 and 100 characters")
private String firstname;
#NotBlank
private String surname;
#NotNull
private Date dob;
#NotBlank
#Email
private String username;
#NotBlank
private String telephone;
#NotBlank
private String address;
#NotBlank
private String city;
#NotBlank
private String country;
#NotBlank
private String postcode;
#NotBlank
#Size(min=6, message="Password must be have more than 6 characters")
private String password;
private boolean enabled = false;
private String authority;
public Users() {
}
public Users(int user_id, String firstname, String surname, Date dob, String username, String telephone,
String address, String city, String country, String postcode, String password, boolean enabled,
String authority) {
super();
this.user_id = user_id;
this.firstname = firstname;
this.surname = surname;
this.dob = dob;
this.username = username;
this.telephone = telephone;
this.address = address;
this.city = city;
this.country = country;
this.postcode = postcode;
this.password = password;
this.enabled = enabled;
this.authority = authority;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
}
Can anyone please help me to get user id from logged user
I have also tried using
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Users user =(Users)authentication.getPrincipal();
but it still did not work
The simplest approach would be to leverage the UserDetails and UserDetailsService interfaces.
Write a simple UserDetailsService:
#Service
public class CustomUserDetailsService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return findUserByUsername(username); //load the user from somewhere (e.g. Database)
}
}
Have your Users class implement the UserDetails interface:
public class Users implements UserDetails {
private String username;
private String userId;
private String password;
private String role;
public Users(String username, String userId, String password, String role) {
this.username = username;
this.userId = userId;
this.password = password;
this.role = role;
}
//...
}
Finally, when you call this static method you'll receive the Users object from which you can extract the userId:
Users user = (Users) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

verify if an email is already in my database, using hibernate

I need to verify the email of the new user who would like to sign up in my application web. if the email is already in my database (mysql) so must don't accept this sign up and said said to him like: "your email already used".
Now I can save users in my database, but how to check them by his email for not repeat the inscription in my application web.
this is my Dao layer class :
public class UserDaoMysql implements UserDao {
private Session session;
private void openSession(){
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
}
private void closeSession(){
session.getTransaction().commit();
session.close();
}
public void insert(User user) {
if(checkEmail(user)){
openSession();
User p = new User(user.getName(), user.getEmail(), user.getPassword());
session.save(p);
System.out.println("sauvegarde reussi");
closeSession();
}
}
public boolean checkEmail(User user){
return true;
}
}
this is my user bean :
#ManagedBean(name="user")
public class User {
private int id;
private String name;
private String email;
private String password;
private String confirmationPass;
// private image
public User() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 getConfirmationPass() {
return confirmationPass;
}
public void setConfirmationPass(String confirmationPass) {
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password,
String confirmationPass) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
public User(String name, String email, String password) {
super();
this.name = name;
this.email = email;
this.password = password;
}
#Override
public String toString() {
return "User [id=" + id + ", Name=" + name + ", email=" + email
+ ", password=" + password + "]";
}
public void save(){
UserBusiness userBusiness = new UserBusinessImp();
userBusiness.add(new User(name, email,password));
}
}
And I created a table "user" in my database.
Maybe there is an annotation which can help us to specify the email property as an unique one or something else.
What you can do is create a unique key on your email column in your table. After that, decorate your field using #Column(unique=true), that will indicate to Hibernate that this field has a unique key.
Also, be careful with your annotations. This is unrelated to your problem, but #ManagedBean marks the class as a bean able to interact with the view in JSF. Probably you want/need to use #Entity instead.

check if an email in my database while sign up, using hibernate

I am programming an IHM for sign up the users, I need to check if this user is already in database(mysql), checking by his email . can you help me please.
I can save my user now but how to check if this user by his email
this is my Dao layer class :
public class UserDaoMysql implements UserDao {
private Session session;
private void openSession(){
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
}
private void closeSession(){
session.getTransaction().commit();
session.close();
}
public void insert(User user) {
if(checkEmail(user)){
openSession();
User p = new User(user.getName(), user.getEmail(), user.getPassword());
session.save(p);
System.out.println("sauvegarde reussi");
closeSession();
}
}
public boolean checkEmail(User user){
return true;
}
}
this is my user bean :
#ManagedBean(name="user")
public class User {
private int id;
private String name;
private String email;
private String password;
private String confirmationPass;
// private image
public User() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 getConfirmationPass() {
return confirmationPass;
}
public void setConfirmationPass(String confirmationPass) {
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password,
String confirmationPass) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
public User(String name, String email, String password) {
super();
this.name = name;
this.email = email;
this.password = password;
}
#Override
public String toString() {
return "User [id=" + id + ", Name=" + name + ", email=" + email
+ ", password=" + password + "]";
}
public void save(){
UserBusiness userBusiness = new UserBusinessImp();
userBusiness.add(new User(name, email,password));
}
}
And I have a table user in my database.
thanks for your help in advance
I would use NamedQuery for this. Define named query in your User entity like this:
...
#NamedQueries({
#NamedQuery(name = "User.findByEmail",
query = "SELECT u FROM User u WHERE u.email = :email")})
#ManagedBean(name="user")
public class User {
...
And then add method like this to your DAO
public List<User> getUsersByEmail(String email){
openSession();
Session session;
Query query = session.getNamedQuery("User.findByEmail");
query.setString("email", email);
Lis<Users> users = query.list();
closeSession();
return users;
}
This method is little bit more generic you can make it more specific returning user count only.

Logging In With JSP Hibernate

I have a problem with Hibernate to make login process. All codes are perfectly correct in terms of syntax. NetBeans tell me that my code have no problem. However, when I run the web, and I test the login process, it doesn't reacting and the address is stucked on the doLogin.
All classes have been mapped correctly.
This is my problem: when I try to retrieve data, my code is stucked on a line.
on doLogin servlet (I use the template provided by NetBeans and just filling in my code on the try. Here's in brief:
Connect con = new Connect(); //my code is stucked on this line.
//I've done testing where's the cause of the stuck, and this line is the cause.
List logger = con.getLogin(username, password);
and to make it clear:
Connect.java
public class Connect {
Session sesi;
public Connect() {
sesi = HibernateUtil.getSessionFactory().openSession();
}
public List getLogin(String username, String password){
return sesi.createQuery("from MsUser WHERE username = '"+username+"' and password = '"+password+"'").list();
}
}
and since that query is HQL, here is the MsUser class:
public class MsUser {
public MsUser() {
}
private int userID;
private String username;
private String firstname;
private String lastname;
private String email;
private String password;
private String gender;
private String address;
private String phone;
private String photo;
public MsUser(int userID, String username, String firstname, String lastname, String email, String password, String gender, String address, String phone, String photo) {
this.userID = userID;
this.username = username;
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.password = password;
this.gender = gender;
this.address = address;
this.phone = phone;
this.photo = photo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public int getUserID() {
return userID;
}
public void setUserID(int userID) {
this.userID = userID;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
please help. But I suspect on Connect's constructor as the main cause. Anybody can suggest or fix or tell me what causing me this.
appendix:
HibernateUtil.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
/**
* Hibernate Utility class with a convenient method to get Session Factory
* object.
*
* #author Ginanjar
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
You can try following code in your hibernateUtil.java file:
SessionFactory factory = new Configuration().configure().buildSessionFactory();
session = factory.openSession();
String query = "select reg.username,reg.password from MsUser as reg where reg.username='" + username + "' and reg.password='" + password + "'";
Query DBquery = session.createQuery(query);
for (Iterator it = DBquery.iterate(); it.hasNext();) { it.next();
count++;
}
System.out.println("Total rows: " + count);
if (count == 1) {
return true;
} else {
return false;
}
}

Categories

Resources