Spring: password encryption [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Here's my view:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Регистрация</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Oswald|Roboto|Roboto+Condensed" rel="stylesheet">
<link href="../static/css/form.css" rel="stylesheet" th:href="#{/css/form.css}">
</head>
<body>
<div id="wrapper">
<div id="register_main_wrapper">
<form action="#" th:action="#{/register}" th:object="${user}" method="post">
<div id="register_form_wrapper">
<div id="register_text_wrapper">
<h1 id="register_text">Создайте учётную запись</h1>
</div>
<div id="email_desc_reg_wrapper" class="desc_text">
<a>ЭЛЕКТРОННАЯ ПОЧТА</a>
</div>
<div id="email_input_reg_wrapper">
<input th:field="*{userEmail}" type="email" size="35" class="input_fields">
</div>
<div id="nickname_desc_reg_wrapper" class="desc_text">
<a>ИМЯ ПОЛЬЗОВАТЕЛЯ</a>
</div>
<div id="nickname_input_reg_wrapper">
<input th:field="*{userNick}" type="text" size="35" class="input_fields">
</div>
<div id="password_desc_reg_wrapper" class="desc_text">
<a>ПАРОЛЬ</a>
</div>
<div id="password_input_reg_wrapper">
<input th:field="*{userPass}" type="password" size="35" class="input_fields">
</div>
<div id="register_button_wrapper">
<button class="form_btn" id="register_button" type="submit" value="Submit">Регистрация</button>
</div>
<div id="login_switch_wrapper">
Вход
</div>
</div>
</form>
</div>
</div>
</body>
</html>
When I press submit, all attributes(pass,nick,email) goes to my controller, there is a part of it
#RequestMapping(value="/register", method=RequestMethod.GET)
public ModelAndView displayRegistration(ModelAndView modelAndView, User user)
{
modelAndView.addObject("user", user);
modelAndView.setViewName("register");
return modelAndView;
}
#RequestMapping(value="/register", method=RequestMethod.POST)
public ModelAndView registerUser(ModelAndView modelAndView, User user)
{
User existingUser = userRepository.findByUserEmailIgnoreCase(user.getUserEmail());
if(existingUser != null)
{
modelAndView.addObject("message","This email already exists!");
modelAndView.setViewName("error");
}
else
{
userRepository.save(user);
I need to add password encryption to my app, so, as far as I know, I need to extract the password attribute from the model object, encrypt it and put it back. How can I extract attributes and return them to the model object?

You can get the password from user , encrypt it with Spring encoder then set it again as a user password, your code will be like this :
//import the Spring encoder
import org.springframework.security.crypto.password.PasswordEncoder;
#RequestMapping(value="/register", method=RequestMethod.POST)
public ModelAndView registerUser(ModelAndView modelAndView, User user) {
// creating the instance class to use it
private final PasswordEncoder passwordEncoder;
User existingUser =userRepository.findByUserEmailIgnoreCase(user.getUserEmail());
if(existingUser != null)
{
modelAndView.addObject("message","This email already exists!");
modelAndView.setViewName("error");
}
else
{ //encrypt the password here
String encryptedPassword = passwordEncoder.encode(user.getPassword());
user.setPassword(encryptedPassword);
userRepository.save(user);
You can find more in Spring docs about PasswordEncoder Interface

Related

Trying to get my login page to respond properly to invalid/valid inputs

I am currently trying to get my login page (using spring boot/Thymeleaf) to respond to invalid inputs (wrong email/password) by showing the same page but with an additional message saying "Email or Password is incorrect". Its not working thus far, and it seems like my controller isn't even interacting with the inputs at all. The reason I think this is because when I submit invalid inputs it doesn't return to /login like it is specified in the controller's Post method, instead it goes to "http://localhost:3307/login?error", which makes me think that the controller's post method isn't working at all. Here is my html code (using some bootstrap template) and my UserController.
HTML code (its maybe a little messy)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta charset="ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<div id="login">
<h3 class="text-center text-white pt-5">Login form</h3>
<div class="container">
<div id="login-row" class="row justify-content-center align-items-center">
<div id="login-column" class="col-md-6">
<div id="login-box" class="col-md-12">
<h3 class="text-center text-info">Login</h3>
<form id="login-form" class="form" th:action="#{/login}" th:object="${user}" method="post">
<p th:if="${invalidCredentials}" class="error">Email or Password is incorrect</p>
<div class="form-group">
<label for="email" class="text-info">Email:</label><br>
<input type="text" name="email" id="email" class="form-control">
</div>
<div class="form-group">
<label for="password" class="text-info">Password:</label><br>
<input type="text" name="password" id="password" class="form-control">
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-info btn-md" value="submit">
</div>
<div id="register-link" class="text-right">
Register here
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
My Controller Class
#Controller
public class UserController {
UserRepository userRepo;
UserService userService;
#GetMapping("/login")
public String login(Model model) {
User user=new User();
model.addAttribute("user", user);
return "login";
}
#PostMapping("/login")
public String loginUser(#ModelAttribute("user") User user, Model model) {
//Checking if User exists and if information is correct
if(userRepo.findByEmail(user.getEmail()).isPresent()) {
UserDetails userDetails = userService.loadUserByUsername(user.getEmail());
//Wrong PassWord
if(!userDetails.getPassword().equals(user.getPassword())) {
model.addAttribute("invaldCredentials", true);
return "login";
}
//Correct info given, redirecting to home page
else {
return "home";
}
}
//No existing User affiliated with given Email
model.addAttribute("invalidCredentials", true);
return "login";
}
}
My WebSecurityConfigurations
#Configuration
#EnableWebSecurity
public class WebSecurityConfig {
private final UserService userService;
private final BCryptPasswordEncoder passwordEncoder;
public WebSecurityConfig(UserService userService, BCryptPasswordEncoder passwordEncoder) {
this.userService = userService;
this.passwordEncoder = passwordEncoder;
}
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests()
.antMatchers("/registration/**", "/login")
.permitAll()
.anyRequest()
.authenticated().and()
.formLogin().loginPage("/login").permitAll();;
return http.build();
}
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
}
#Bean
public DaoAuthenticationProvider daoAutenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(passwordEncoder);
provider.setUserDetailsService(userService);
return provider;
}
}
In case of a login error, you can tell Spring to redirect to another page that'll handle the error (this is done when configuring the Spring web security)
....
.authenticated().and()
.formLogin().loginPage("/login").permitAll().failureUrl("/loginFailure")
If you don't specify a page for failed logins, Spring will simply return your login page with an error parameter (e.g /login?error ), You can access this parameter in Thymeleaf and display the error to the user then.
<div th:if="${param.error != null}" >
<span >Wrong credentials </span>
</div>
Also, there's no need to write your endpoint (loginUser in this case) to handle the login process as Spring will do this automatically for you provided that you've set up the AuthenticationManager properly.

Thymeleaf th:text does not work in some case

I started to work with thymeleaf in a basic project. When I want to display a message in the sign up page the th:text does not work. I used already th:text in other .html files and it works there but in the signUp.html doesn't.
Here is my controller where I set the message:
package com.teszt.thymeleaftest.controller;
#Controller
#RequestMapping("/login")
#AllArgsConstructor
public class MemberController {
MembersService membersService;
#GetMapping("/login")
public String showLoginPage(){
return "/login/login";
}
#GetMapping("/signUp")
public String showSignUpPage(Model theModel){
Members theMember = new Members();
theModel.addAttribute("member", theMember);
return "/login/signUp";
}
#PostMapping("/save")
public String saveMember(#ModelAttribute("member") Members theMember, ModelMap modelMap){
Members tempMember = membersService.findByEmail(theMember.getEmail());
if(tempMember != null){
modelMap.addAttribute("error", "Email is already exist!");
return "redirect:/login/signUp";
}else{
membersService.save(theMember);
//prevent duplication
return "redirect:/login/login";
}
}
}
Here is my signUp.html
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<title>Signup</title>
</head>
<body>
<div class="container">
<h3>Signup</h3>
<hr>
<p class="h4 mb-4">Signup</p>
<form action="#" th:action="#{/login/save}" th:object="${member}" method="POST">
<input type="text" th:field="*{firstName}" class="form-control mb-4 col-4" placeholder="First name">
<input type="text" th:field="*{lastName}" class="form-control mb-4 col-4" placeholder="Last name">
<input type="text" th:field="*{email}" class="form-control mb-4 col-4" placeholder="Email">
<input type="password" th:field="*{password}" class="form-control mb-4 col-4" placeholder="Password">
<button type="submit" class="btn btn-info col-2">Save</button>
<p th:text="${error}" />
</form>
<br>
Do you have an account? <a th:href="#{/login/login}">Click here</a>
</div>
</body>
</html>
As I mentioned above this is the only html where the th:text does not works, everywhere else is good.
I hope somebody can help me!
When you use a redirect:, you lose all your model attributes (because it's loading a new page). You need to use a FlashAttribute instead. Like this:
#PostMapping("/save")
public String saveMember(#ModelAttribute("member") Members theMember, ModelMap modelMap, RedirectAttributes redirAttrs){
Members tempMember = membersService.findByEmail(theMember.getEmail());
if(tempMember != null){
redirAttrs.addFlashAttribute("error", "Email is already exist!");
return "redirect:/login/signUp";
}else{
membersService.save(theMember);
//prevent duplication
return "redirect:/login/login";
}
}

spring return object on button click out of list

Hi guys hope you can help me, because i cant get further at the moment
I have my Controller.
#RequestMapping(value="/kundenseite", method= RequestMethod.GET)
public String kundenLogin(ModelMap model) {
if(kundeComponent.getKunde() != null) {
List<Restaurant> restaurants = restaurantService.alleRestaurants();
model.addAttribute("restaurants", restaurants);
return "kundenseite";
}else {
return "redirect:/kunde/login";
}
}
#RequestMapping(value="/kundenseite", method= RequestMethod.POST)
public String kundenLoginAnswer(ModelMap model, #ModelAttribute Restaurant restaurant) {
System.out.println(restaurant.toString());
return "kundenseite";
And my jsp file
<%# include file="common/header.jspf" %>
<div class="jumbotron text-center">
<h1>MiMiMi Lieferservice</h1>
<p>Der schnellste Lieferservice von Passpick</p>
</div>
<div style="margin-right:auto; margin-left:auto; width: 33%">
<h2 style="text-align: center">Restaurant wählen</h2>
<div class="well">
<c:forEach items="${restaurants}" var="restaurant">
<form:form modelAttribute="${restaurant}" method="post">
<div style="margin-top: 8px" class=col-sm-4 >${restaurant.name}</div>
<div style="margin-top: 8px" class=col-sm-4 >${restaurant.restaurantTyp}</div>
<button type="submit">Bestellen</button>
</form:form>
<br style="clear:both;" />
</c:forEach>
</div>
</div>
</body>
</html>
If the user presses a button i want to return a restaurant.
But i don't know how to make that happen, my thought was to use a form but i cant get it to send a complete restaurant object back
If there is no solution for this i have to write the id with the button.
You need input hidden inside the form tab as below input hidden:
<input type="hidden" name="name" value="${restaurant.name}">
<input type="hidden" name="restaurantTyp" value="${restaurant.restaurantTyp}">

Unsupported Media Type error in browser console when sending json using angularjs to spring controller

Here is my controller function
#RequestMapping(value = "/logInChecker", method = RequestMethod.POST, consumes = {"application/json"})
public #ResponseBody String logInCheckerFn(#RequestBody UserLogData userLogData){
Integer userAuthFlag = goAnalyserModel.checkUserAuth(userLogData);
return userAuthFlag.toString();
}
My Bean class
public class UserLogData {
private String userName;
private String password;
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;
}
}
My html file with angularjs function
<!DOCTYPE html>
<html lang="en" ng-app="nameAppIndexPage">
<head>
<meta charset="utf-8">
<title>Go Analyser - Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="assets/css/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {
padding-top: 60px;
padding-bottom: 40px;
}
</style>
<link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
</head>
<body ng-controller="nameController">
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="brand" href="#">Go Analyser</a>
</div>
</div>
</div>
<div class="container">
<!-- Example row of columns -->
<div class="row">
<div class=" margin_alignment"></div>
<div class="span4"></div>
<div class="span4">
<form class="form-signin">
<label for="exampleInputEmail1">Email address</label>
<input type="text" class="input-block-level" placeholder="Email address" ng-model="userName">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="input-block-level" placeholder="Password" ng-model="password">
<!-- <center><button class="btn btn-large" type="submit">Login</button></center>-->
<button type="submit" ng-click='checkLogin()'>login</button>
</form>
</div>
<div class="span4"></div>
</div>
<div class="hr_space"></div>
<footer>
</footer>
</div>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/angular.js"></script>
<script>
var myApp = angular.module('nameAppIndexPage',[]);
myApp.controller('nameController',function($http,$scope){
$scope.checkLogin = function(){
alert("inside checklogin()");
var userName = $scope.userName;
var password = $scope.password;
var dataToSend = {
"userName" : userName,
"password" : password
};
console.log(dataToSend);
alert("after data to send");
$http.post('logInChecker',dataToSend).success(function(data){
if(data == 1){
alert("inside loginSuccess");
}else{
alert("username and password mismatch");
//write function to show incorrect password
}
}).error(function(data){
alert("error in post" + JSON.stringify({data: data}));
});
}
});
</script>
</body>
</html>
I keep getting unsupported media error in browser console. The angularjs function is not getting the request through to the spring controller. But every thing seems to be fine.
This message happens either when the request cannot be converted to a java object, or when a java object cannot be converted to response.
As you've explained, you have the former case. Few things that you should check:
check that you have the <mvc:annotation-driven /> in your servlet configuration
check that you have jackson dependencies on your classpath, for spring 4.x you should have the jackson 2.x version, for spring 3.x you should use jackson 1.9
to ensure that your response is also properly converted you should, besides having the proper dependencies, ensure that
Either an Accept header is sent with your request with the value application/json or that the RequestMapping annotation of your handler method has the attribute produces = {"application/json"}
Add #JsonProperty("**") (**Name of the property) to your bean class. Check in the browser's developer tool type of JSON post messages.

grails login using sql query

I am working on grails and I am new to it. I need to login using sql query in grails. Please help me. Here is my view page, controller and domain class.
login.gsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="layout"content="main"/>
<g:set var="entityName" value="ProjectTracker Login" />
<title><g:message code="projectTracker login" args="[entityName]" /></title>
</head>
<body>
<div class="nav" role="navigation">
<ul>
<li><a class="home" href="${createLink(uri:"/")}"></a></li>
<li><g:link class="list" action="logout">Logout</g:link></li>
</ul>
</div>
<div id="create-endUser" class="content scaffold-create" role="main">
<h1>Login</h1>
<g:form action="authenticate" >
<fieldset class="form">
<div class="fieldcontain ${hasErrors(bean: endUserInstance, field: 'userName', 'error')} ">
<label for="userName">
<g:message code="endUser.userName.label" default="User Name" />
</label>
<g:textField name="userName" value="${endUserInstance?.userName}"/>
</div>
<div class="fieldcontain ${hasErrors(bean: endUserInstance, field: 'password', 'error')} ">
<label for="password">
<g:message code="endUser.password.label" default="Password" />
</label>
<g:field type="password" name="password" value="${endUserInstance?.password}"/>
</div>
</fieldset>
<fieldset class="buttons">
<g:submitButton name="login" class="save" value="Login" />
</fieldset>
</g:form>
</div>
</body>
</html>
my domain class
Testuser.groovy
class Testuser {
String userName
String password
String fullName
String toString(){
"${fullName}"
}
static constraints = {
fullName();
userName(unique:true);
password(password:true);
}
}
my controller is
TestuserController.groovy
import groovy.sql.*
def index()
{
redirect(action:"login")
}
def login={ }
def authenticate={
def username_log = parmas.userName
def password_log = parmas.password
def results
Sql sql = new Sql(dataSource)
def joining = sql.rows("SELECT user_name,password from user where user_name=username_log and password=password_log")
{
results << it.toRowResult()
}
results
if (joining != null) {
results = sql.eachRow()
redirect(action:"login")
}
else {
redirect(action:"login")
}
this is my code for simple login using sql query and I am getting error like
URI
/login/testuser/authenticate
Class
groovy.lang.MissingPropertyException
Message
No such property: parmas for class: login.test.TestuserController Possible solutions: params
It's not parmas but params.
You want to implement login without using spring security ?
By the way the SQL query should be like this
"SELECT user_name,password from user where user_name=$username_log and password=$password_log"
You forgot $

Categories