Spring Security form login is not working - spring-boot

I am trying to implement the form login in spring security and the configuration is following.
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("amit").password(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("password"))
.authorities("ROLE_USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.addFilter(getAuthenticationFilter())
.formLogin(formLoginConfigurer ->{
formLoginConfigurer
.loginPage("/api/authentication/login")
.defaultSuccessUrl("/api/loginSuccess")
.failureForwardUrl("/api/loginFailed")
.loginProcessingUrl("/api/login")
.permitAll();
});
}
private Filter getAuthenticationFilter() throws Exception{
return new AuthorizationFilter(authenticationManager());
}
}
The AuthFilter
public class AuthorizationFilter extends UsernamePasswordAuthenticationFilter{
public AuthorizationFilter(AuthenticationManager auth) {
super.setAuthenticationManager(auth);
}
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
String username= obtainPassword(request);
String password = obtainPassword(request);
System.out.println("username : "+username +" and password : "+password);
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
return this.getAuthenticationManager().authenticate(authRequest);
}
}
I am getting the form on http://localhost:8080/api/authentication/login but when I submit nothing happens. I mean when you click on submit button nothing happens and you stay on the same page. In fact the request was never sent to the server at /login path to process the request!
The Controller
#Controller
#RequestMapping("/api")
public class HomeController {
#ResponseBody
#GetMapping
public String statusCheck() {
return "service is up and running :)";
}
#GetMapping("/authentication/login")
public String returnLoginForm() {
return "login";
}
#GetMapping("/loginSuccess")
public String successLogin() {
return "You are successfully logged in";
}
#GetMapping("/loginFailed")
public String failedLogin() {
return "Incorrect username or password";
}
If you want to see my form so there you go:
<html>
<head></head>
<body>
<h1>Login</h1>
<form name='f' action="login" method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' /></td>
</tr>
<tr>
<td><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Any ideas?

Related

OAUTH2: authorization decision Page isnt coming after successful form login

I am writing a form based OAUTH authentication for Getting The Authorization Code.It was supposed to have a "authorization decision Page" after the Resource Server asks the Resource Owner to authenticate itself and as for authorization to share data.
Below are the server side configs
Authorization Server
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("javainuse").secret("{noop}secret").authorizedGrantTypes("authorization_code")
.scopes("read").authorities("CLIENT");
}
}
WebSecurity Configurer
#Configuration
#EnableWebSecurity
public class EmployeeSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Bean
#Override
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
#Autowired
private BCryptPasswordEncoder passwordEncoder;
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/user/getEmployeesList")
.hasAnyRole("ADMIN").anyRequest().authenticated().and().formLogin()
.permitAll().and().logout().permitAll();
http.csrf().disable();
}
#Override
public void configure(AuthenticationManagerBuilder authenticationMgr) throws Exception {
authenticationMgr.inMemoryAuthentication().withUser("admin").password(passwordEncoder.encode("admin"))
.authorities("ROLE_ADMIN");
}
}
Below are the client side configs
Controller
#Controller
public class EmployeeController {
#RequestMapping(value = "/getEmployees", method = RequestMethod.GET)
public ModelAndView getEmployeeInfo() {
return new ModelAndView("getEmployees");
}
#RequestMapping(value = "/showEmployees", method = RequestMethod.GET)
public String getEmployeeInfo1() {
return "showEmployees";
}
}
getEmployees.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Employee</title>
</head>
<body>
<h3 style="color: red;">Add New Employee</h3>
<div id="addEmployee">
<form:form action="http://localhost:8081/oauth/authorize"
method="post" modelAttribute="emp">
<p>
<label>Enter Employee Id</label>
<input type="text" name="response_type" value="code" />
<input type="text" name="client_id" value="javainuse" />
<input type="text" name="redirect_uri" value="http://localhost:8090/showEmployees" />
<input type="text" name="scope" value="read" />
<input type="SUBMIT" value="Get Employee info" />
</form:form>
</div>
</body>
</html>
After providing login details on login prompt
i provided the details, after it should have provided me prompt at http://localhost:8081/oauth/authorize
it is giving me info on logs
INFO AuthorizationEndpoint : Handling OAuth2 error: error="invalid_request", error_description="At least one redirect_uri must be registered with the client."
any help is really appreciated, not sure where i'm doing wrong.
I'm using Spring Boot 2.0.2.RELEASE.
The redirect_uri value http://localhost:8090/showEmployees which is given in the input tag is also needs to be mapped in Authorization Server configuration above, so
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("javainuse").secret("secret").authorizedGrantTypes("authorization_code")
.scopes("read").authorities("CLIENT").redirectUris("http://localhost:8090/showEmployees");
}
adding redirect URL in ClientDetailsServiceConfigurer will work.

Spring boot Security Redirecting from error page to login page In case of authentication failure [duplicate]

This question already has answers here:
Authentication failure redirect with request params not working
(3 answers)
Closed 5 years ago.
I have configured spring security for my web application, Implemented custom authentication handler to authenticate the user details.
Its working as expected when authentication is success ,when authentication fails its invoking custom authentication failure handler redirecting error page(in my case login page with error message) after that again it's redirecting to login page(without message)
Below is my configuration (Let me know what's wrong here)
#Configuration
#EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private CustomAuthenticationProvider authProvider;
#Autowired
private AuthSuccessHandler authHandler;
#Autowired
private AuthFailureHandler authFailureHandler;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/resources/**","/rest/**")
.permitAll().anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.successHandler(authHandler)
.failureHandler(authFailureHandler)
.usernameParameter("username").passwordParameter("password")
.permitAll()
.and().csrf().disable();
}
#Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(authProvider);
}
}
Success Handler
#Component
public class AuthSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Override
protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
redirectStrategy.sendRedirect(request, response, "/home");
}
}
Failure Handler
#Component
public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler{
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
System.out.println("AuthFailureHandler.onAuthenticationFailure()");
redirectStrategy.sendRedirect(request, response, "/login?msg=Bad Credentials");
}
}
Custom Authentication Provider
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider
{
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
String username = (String)token.getPrincipal();
String password = (String) token.getCredentials(); // retrieve the password
System.out.println("username="+username+" password="+password);
flag = //autheticate logic
if(flag) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_ONE"));
authorities.add(new SimpleGrantedAuthority("ROLE_TWO"));
return new UsernamePasswordAuthenticationToken(username, password, authorities);
}
else
throw new BadCredentialsException("401");
}
public boolean supports(Class<?> object) {
return object.equals(UsernamePasswordAuthenticationToken.class);
}
}
Controller :
Below is the controller configuration
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(#RequestParam(name="msg",required=false) String message)
{
System.out.println("HomeController.login()"+message);
return new ModelAndView("login","message",message);
}
login.jsp
<form id='loginForm' method='GET' action='./login'>
<div class="login">
<div id='errorMsg' class="hide alert alert-danger" role="alert"><strong><i class='fa fa-warning'></i>
<span id='errorTitle'></span></strong><span id='errorText'></span>
</div>
<div class="form-group">
<label for='txtUserName' class="UsernamePassword">Username:</label>
<input name="username" type="email" class="form-control" value="" id="txtUserName" maxlength="100" />
</div>
<div class="form-group">
<label for='txtPassword' class="UsernamePassword">Password:</label>
<input value='' name="password" class="form-control" type="password" id="txtPassword" maxlength="100" />
</div>
<div class="form-group">
<label>
<input checked type="checkbox" name="RememberMe" id="checkboxRememberMe"/> Remember My Information
</label>
</div>
<c:if test="${param.error != null}">
<div class="alert alert-danger">
<p>Invalid username and password.</p>
</div>
</c:if>
<c:if test="${param.logout != null}">
<div class="alert alert-success">
<p>You have been logged out successfully.</p>
</div>
</c:if>
<div>
<p>${message}</p>
</div>
<div>
<button id="btnLogin" class="btnBlue" style='width:100% !important' type='submit'>Login</button>
</div>
<div class="usernamePassword">
<a href="#" onclick='forgotPassword()'>I forgot my username/password</a>
</div>
</div>
</form>
It's really important that the "/login?msg=Bad Credentials" is added to an authorizeRequests() section otherwise the controller won't pick up the error parameter.
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/resources/**","/rest/**,/login*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.successHandler(authHandler)
.failureHandler(authFailureHandler)
.usernameParameter("username").passwordParameter("password")
.permitAll()
.and().csrf().disable();
}
Try this config :
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")

how to add custom filter to spring security filter chain with custom filter mapping?

I want to check captcha if use wants to be logined and if captcha was correct, call filterChain.doFilter() to resume authentication and if captcha was incorrect rediredt user to login page to re-enter username, password and captcha.
So, i want to put my CaptchaFilter with /login filterMapping in the first of spring securtiy fiter chain.
login.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page contentType="text/html; charset=UTF-8" language="java" pageEncoding="UTF-8" session="true" %>
<html>
<head>
<title>Login Page</title>
</head>
<body onload='document.loginForm.username.focus();'>
<div id="login-box">
<form name='loginForm' action="<c:url value='/login' />" method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='username'></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password'/>
</td>
</tr>
<tr>
<td colspan="2">
<img id="imgCaptcha" src="<c:url value = '/j-captcha.jpg' />" onclick='this.src="<c:url value='/j-captcha.jpg'/>";' style="cursor: pointer"/>
</td>
</tr>
<tr>
<td colspan="2">
<input name="jcaptcha" type="text" placeholder="captcha"/>
</td>
<tr>
<td colspan='2'><input name="submit" type="submit" value="submit"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
CaptchaFilter
public class CaptchaFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if (request.getParameter("jcaptcha") != null) {
checkCaptcha(request, response, filterChain);
} else {
filterChain.doFilter(request, response);
}
}
private void checkCaptcha(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
try {
String userCaptchaResponse = request.getParameter("jcaptcha");
boolean isResponseCorrect = CaptchaService.getInstance().validateResponseForID(request.getRequestedSessionId(), userCaptchaResponse);
if (isResponseCorrect) {
filterChain.doFilter(request, response);
} else {
String url = request.getHeader("referer").replaceAll("[&?]error.*?(?=&|\\?|$)", "");
url += "?error=" + SecurityUtility.CAPTCHA_IS_WRONG;
redirect(request, response, url);
}
} catch (Exception e) {
e.printStackTrace();
filterChain.doFilter(request, response);
}
}
private void redirect(HttpServletRequest request, HttpServletResponse response, String url) {
try {
response.sendRedirect(request.getContextPath() + url);
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void destroy() {
}
}
SpringSecurityConfig:
#Configuration
#EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
#Qualifier("userDetailsService")
UserDetailsService userDetailsService;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin/**")
.access("hasRole('ROLE_USER')").and().formLogin()
.loginPage("/login").failureUrl("/login?error")
.usernameParameter("username")
.passwordParameter("password")
.and().logout().logoutSuccessUrl("/login?logout")
.and().exceptionHandling().accessDeniedPage("/403");
}
}
SpringWebConfig
#EnableWebMvc
#Configuration
#ComponentScan({"com.rgh.*"})
#EnableTransactionManagement
#Import({SpringSecurityConfig.class})
public class SpringWebConfig {
#Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
builder.scanPackages("com.rgh.*.model").addProperties(getHibernateProperties());
return builder.buildSessionFactory();
}
private Properties getHibernateProperties() {
// set and return properties
}
#Bean(name = "dataSource")
public BasicDataSource dataSource() {
// set and return datasource
}
#Bean
public HibernateTransactionManager txManager() {
return new HibernateTransactionManager(sessionFactory());
}
}
SpringWebInitializer
public class SpringWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringWebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/", "/rest/*"};
}
}
SpringSecurityInitializer
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
i'm new to spring 4 and spring java config.
You can add your filter like this :
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
...
http.addFilterAfter(yourFilter, CsrfFilter.class);
...
}
There are other methods addFilterBefore(..) and addFilter(..) to add filters.
addFilterBefore and addFilterAfter expect as second argument a filter class that is part of the SecurityFilterChain, and they will be added relative to it.
addFilter requires some comperator which I never tried.
To find the filter classes that are actually in the SecurityFilterChain set a breakpoint in a controller method and search in the stack for the SecurityFilterChain (or DefaultSecurityFilterChain). There you can see which filter classes are configured e.g. in DefaultSecurityFilterChain.fiters
Find the first filter class than use addFilterBefore to add your CaptchaFilter.

Spring security : redirecting to the login page after loggin in

I am implementing spring security using the java configuration.
Poviding the necessary config classes here.
SpringSecurity.java
#Configuration
#EnableWebSecurity
public class SpringSecurity extends WebSecurityConfigurerAdapter {
#Autowired
private AuthenticationSuccessHandler authenticationSuccessHandler;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("IS_AUTHENTICATED_ANONYMOUSLY");
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/auth/login").permitAll()
.anyRequest().authenticated()
.and().formLogin().loginPage("/auth/login")
.usernameParameter("j_username").passwordParameter("j_password")
.permitAll().successHandler(authenticationSuccessHandler)
.and().httpBasic();
}
}
WebConfig.java
public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SpringConfig.class,SpringSecurity.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[] {"/"};
}
}
AuthenticationSuccessHandler.java
#Component
public class AuthenticationSuccessHandler implements org.springframework.security.web.authentication.AuthenticationSuccessHandler{
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException,
ServletException {
System.out.println(authentication.getName());
redirectStrategy.sendRedirect(request, response, "/home/homePage");
}
}
SpringConfig.java is where all the datasource and other packages scan related stuff are defined, i guess that won't be needed here.
Problem is that when hit the login page url (contextPath)/auth/login, it shows me login page. But,
after i hit the login button it redirects me to the same login page.
I am providing the login.jsp here.
<form:form action="../home/homePage" class = "form-horizontal">
<legend id = "loginLegend">LOGIN</legend>
<hr style="border: none; height: 1px; color: blue; background: #244363;"/>
UserName: <br>
<input type="text" class="form-control" name="j_username" style = "width: 90% !important; margin-left : 20px;"/><br>
Password:<br>
<input type="password" class = "form-control" name="j_password" style = "width: 90% !important;margin-left : 20px;"/><br>
<button id = "loginButton" class="btn btn-primary" type="submit">Login</button>
</form:form>
So a few issues with what you have now and how you are expecting it to work.
Firstly, you need to point your login page to the url that will process the login form (you can have custom if you want).
Secondly, if you want the user to always end up at "/home/homePage" then you should just add loginSuccessURL("/home/homePage");
Otherwise what you can do, is just set the antMatcher("/home/homePage") with a role expected and it will always request login unless the user is authenticated.

JavaConfiguration for Spring 4.0 + Security 3.2 + j_spring_security_check

Create a login page
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test</title>
<script src="static/js/jquery-1.10.2.min.js"></script>
<script src="static/js/app-controller.js"></script>
</head>
<body>
<div>Login</div>
<form name="f" action="<c:url value="/j_spring_security_check"/>" method="POST">
<label for="password">Username</label> <input type="text" id="j_username" name="j_username"><br/>
<label for="password">Password</label> <input type="password" id="j_password" name="j_password"><br/>
<input type="submit" value="Validate"> <input name="reset" type="reset">
<input type="hidden" id="${_csrf.parameterName}" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
<hr/>
<c:if test="${param.error != null}">
<div>
Failed to login.
<c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}">
Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
</c:if>
</div>
</c:if>
<hr/>
<input type="button" value="Echo" id="echo" name="echo" onclick="AppController.echo();">
<div id="echoContainer"></div>
</body>
</html>
Declare a WebSecurityConfigurer HERE IS WHERE I WAS MISSING j_username AND j_password
#Configuration
#EnableWebSecurity
#ComponentScan(basePackages = {"com.sample.init.security"})
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
#Inject
private AuthenticationProvider authenticationProvider;
#Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(
"/resources/**",
"/static/**",
"/j_spring_security_check",
"/AppController/echo.html").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.usernameParameter("j_username") /* BY DEFAULT IS username!!! */
.passwordParameter("j_password") /* BY DEFAULT IS password!!! */
.loginProcessingUrl("/j_spring_security_check")
.loginPage("/")
.defaultSuccessUrl("/page")
.permitAll()
.and()
.logout()
.permitAll();
}
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/static/**");
}
}
Declare a WebMvcConfigurer
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = {
"com.app.controller",
"com.app.service",
"com.app.dao"
})
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/page").setViewName("page");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("static/**").addResourceLocations("static/");
}
}
Declare a Security Initializer
public class SecurityWebAppInitializer
extends AbstractSecurityWebApplicationInitializer { }
Declare an App Initialzer
public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{WebSecurityConfigurer.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebMvcConfigurer.class, DataSourceConfigurer.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
Implement your custom Authentication Provider
#Component
#ComponentScan(basePackages = {"com.app.service"})
public class CustomAuthenticationProvider implements AuthenticationProvider {
private static final Logger LOG = LoggerFactory.getLogger(CustomAuthenticationProvider.class);
#Inject
private AppService service;
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
//Thread.dumpStack();
String username = authentication.getName();
String password = authentication.getCredentials().toString();
String message = String.format("Username: '%s' Password: '%s'", username, password);
UserBean userBean = service.validate(username, password);
LOG.debug(message);
if (userBean != null) {
List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("USER"));
return new UsernamePasswordAuthenticationToken(userBean, authentication, grantedAuths);
} else {
String error = String.format("Invalid credentials [%s]", message);
throw new BadCredentialsException(error);
}
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
I am skipping EchoController, AppService, AppDao and UserBean.
Thanks.
In 3.2 version post parameters have changed from j_username to username and j_password to password. The login url has also changed from /j_spring_security_check to /login.
See this link for the explanation of why this change was implemented: http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#jc-httpsecurity. These are the changes:
GET /login renders the login page instead of /spring_security_login
POST /login authenticates the user instead of /j_spring_security_check
The username parameter defaults to username instead of j_username
The password parameter defaults to password instead of j_password
And this for an example of a login form: http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#jc-form

Resources