Password Encoder Match not working Spring boot - spring

i am creating the Spring Boot application login with hash password.without set hash password login working successfully.with hash password set getting error while writing the code.
passwordEncoder.matches(loginDTO.getEmail())
it indicate the error was
'matches(java.lang.CharSequence, java.lang.String)' in 'org.springframework.security.crypto.password.PasswordEncoder' cannot be applied to '(java.lang.String)'
what i tried so far i attached the full code below.
LoginDTO.java
package com.example.Registation.Dto;
public class LoginDTO {
private String email;
private String password;
public LoginDTO() {
}
public LoginDTO(String email, String password) {
this.email = email;
this.password = password;
}
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;
}
#Override
public String toString() {
return "LoginDTO{" +
"email='" + email + '\'' +
", password='" + password + '\'' +
'}';
}
}
EmployeeController.java
#PostMapping(path = "/login")
public String loginEmployee(#RequestBody LoginDTO loginDTO)
{
String email = employeeService.loginEmployee(loginDTO);
return email;
}
Employee Service
public interface EmployeeService {
String loginEmployee(LoginDTO loginDTO);
}
EmployeeRepo
#EnableJpaRepositories
#Repository
public interface EmployeeRepo extends JpaRepository<Employee,Integer>
{
Optional<Employee> findOneByEmailAndPassword(String email, String password);
}
EmployeeIMPL
#Override
public String loginEmployee(LoginDTO loginDTO) {
CharSequence password = loginDTO.getPassword();
String encodedPassword = loginDTO.getPassword(); // assume this is the encoded password from the database
Optional<Employee> employee = employeeRepo.findOneByEmailAndPassword(loginDTO.getEmail(), passwordEncoder.matches(password,encodedPassword));
if (employee.isPresent()) {
return "Login Success for " + employee.get();
} else {
return "Login Fail";
}
}
}

import org.springframework.security.crypto.password.PasswordEncoder;
//PasswordEncoder bean
#Autowired
private PasswordEncoder passwordEncoder;
//check password
if (passwordEncoder.matches(changePasswordRequest.getOldPassword(), user.getPassword())){
}
Both password type is String.
OldPassword and Password type is String.

Related

I can't get an entity ID in spring boot

I am learning Spring-Boot and I'm doing a little project to practice, but I have a problem.
This is a simple authentication app, you can register and log in. My aim is: If you log in your username should be appeared, and for further functions I need the ID as well.
So I have this code:
#PostMapping("/main")
public String login(#ModelAttribute Users user, Model model) {
time = sdf.format(new Date());
Users correctUser = serv.selectUser(user.getName(), user.getPassword());
if (correctUser != null) {
//Users data
login_name = user.getName();
actual_user_id = user.getId();
model.addAttribute("given_name", login_name);
System.out.println("DEBUG: " + user);
System.out.println(time + " Successful");
return "main_screen";
} else {
System.out.println(time + " Log in failed");
return "error_page";
}
}
I can get and storage the name well in login_name, but with the ID I have some problems. As you can see I use user.getId() same as with name, but either way I get null and can't storage the ID in my actual_user_id variable.
Here is my repository:
#Repository
public interface UserRepository extends JpaRepository<Users, Integer> {
Optional<Users> findFirstByName(String name);
Optional<Users> findUserByNameAndPassword(String name, String password);
}
And my service method:
public Users authentication(String name, String password) {
return repo.findUserByNameAndPassword(name, password).orElse(null);
}
EDIT: And this is my Users class
#Entity
#Table(name = "users")
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String password;
private String email;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Users{" +
"id=" + id +
", name='" + name + '\'' +
", passowrd='" + password + '\'' +
", email='" + email + '\'' +
'}';
}
}
I think it should work, but I can't find the problem.
Can anyone help me?
As I can see, I get the name and the password with the findUserByNameAndPassword() and nothing else, however I should I suppose.
You look to be trying to get your id from the user passed to you in the post request:
actual_user_id = user.getId();
Try getting your information from the user you retrieved from the database:
actual_user_id = correctUser.getId();

Foregine key is not updating in spring boot Jpa

Basically, I am trying to establish a relationship between my two tables using spring boots.
And the relationship which I had used was the #onetoone and #onetomany relationship.
But after building the relationship and creating the table in MySQL whenever I run the program my foreign key is not updating.
The relationship is one user can have many contacts. I have tried unidirectional as well as bidirectional mapping but it is not working.
I want in contact table there will be a separate column for the foreign key. Based on that key I will show all contacts for that particular user.
This is my contact entity...
package com.example.jpa.contactEntities;
#Entity
#Table(name = "Contact")
public class ContactEntities {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long c_id;
private String c_name;
private String second_c_name;
private String c_work;
private String c_emali;
private String c_phone;
private String c_image;
#Column(length = 5000)
private String c_description;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "contact_id")
private UserEntities userEntities;
public ContactEntities() {
super();
}
public ContactEntities(long c_id, String c_name, String second_c_name, String c_work, String c_emali,
String c_phone, String c_image, String c_description, UserEntities userEntities) {
super();
this.c_id = c_id;
this.c_name = c_name;
this.second_c_name = second_c_name;
this.c_work = c_work;
this.c_emali = c_emali;
this.c_phone = c_phone;
this.c_image = c_image;
this.c_description = c_description;
this.userEntities = userEntities;
}
public long getC_id() {
return c_id;
}
public void setC_id(int c_id) {
this.c_id = c_id;
}
public String getC_name() {
return c_name;
}
public void setC_name(String c_name) {
this.c_name = c_name;
}
public String getSecond_c_name() {
return second_c_name;
}
public void setSecond_c_name(String second_c_name) {
this.second_c_name = second_c_name;
}
public String getC_work() {
return c_work;
}
public void setC_work(String c_work) {
this.c_work = c_work;
}
public String getC_emali() {
return c_emali;
}
public void setC_emali(String c_emali) {
this.c_emali = c_emali;
}
public String getC_phone() {
return c_phone;
}
public void setC_phone(String c_phone) {
this.c_phone = c_phone;
}
public String getC_image() {
return c_image;
}
public void setC_image(String c_image) {
this.c_image = c_image;
}
public String getC_description() {
return c_description;
}
public void setC_description(String c_description) {
this.c_description = c_description;
}
public UserEntities getUserEntities() {
return userEntities;
}
public void setUserEntities(UserEntities userEntities) {
this.userEntities = userEntities;
}
#Override
public String toString() {
return "ContactEntities [c_id=" + c_id + ", c_name=" + c_name + ", second_c_name=" + second_c_name + ", c_work="
+ c_work + ", c_emali=" + c_emali + ", c_phone=" + c_phone + ", c_image=" + c_image + ", c_description="
+ c_description + ", userEntities=" + userEntities + "]";
}
}
this is my user entity...
package com.example.jpa.userEntities;
#Entity
#Table(name = "UserEntities")
public class UserEntities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long userId;
#NotBlank
#Size(min = 2, max = 20)
private String userName;
#NotBlank
#Column(unique = true)
#Email(regexp = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$")
private String userEmail;
#NotNull(message = "password should not be blank")
private String userPass;
private boolean enable;
private String role;
#Column(length = 500)
private String userAbout;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "userEntities", orphanRemoval = true)
private List<ContactEntities> contactList = new ArrayList<>();
public UserEntities() {
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public String getRoll() {
return role;
}
public void setRoll(String role) {
this.role = role;
}
public String getUserAbout() {
return userAbout;
}
public void setUserAbout(String userAbout) {
this.userAbout = userAbout;
}
public List<ContactEntities> getContactList() {
return contactList;
}
public void setContactList(List<ContactEntities> contactList) {
this.contactList = contactList;
}
#Override
public String toString() {
return "UserEntities [userId=" + userId + ", userName=" + userName + ", userEmail=" + userEmail + ", userPass="
+ userPass + ", enable=" + enable + ", role=" + role + ", userAbout=" + userAbout + ", contactList="
+ contactList + "]";
}
}
Repository of Contact
package com.example.jpa.repo;
import java.util.List;
import com.example.jpa.contactEntities.ContactEntities;
public interface ContactRepo extends JpaRepository<ContactEntities, Integer> {
#Query("from ContactEntities as c where c.userEntities.userId=:u_Id")
public List<ContactEntities> findContactsByUser(#Param("u_Id") long l);
}
Repository of User
package com.example.jpa.repo;
import com.example.jpa.userEntities.UserEntities;
#EnableJpaRepositories
public interface UserRepository extends JpaRepository<UserEntities, Integer> {
#Query("select u from UserEntities u where u.userEmail=:userEmail")
public UserEntities getUserByUserName(#Param("userEmail") String userEmail);
}
User controller
package com.example.jpa.controller;
#Controller
#RequestMapping("/user")
public class UserController {
#Autowired
private UserRepository userRepository;
#Autowired
private ContactRepo contactRepo;
#ModelAttribute
public void addCommonData(Model model, Principal principal) {
String username = principal.getName();
System.out.println("UserName:-" + username);
UserEntities userEntities = this.userRepository.getUserByUserName(username);
System.out.println("User:- " + userEntities);
model.addAttribute("userEntities", userEntities);
}
//dash board home
#RequestMapping("/index")
public String dashboard(Model model, Principal principal) {
return "normal/user_dashboard";
}
// open add form handler
#GetMapping("/add-contact")
public String openAddContactForm(Model model) {
model.addAttribute("title", "Add contact");
model.addAttribute("contactEntitie", new ContactEntities());
return "normal/add_contact";
}
// processing and contact form
#PostMapping("/upload")
public String processContact(#ModelAttribute ContactEntities contactEntitie,
#RequestParam("userImage") MultipartFile multipartFile, Principal principal, Model model,
HttpSession session) {
try {
model.addAttribute("contactEntitie", new ContactEntities());
String name = principal.getName();
UserEntities userEntities = userRepository.getUserByUserName(name);
userEntities.getContactList().add(contactEntitie);
// processing and uploading file....
if (multipartFile.isEmpty()) {
System.out.println("File is empty");
} else {
// upload the the file and update
contactEntitie.setC_image(multipartFile.getOriginalFilename());
File saveFile = new ClassPathResource("static/img").getFile();
// bring the folder path...
Path path = Paths
.get(saveFile.getAbsolutePath() + File.separator + multipartFile.getOriginalFilename());
Files.copy(multipartFile.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Image is uploaded");
}
userRepository.save(userEntities);
System.out.println("Datas are :" + contactEntitie);
// message success
session.setAttribute("message", new Messages("Your Contact is added !!! Add more...", "success"));
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
// error message
session.setAttribute("message", new Messages("Something went wrong !!! Try Again", "danger"));
}
return "normal/add_contact";
}
// show Contact handler
#GetMapping("/show-contacts")
public String showContact(Model model, Principal principal) {
model.addAttribute("title", "Show Contacts");
String userName = principal.getName();
UserEntities userEntities = userRepository.getUserByUserName(userName);
List<ContactEntities> contactList = contactRepo.findContactsByUser(userEntities.getUserId());
model.addAttribute("contactList", contactList);
return "normal/show_contacts";
}
}
All configuration class
User Details configuration
package com.example.jpa.Myconfiguration;
public class UserDetailsServiceImple implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// fetching data from DB
UserEntities userEntities = userRepository.getUserByUserName(username);
if (userEntities == null) {
throw new UsernameNotFoundException("Could not found user !!!");
}
CustomUserDetails customUserDetails = new CustomUserDetails(userEntities);
return customUserDetails;
}
}
package com.example.jpa.Myconfiguration;
public class CustomUserDetails implements UserDetails {
private UserEntities userEntities;
public CustomUserDetails(UserEntities userEntities) {
super();
this.userEntities = userEntities;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(userEntities.getRoll());
return List.of(simpleGrantedAuthority);
}
#Override
public String getPassword() {
return userEntities.getUserPass();
}
#Override
public String getUsername() {
return userEntities.getUserEmail();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
Application property:-
#Database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/smartcontact
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.NonRegisteringDriver
spring.jpa.properties.hibernate.dilact=org.hibernate.dialect.Mysql8Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=2KB
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

Get actual user details with spring boot

Actually I´m working in a forum project built with Spring boot, Mongodb and Vue.js.
When I´m trying to post a new comment and get the user datails with the SecurityContextHolder and cast it to my UsersDetailImpl who implements from the UserDetails class provided by Spring boot, it throw the following error: org.springframework.security.web.authentication.webauthenticationdetails cannot be cast to .... UserDetailsImpl
I don´t really know the reason of this error becasuse if I test it from Postman does not report an error.
UserDetailsImpl.java
public class UserDetailsImpl implements UserDetails {
private static final long serialVersionUID = 1L;
private String id;
private String username;
private String email;
#JsonIgnore
private String password;
private Collection<? extends GrantedAuthority> authorities;
public UserDetailsImpl(String id, String username, String email, String password,
Collection<? extends GrantedAuthority> authorities) {
this.id = id;
this.username = username;
this.email = email;
this.password = password;
this.authorities = authorities;
}
public static UserDetailsImpl build(User user) {
List<GrantedAuthority> authorities = user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getName().name()))
.collect(Collectors.toList());
return new UserDetailsImpl(
user.getId(),
user.getUsername(),
user.getEmail(),
user.getPassword(),
authorities);
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public String getId() {
return id;
}
public String getEmail() {
return email;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getUsername() {
return username;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
UserDetailsImpl user = (UserDetailsImpl) o;
return Objects.equals(id, user.id);
}
}
CommentController.java
#CrossOrigin(origins = "*", maxAge = 3600)
#RestController
#RequestMapping("/comments")
public class CommentController {
#Autowired
CommentRepository commentRepository;
#Autowired
RoleRepository roleRepository;
#PostMapping("/ask")
public ResponseEntity<?> ask (#Valid #RequestBody AskRequest askRequest) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
HashSet<String> strRoles = userDetails.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toCollection(HashSet::new));
Set<Role> roles = new HashSet<>();
strRoles.forEach(role -> {
int cutPoint = role.indexOf("_");
role = role.substring(cutPoint + 1).toLowerCase();
findRole(roles, role, roleRepository);
});
User user = new User(userDetails.getUsername(), userDetails.getEmail(), roles);
ObjectId discussion_id = ObjectId.get();
String slug = new Slugify().slugify(askRequest.getTitle());
Comment comment = new Comment(discussion_id, askRequest.getTitle(),
askRequest.getText(),slug, "full_slug_test", Instant.now(),user);
String info = comment.getDiscussion_id().toString() + comment.getPosted() + comment.getTitle()
+ comment.getText() + comment.getAuthor().getUsername() + comment.getAuthor().getEmail()
+ comment.getAuthor().getId() + comment.getAuthor().getRoles();
commentRepository.save(comment);
return ResponseEntity.ok(new MessageResponse(info));
}
}
I´m new in all this technologies there may be serious errors. All the advices will be a great help to me because the project is academic.
If someone need more information just ask for it.
Thank you all :)
Change authentication.getDetails() to getAuthentication().getPrincipal()
You will have:
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
Finally I found the error and it was in the front-end side. I was sending de headers with the JWT in this way.
import axios from 'axios';
import authHeader from './auth-header';
const API_URL = 'http://localhost:8080/comments/';
class CommentsService {
ask(post){
return axios.post(API_URL + 'ask', {
title: post.title,
text: post.text,
headers: authHeader()
});
}
}
export default new CommentsService();
and it is totally wrong so I found the manner to do it.
import axios from 'axios';
import authHeader from './auth-header';
const API_URL = 'http://localhost:8080/comments/';
class CommentsService {
ask(post){
return axios.post(API_URL + 'ask', {
title: post.title,
text: post.text
},{headers: authHeader()});
}
}
export default new CommentsService();
I also add the code to mount the headers.
export default function authHeader() {
let user = JSON.parse(localStorage.getItem('user'));
if (user && user.accessToken) {
return { Authorization: 'Bearer ' + user.accessToken };
} else {
return {};
}
}

Loading application Properties Spring-boot getting null values

I was trying read the properties from application.properties files using
#ConfigurationProperties getting null values for the variables, tried Using #Value Also having the same issue with that. Is There any other way to load the properties into application
#Component
#ConfigurationProperties(prefix = "email")
public class EmailProperties {enter code here
private String host;
private String port;
private String username ;
private String password;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
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;
}
#Override
public String toString() {
return "EmailProperties [host=" + host + ", port=" + port + ", username=" + username + ", password=" + password
+ "]";
}
properties file
email.host=test
email.port=25
email.username=Test
email.password=Test
Method where Using Those properties
#Autowired
private EmailProperties emailProperties;
#SuppressWarnings("unused")
public void sendMail( String toEmail, String messageSubject, String messageBody) {
System.out.println("host");
Properties prop = new Properties();
prop.put("mail.smtp.auth", false);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", emailProperties.getHost());
prop.put("mail.smtp.port", emailProperties.getPort());
prop.put("mail.smtp.ssl.trust", emailProperties.getHost());

DuplicateKeyException in mongodb and spring boot

I am using Spring Boot and MongoDB and I am able to store a document in MongoDB successfully. When I was trying to insert a second document, it is showing duplicatekeyexception. The total message of exception is as follows:
com.mongodb.DuplicateKeyException: Write failed with error code 11000
and error message 'E11000 duplicate key error collection:
Football_Admin.SignUp index: id dup key: { : 0 }'
The code is as follows:
SignUpRepository.java
package com.admin.Repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.admin.Model.SignUp;
#Repository
public interface SignUpRepository extends MongoRepository<SignUp,String>{
}
Controller
#Controller
#RequestMapping("/SignIn_Up")
public class HomeController {
#Autowired
SignUpRepository repository;
#RequestMapping(value = "/addadmin", method = RequestMethod.POST)
public String addAdmin(#ModelAttribute("SignUp") SignUp sign) throws NoSuchAlgorithmException,InvalidKeySpecException {
String originalPassword = sign.getPassword();
String generatedSecuredPasswordHash = generateStorngPasswordHash(originalPassword);
String email = sign.getEmail();
String fullname = sign.getFullName();
try {
sign.setEmail(email);
sign.setFullName(fullname);
sign.setPassword(generatedSecuredPasswordHash);
repository.save(sign);
}
catch (DuplicateKeyException e) {
e.printStackTrace();
}
System.out.println(generatedSecuredPasswordHash);
System.out.println("Email name is:"+sign.getEmail());
System.out.println("Full Name is:"+sign.getFullName());
System.out.println("Password is:"+sign.getPassword());
return "welcome";
}
Entity
package com.admin.Model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection="SignUp")
public class SignUp {
#Id
private int id;
private String fullName;
private String email;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString() {
return id+""+fullName+""+password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
MongoDb driver don't know how to create a unique Id of type int when inserting so you received unique index exception
So either you manually create and maintain your index (quite hard) or change your id field type to ObjectId

Resources