In most cases when you create a web application you need to restrict it to certain groups of users with login and password, manage their roles and sessions. Spring Security helps to develop secured apps supporting all of the AAA aspects: authentication, authorization and accounting.
This post will teach you basics about the login & password authentication along with roles and permissions. The code is based on the Spring boot MVC tutorial with Java Configuration (Annotation driven).
Download this tutorial source code
source for this tutorial is available here, under the MvcSecurity tag: https://github.com/yacekmm/looksok/tree/MvcSecurity/Spring/SpringSecurity
1. Download the codebase to begin with
Firstly, follow the Spring boot MVC tutorial or download its final source code. Rest of this article is based on it.
2. Add spring boot security dependency
Spring boot security is provided in the security package. Add this dependency to the build.gradle:
compile("org.springframework.boot:spring-boot-starter-security")
3. Add basic authentication
This Java configuration will create a Servlet Filter for all of your Security. It will protect the application URLs, validate username and password, handle redirects to login form etc. The most basic configuration is to use the hardcoded login, password and role. This way all of your resources will be protected with these credentials.
To do it you need to create a Security Configuration class, extending the WebSecurityConfigurerAdapter, and annotated with @Configuration and @EnableWebMvcSecurity (or any other security scoped annotation: @EnableWebSecurity, @EnableGlobalMethodSecurity or @EnableGlobalAuthentication).
@Configuration @EnableWebMvcSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{ auth .inMemoryAuthentication() .withUser("user").password("pwd").roles("USER"); } }
4. What we have now
These lines of code will automatically:
- require authentication for every URL
- generate the default login form allowing the specified user and password combination to access resources:
Moreover now in every Request will be present the authentication data and methods:
- HttpServletRequest#getRemoteUser()
- HttpServletRequest.html#getUserPrincipal()
- HttpServletRequest.html#isUserInRole(java.lang.String)
- HttpServletRequest.html#login(java.lang.String, java.lang.String)
- HttpServletRequest.html#logout()
You can use them to logout user, check his role when requesting the particular page and check the logged in username.
5. Provide your custom login page
Default login page provided by Spring is good to quickly get up running, but in most cases you want to have your own customized page. The way to do it is to configure security in
HttpSecurity
class:
protected void configure(HttpSecurity http) throws Exception{ http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll(); }
this is how you should read the code above:
“Regarding authorization, require any http request to be authenticated and define login form under “/login” and permit every http request to access the login page”
Concerning “/login” endpoint:
- GET /login: will return the html view with login form
- POST /login with credentials: should be sent by browser to authenticate user
6. Create login page HTML template
I will add the new view in my WebMvcAutoConfigurerAdapter sibling (or you can define new controller endpoint):
registry.addViewController("/login").setViewName("login");
This is how the simpliest login page body may look like:
<c:url value="/login" var="loginUrl"/> <form action="${loginUrl}" method="post"> <c:if test="${param.error != null}"> <p> Invalid username and password. </p> </c:if> <c:if test="${param.logout != null}"> <p> You have been logged out. </p> </c:if> <p> <label for="username">Username</label> <input type="text" id="username" name="username"/> </p> <p> <label for="password">Password</label> <input type="password" id="password" name="password"/> </p> <button type="submit" class="btn">Log in</button> </form>
This is a html form that on submit will post under the /login url with username and password params in http header.
7. handle logout and login error
Spring will automatically redirect the user to the:
- /login?error – if the credentials provided were invalid
- /login?logout – if user requested to logout
This way you can read the url param and show message to the user about incorrect login or password and the logout message.
Download tutorial source code
source for this tutorial is available here, under the MvcSecurity tag: https://github.com/yacekmm/looksok/tree/MvcSecurity/Spring/SpringSecurity
Did I help you?
I manage this blog and share my knowledge for free, sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality
Thank You!
3 thoughts on “Spring Security: Securing your MVC app with basic login and password authentication”