I am currently in the process of developing a web application in Java using Spring Boot.
What I am using for the app:
- MySQL as Data source
- Hibernate JPA for ORM
- Thymeleaf for templating
Currently my database has a table for users and roles. Login, registration and sessions are working fine.
I have created an admin-only page on the site.
I am having issues with creating and using roles for users.
I'd like to have a role for every user in the DB and be able to use it on the site. The default role on registration would be "USER", and I would be able to manually change an user's role to "ADMIN" in the MySQL admin.
This is currently my User entity class:
@Entity
@Table(name = "user")
public class User extends Auditable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "email", nullable = false, unique = true)
@Email(message = "Please provide a valid e-mail")
@NotEmpty(message = "Please provide an e-mail")
private String email;
@Column(name = "password")
@Transient
private String password;
@Column(name = "first_name")
@NotEmpty(message = "Please provide your first name")
private String firstName;
@Column(name = "last_name")
@NotEmpty(message = "Please provide your last name")
private String lastName;
@Column(name = "enabled")
private boolean enabled;
@Column(name = "confirmation_token")
private String confirmationToken;
@OneToOne(mappedBy="user", cascade={CascadeType.ALL})
private Role role;
public User() {
}
public User(String firstName, String lastName, String email, String password, Role role) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.role = role;
}
/** Getters and setters */
}
This is my Role entity:
@Entity(name="role")
public class Role {
@Id
private Long id;
@OneToOne
private User user;
private Integer role;
/** Getters and setters */
}
Load by username in UserService:
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = userRepository.findByEmail(email);
if (user == null){
throw new UsernameNotFoundException("Invalid username or password.");
}
return new org.springframework.security.core.userdetails.User(user.getEmail(),
user.getPassword(), getAuthorities(user.getRole().getRole()));
}
But for some reason this is not working. It creates the "role" table in the DB, and it has two rows in it
id name
1 ROLE_USER
2 ADMIN
Question is, what do I need to do when I am saving the user to the DB in order to set a role for the user I am saving? Currently none of the user rows in my table have a role column. And how can I make it work so that when I have a rule in my securityconfig;
.hasRole("ADMIN")
It won't allow an user without that role to access? Currently when I try to access the page with that rule, it always returns the no access page I've configured.