restrict users to access URL directly - spring security - java

I am trying to implement spring security and there are no errors / exceptions, but it is not working, I am not able to redirect to the success page.
My success page is /sucessPage, /Verify will verifying the user details against database.
I want to verify the user with 3 different parameters
SecurityConfig.java
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Resource(name="AdminDB")
private DataSource datasource;
#Autowired
private UserDetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new Md5PasswordEncoder());
auth.eraseCredentials(false);
}
#Override
protected void configure(HttpSecurity security) throws Exception {
logger.info("Inside SecurityConfig - configure() - Spring security");
security
.authorizeRequests()
.antMatchers("/resources/**", "/unsecured/**", "/","/Verify").permitAll()
.anyRequest().authenticated()
.and().formLogin()
.loginPage("/").permitAll()
.usernameParameter("email")
//.passwordParameter("password")
.defaultSuccessUrl("/sucessPage/")
.successHandler(successhandler())
.failureUrl("/")
.and().logout()
.invalidateHttpSession(true).deleteCookies("JSESSIONID")
.permitAll()
.and().exceptionHandling().accessDeniedPage("/systemError.html")
.and().csrf().disable();
}
#Bean
public CustomAuthenticationSuccessHandler successhandler() {
return new CustomAuthenticationSuccessHandler();
}
}
login page - HTML:
<form id="form" name="Form" action="#" th:action="#{/verify}" th:object="${Form}" method="post">
<div class="50">
<label for="first-name" class="label-first-name">First Name*</label>
<input type="text" id="firstName" name="first-name" placeholder="Enter First Name" th:field="*{firstName}">
</div>
<div class="50">
<label for="last-name" class="label-last-name">Last Name*</label>
<input type="text" id="lastName" name="last-name" placeholder="Enter Last Name" th:field="*{lastName}">
</div>
</div>
<div class="100">
<label for="email-1" class="label-email-address">Email Address*<span class="label-note">This is your login username</span></label>
<input type="text" id="email" name="email" placeholder="Enter Email" th:field="*{email}">
</div>
<div class="100">
<label for="email-2" class="label-email-address">Verify Email Address*</label>
<input type="text" id="verifyEmail" name="verifyEmail" placeholder="Re-enter Email" th:field="*{verifyEmail}">
</div>
<div class="100">
<label for="phone" class="label-phone-number">Phone Number<span class="label-note">(optional)</span></label>
<input type="text" id="phoneNumber" name="phoneNumber" placeholder="Enter Phone Number" th:field="*{phoneNumber}">
</div>
<input type="submit" id="submitBtn" value="Next">
</form>
On submit it should verify user and redirect to the /sucessPage. I just want to restrict users to access other URLs directly and other flow will go as it is.
right now it's redirecting back to "/" without any error.
UserDetailsServiceImpl.java
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private LoginManager loginManager;
#Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
UserDetails user = null;
try {
user = loginManager.findUserByEmail(userName);
} catch (LoginException e) {
throw new UsernameNotFoundException("Username not found: " + e.getMessage());
}
return user;
}
}
loadUserByUsername takes only 1 argument. I want to verify the user by firstName, lastName, email against db and redirecting to success with spring security.Thanks

I think your SecurityConfig.java is incomplete
.formLogin().loginPage("/") is missing :
.loginProcessingUrl("/j_spring_security_check")
and
.defaultSuccessUrl("/sucessPage")

Related

spring boot: 404 on login post call

I know that there is many questions like this, but nothing I found helped me fix the issue.
I'm using Spring Boot with security to handle login, with custom login page. This is my config:
#SpringBootApplication
public class CompetencyMatrixApplication {
public static void main(String[] args) {
SpringApplication.run(CompetencyMatrixApplication.class, args);
}
}
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
private final UserDetailsService userDetailsService;
public SecurityConfig(UserDetailsService userDetailsService)
{
this.userDetailsService = userDetailsService;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/matrix", "/matrix/show", "/cas/getImage", "/documentModal").access("hasRole('2')")
.antMatchers("/matrix/fromFile", "/matrix/upload").access("hasRole('1')")
.antMatchers("/cas/new", "/cas/uploadImage").access("hasRole('1')")
.antMatchers("/department/**", "/departmentType/**").access("hasRole('1')")
.antMatchers("/employee/**").access("hasRole('1')")
.antMatchers("/position", "/position/**").access("hasRole('1')")
.antMatchers("/login").permitAll()
.antMatchers("/resources/**").permitAll()
.and().formLogin()
.loginPage("/sign-in").permitAll()
.defaultSuccessUrl("/",true)
.failureUrl("/sign-in?error")
.usernameParameter("email")
.passwordParameter("password")
.and().logout().logoutSuccessUrl("/sign-in?logout")
.and().exceptionHandling().accessDeniedPage("/403");
}
}
and login page (just the form part)
<c:url var="loginUrl" value="/login"/>
<form action="${loginUrl}" method="post">
<div class="mb-4">
<label for="email" class="block text-gray-700 text-sm font-bold mb-2">Email</label>
<input id="email" type='text' name='email' value=''
class="block appearance-none w-full bg-gray-200 border border-gray-200 text-gray-700 py-3 px-4 pr-8 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500">
</div>
<div class="mb-4">
<label for="password" class="block text-gray-700 text-sm font-bold mb-2">Hasło</label>
<input id="password" type='password' name='password'
class="block appearance-none w-full bg-gray-200 border border-gray-200 text-gray-700 py-3 px-4 pr-8 rounded leading-tight focus:outline-none focus:bg-white focus:border-gray-500">
</div>
<input name="submit" type="submit" value="Zaloguj"
class="shadow bg-purple-500 hover:bg-purple-400 focus:shadow-outline focus:outline-none text-white font-bold py-2 px-4 rounded"/>
</form>
So I get my custom page for login, but when I submit it I get 404 Whitelabel Error Page.
What am I missing here? Every example I saw was just using the default /login url to post login details and it worked, mine obviously doesn't even reach UserDetailsService
Found the issue, if someone comes here looking for solution, for me adding
http.csrf().disable(); did the trick

JSP & Spring Security: redirect is working correct, but without login

I'm implementing Spring Security for Spring Boot project.
The problem is: if I use Spring Security configuration like:
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
public SecurityConfiguration(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
#Bean
public DaoAuthenticationProvider authProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(bCryptPasswordEncoder());
return authProvider;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().
antMatchers("/index", "/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").failureUrl("/error")
.defaultSuccessUrl("/CarRentalServlet", true)
.permitAll()
.and()
.logout()
.permitAll()
.and()
.httpBasic();
}
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
Logic for Controller is:
#Controller
public class CarRentalController {
final OrderRepository orderRepository;
final VehicleRepository vehicleRepository;
private final CommandFactory commandFactory;
public CarRentalController(OrderRepository orderRepository, VehicleRepository vehicleRepository, CommandFactory commandFactory) {
this.orderRepository = orderRepository;
this.vehicleRepository = vehicleRepository;
this.commandFactory = commandFactory;
}
#GetMapping("/{view}")
public String viewMapping(#PathVariable String view) {
return view;
}
#RequestMapping(value = { "/CarRentalServlet" }, method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView getCommand(#RequestParam(required = false) String command,
HttpServletRequest req, HttpServletResponse res,
HttpSession session,
#RequestParam(value = "page", required = false, defaultValue = "0") Integer page
) throws ServletException, IOException {
Page<Vehicle> vehiclePage = vehicleRepository.findAll(new PageRequest(page, 2, new Sort(Sort.Direction.DESC, "dailyPrice")));
session.setAttribute("number", vehiclePage.getNumber());
session.setAttribute("totalPages", vehiclePage.getTotalPages());
session.setAttribute("totalElements", vehiclePage.getTotalElements());
session.setAttribute("size", vehiclePage.getSize());
session.setAttribute("data",vehiclePage.getContent());
session.setAttribute("orderList", orderRepository.findAll());
session.setAttribute("vehicleList", vehicleRepository.findAll());
return commandFactory.getCommand(command).execute(req, res, session);
}
}
And login.jspx file as jsp form:
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><fmt:message key="login.paneltitle" /></h3>
</div>
<div class="panel-body">
<form role="form" name="loginForm" method="POST" action="${pageContext.request.contextPath}/login">
<input type="hidden" name="command" value="logInCommand"/>
<fieldset>
<div class="form-group">
<fmt:message key="login.label.login" var="loginValue" />
<input class="form-control" placeholder="${loginValue}" name="username" type="text" autofocus=""/>
</div>
<div class="form-group">
<fmt:message key="login.label.password" var="passwordValue" />
<input class="form-control" placeholder="${passwordValue}" name="password" type="password" value=""/>
</div>
<fmt:message key="login.button.login" var="loginButtonValue" />
<input type="submit" class="btn btn-lg btn-success btn-block" value="${loginButtonValue}" />
</fieldset>
</form>
</div>
</div>
</div>
Another jsp form as index.jsp:
<div class="navbar-default navbar-static-side" role="navigation">
<div class="sidebar-collapse">
<ul class="nav" id="side-menu">
<c:if test="${!empty sessionScope.userName}">
<li>
<form name="makeOrderButton" method="post" action="CarRentalServlet">
<input type="hidden" name="command" value="makeOrderButtonCommand"/>
<a href="" onclick="parentNode.submit();
return false;">
<i class="fa fa-shopping-cart fa-fw"></i>
<fmt:message key="index.button.makeOrder" />
</a>
</form>
</li>
<c:if test="${sessionScope.userTypeID == 1}">
<li>
<form name="adminZoneButton" method="post" action="CarRentalServlet">
<input type="hidden" name="command" value="adminZoneButtonCommand"/>
<a href="" onclick="parentNode.submit();
return false;">
<i class="fa fa-wrench fa-fw"></i>
<fmt:message key="index.button.adminZone" />
</a>
</form>
</li>
</c:if>
</c:if>
</ul>
<!-- /#side-menu -->
</div>
<!-- /.sidebar-collapse -->
</div>
it redirects me to the correct endpoint /CarRentalServlet, but login isn't working at all.
For example, if I don't use SecurityConfiguration class, but I'll modify my jsp file like:
action="CarRentalServlet" instead of action="${pageContext.request.contextPath}/login" and name="login" instead of name="username"
it works as expected and login is working, but in this case I don't use Spring Security.
Can someone suggest me how to fix Spring Security configuration or JSP form to make login work as it works without Spring Security.
The problem was because of usage <c:if test="${!empty sessionScope.userName}"> and <c:if test="${sessionScope.userTypeID == 1}"> in jsp files.
To fix it, I've used authorize tag. So I've changed to <sec:authorize access="isAuthenticated()"> and <sec:authorize access="hasRole('ADMIN')"> accordingly.

Spring Boot authentication without formLogin() but with custom login form

I'm working on a blog application with Spring Boot Security.
My overridden configure method looks like:
#Override
protected void configure(HttpSecurity httpSec) throws Exception {
httpSec
.authorizeRequests()
.antMatchers("/users").authenticated()
.antMatchers("/admin", "/db").hasRole("ADMIN")
.antMatchers("/**").permitAll()
//.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.and()
.logout().logoutSuccessUrl("/login?logout").permitAll();
httpSec.csrf().disable();
httpSec.headers().frameOptions().disable();
}
And my custom login form:
<form name="login" th:action="#{/login}" method="post" class="form-signin">
<h1>Please log in!</h1>
<div th:if="${param.error}" class="alert alert-danger">Wrong username and/or password.</div>
<div th:if="${param.logout}" class="alert alert-success">You logged out successfully.</div>
<label for="username">Username</label>
<input type="text" name="username" class="form-control" placeholder="username" required="true"/>
<label for="password">Password</label>
<input type="password" name="password" class="form-control" placeholder="password" required="true"/>
<br/>
<button type="submit" class="btn btn-lg btn-primary btn-block">Log in</button>
<br/>
You can register here.
<hr/>
</form>
The default behaviour of Spring Security is that when I send a request to an URL which needs to be authenticated (for example /users or /admin in my case) it automatically redirects to this custom login page.
I would like to disable this automatic redirection. When authentication is needed I would like to throw a custom exception (which I handle with a separate Class with #ControllerAdvice annotation) instead with message like "You have to log in to see this content". But I would like to reach my custom login page via navigation menu to authenticate "manually".
How could I reach this?
So far I have tried .formLogin().disabled(). In this way I can still reach my custom login page, but when I try to submit it gave an error "Method not allowed". But it is logical since th:action="#{/login}" can't send the username and password to /login.
I have found a solution. Maybe not perfect, but it works.
First of all, I have commented out the login/logout part in my configure method:
#Override
protected void configure(HttpSecurity httpSec) throws Exception {
httpSec
.authorizeRequests()
.antMatchers("/users").authenticated()
.antMatchers("/admin", "/db").hasRole("ADMIN")
.antMatchers("/**").permitAll()
/**
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.and()
.logout().logoutSuccessUrl("/login?logout").permitAll();
*/
.and()
.csrf().disable()
.headers().frameOptions().disable();
}
From now when authentication is needed it won't redirect to any (custom) login screen. But the Forbidden (403) error should be handled:
case "Forbidden":
if (SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString().equals("[ROLE_ANONYMOUS]"))
error.put("error", "You have to log in to see this content");
else error.put("error", "It is only for admins");
break;
Next step is creating a login form into the navigation menu:
<form th:action="#{/loginauth}" method="post">
<span sec:authorize="!isAuthenticated()">
<input type="text" name="email" placeholder="e-mail" required="true"/>
<input type="password" name="password" placeholder="password" required="true"/>
<button type="submit" class="btn btn-success btn-xs">Log in</button>
</span>
</form>
After submit we have to be forwarded to a #PostMapping in one of the #Controller classes:
#PostMapping("/loginauth")
public String authenticateLogin(HttpServletRequest request) {
loginService.authenticateBlogUser(request.getParameter("email"), request.getParameter("password"));
return "redirect:/";
}
Finally this data should be sent to a service layer to process:
BlogUserRepository blogUserRepository;
#Autowired
public void setBlogUserRepository(BlogUserRepository blogUserRepository) {
this.blogUserRepository = blogUserRepository;
}
public void authenticateBlogUser(String email, String password) throws UsernameNotFoundException {
BlogUser user = blogUserRepository.findByEmail(email);
if (user == null || !user.getPassword().equals(password))
throw new UsernameNotFoundException("Wrong e-mail and/or password");
Collection<GrantedAuthority> authorities = new HashSet<>();
Set<Role> roles = user.getRoles();
for (Role role : roles)
authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getAuth()));
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword(), authorities));
}

Login Error in SpringBoot 2.1.4.RELEASE WebApp

I have a basic SpringBoot 2.1.4.RELEASE app. Using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file. with those methods in the security config file:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserSecurityService userSecurityService;
/** The encryption SALT. */
private static final String SALT = "asd31*(_)nof";
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12, new SecureRandom(SALT.getBytes()));
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(publicMatchers()).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/calzadas/list")
.failureUrl("/login?error").permitAll()
.and()
.logout().permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.eraseCredentials(false)
.userDetailsService(userSecurityService)
.passwordEncoder(passwordEncoder());
}
private String[] publicMatchers() {
/** Public URLs. */
final String[] PUBLIC_MATCHERS = {
"/webjars/**",
serverContextPath + "/css/**",
serverContextPath + "/js/**",
serverContextPath + "/fonts/**",
serverContextPath + "/images/**",
serverContextPath ,
"/",
"/error/**/*",
"/console/**",
SignupController.USER_VALIDATION_URL_MAPPING
};
return PUBLIC_MATCHERS;
}
}
and
#Service
public class UserSecurityService implements UserDetailsService {
/** The application logger */
private static final Logger LOG = LoggerFactory.getLogger(UserSecurityService.class);
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
LOG.info("Searching user with email: " + email);
User user = userRepository.findByEmailIgnoreCase(email);
LOG.info("user: {} " + user);
if (null == user) {
LOG.warn("Username {} not found", email);
throw new UsernameNotFoundException("Username " + email + " not found");
}
return user;
}
}
on the login.html:
<div th:if="${param.error}" class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">x</span>
</button>
<p th:text="#{login.error.message}" />
</div>
on the other hand I have a RestController also for the validation:
#RestController
public class AuthenticationRestController {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private JwtTokenUtil jwtTokenUtil;
#Autowired
private UserSecurityService userSecurityService;
#Autowired
private EmailService emailService;
...
/**
* Authenticates the user. If something is wrong, an {#link AuthenticationException} will be thrown
*/
private void authenticate(String username, String password) {
Objects.requireNonNull(username);
Objects.requireNonNull(password);
if (StringUtils.isEmpty(username)) throw new AuthenticationException();
if (StringUtils.isEmpty(password)) throw new AuthenticationException();
try {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
} catch (DisabledException e) {
throw new AuthenticationException("User is disabled!", e);
} catch (BadCredentialsException e) {
throw new AuthenticationException("Bad credentials!", e);
}
}
}
I don't know why with the Web authentication I can't log, I got always an error, Bad credential ? , but with the RestController I can log using the same credentials, and I don't know how to figure out what is the difference ...
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="pradera/common/header :: common-header" />
<link rel="stylesheet" th:href="#{/pradera/css/login.css}" type='text/css' />
<!-- for the error login message box -->
<link th:href="#{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" rel="stylesheet" media="screen" />
<body>
<div class="wrap">
<div class="login">
<div class="logo"><img th:src="#{pradera/images/login.png}" width="224" height="71" alt="pradera Cloud" /></div>
<form id="loginForm" th:action="#{/login}" method="post">
<div class="row">
<div class="col-md-6 col-md-offset-3 text-center">
<div th:if="${param.error}" class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">x</span>
</button>
<p th:text="#{login.error.message}" />
</div>
<div th:if="${param.logout}" class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">x</span>
</button>
<p th:text="#${param.error}" />
</div>
</div>
</div>
<div class="input_label"><i class="fa fa-user"></i><input type="text" id="usernameId" name="username" th:attr="placeholder=#{login.user.placeholder}" value="ricard.olle#gmail.com" /></div>
<div class="input_label"><i class="fa fa-key"></i><input type="password" name="password" placeholder="Password" value="Iconofcoil100#"/></div>
<input type="submit" value="LOGIN" />
</form>
<div class="forget">
<a th:href="#{/signup?planId=1}" th:text="#{login.register.text}">Register</a><br/>
<br/>
</div>
<div class="forget">
<a th:href="#{/forgotmypassword}" th:text="#{login.forgot.password.text}" >Do you forgot your password</a><br/>
<br/>
<br/>
<br/>
<br/>
<span>Powered By Cryptsonic.io 2018 ©</span>
</div>
</div>
</div>
<!-- Js zone -->
<div th:replace="pradera/common/header :: before-body-scripts" ></div>
<script th:src="#{/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js}"></script>
<script type="text/javascript">
$( document ).ready(function() {
$( "#usernameId" ).focus();
});
$(document).keypress(function(e) {
if(e.which == 13) {
$( "#loginForm" ).submit();
}
});
</script>
</body>
</html>
and
#Repository
public interface UserRepository extends CrudRepository<User, Long> {
/**
* Returns a User given a username or null if not found.
* #param username The username
* #return a User given a username or null if not found.
*/
User findByUsernameIgnoreCase(String username);
/**
* Returns a User for the given email or null if none was found.
* #param email The user's email
* #return a User for the given email or null if none was found.
*/
User findByEmailIgnoreCase(String email);
..
}
and I see in the logs that the user is retrieved:
2019-04-21 10:56 [http-nio-2233-exec-3] INFO i.i.b.service.UserSecurityService.loadUserByUsername(39) - user: {} com.bonanza.backend.persistence.domain.backend.User#5a3163ef
Try activating the debug logging for Spring security:
<logger name="org.springframework.security" level="debug" />

Spring Security always returns BadCredentialsException at DaoAuthenticationProvider on user authentication [duplicate]

I've generated a Spring Boot web application using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
Technologies used:
Spring Boot 1.4.2.RELEASE, Spring 4.3.4.RELEASE, Thymeleaf 2.1.5.RELEASE, Tomcat Embed 8.5.6, Maven 3, Java 8
This is my security config class:
#Configuration
#EnableWebSecurity
#PropertySource("classpath:/config/app-${APP-KEY}.properties")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Value("${securityConfig.formLogin.loginPage}")
private String loginPage;
#Bean
public StandardPasswordEncoder encoder() {
return new StandardPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage(loginPage)
.permitAll()
.loginProcessingUrl("/tdk/login")
.failureUrl("/tdk/login?error=true")
.defaultSuccessUrl("/events/list")
.and()
.exceptionHandling()
.accessDeniedPage("/denied")
.and()
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/mockup/**").permitAll()
.antMatchers("/users/**").permitAll()
.antMatchers("/books/**").permitAll()
.antMatchers("/welcome/**").authenticated()
.and()
.logout()
.permitAll()
.logoutSuccessUrl("/index.html");
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.passwordEncoder(new StandardPasswordEncoder())
.withUser("test1").password("c1f02fa50809b7f715576198eda6466cd17f63404ae6eded7c22290b025baf3868bc8f785267d4ae").roles("ADMIN").and()
.withUser("test2").password("test2").roles("USER").and()
.withUser("test3").password("test3").roles("SUPERADMIN");
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertyDefaultConfig() {
return new PropertySourcesPlaceholderConfigurer();
}
}
This is my Junit Tests that works properly
public class StandardPasswordEncoderTests {
#Test
public void getPasswordForTest1() {
StandardPasswordEncoder encoder = new StandardPasswordEncoder();
String password = "test1";
assertTrue(
encoder.matches(password, "c1f02fa50809b7f715576198eda6466cd17f63404ae6eded7c22290b025baf3868bc8f785267d4ae"));
}
}
Here my login template
<form th:action="#{/tdk/login}" method="post">
<p th:if="${param.error}">
Bad Credentials ${param.error}
</p>
<p th:if="${loginError}" class="error">Wrong user or password</p>
<div class="input_label"><i class="fa fa-user"></i><input type="text" name="user" placeholder="User" /></div>
<div class="input_label"><i class="fa fa-key"></i><input type="password" name="pass" placeholder="Password" /></div>
<input type="submit" value="LOGIN" />
</form>
But whatever I put:
test1 / c1f02fa50809b7f715576198eda6466cd17f63404ae6eded7c22290b025baf3868bc8f785267d4ae
or
test2 / test2
I see the message Bad Credentials ${param.error} in the output of my template
The parameter names for username and password in your login page are not matching the names in Spring Security configuration.
You could change the Spring Security configuration to use the parameter names from your login page. Or you could change the login page to use the default parameter names.
See FormLoginConfigurer#usernameParameter:
The HTTP parameter to look for the username when performing authentication. Default is "username".
and FormLoginConfigurer#passwordParameter:
The HTTP parameter to look for the password when performing authentication. Default is "password".
Your modified login page (with default parameter names):
<form th:action="#{/tdk/login}" method="post">
<p th:if="${param.error}">
Bad Credentials ${param.error}
</p>
<p th:if="${loginError}" class="error">Wrong user or password</p>
<div class="input_label">
<i class="fa fa-user"></i>
<input type="text" name="username" placeholder="User" />
</div>
<div class="input_label">
<i class="fa fa-key"></i>
<input type="password" name="password" placeholder="Password" />
</div>
<input type="submit" value="LOGIN" />
</form>

Categories

Resources