Security configurations are often used in development, and users who do not have access need to go to the login form page.There are many ways to achieve access control, including through Aop, interceptors, and frameworks (such as Apache Shiro, Spring Security).
We describe how Spring Security is used for security control in Spring Boot.
Dead work
First, build a simple Web project
Web tier implements request mapping
@Controller public class HelloController { @RequestMapping("/") public String index() { return "index"; } @RequestMapping("/hello") public String hello() { return "hello"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login() { return "login"; } }
- /: Map to index.html
- /hello: map to hello.html
Pages Implementing Mapping - src/main/resources/templates/index.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Spring Security Introduction</title> </head> <body> <h1>Welcome Spring Security!</h1> <p>click <a th:href="@{/hello}">Here</a> Hello</p> </body> </html>
- src/main/resources/templates/hello.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Hello World!</title> </head> <body> <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1> <form th:action="@{/logout}" method="post"> <input type="submit" value="Cancellation"/> </form> </body> </html>
You can see the link to / Hello provided in index.html, apparently without any security controls here, so you can click on the link and jump directly to the hello.html page.
Integrate Spring Security
In this section, we will control the permissions on the / hello page, which must be accessed by authorized users.When a user without permission accesses it, jump to the login page.
Add Dependency
Add the following configuration to pom.xml to introduce a dependency on Spring Security.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
Spring Security Configuration
Create the configuration class WebSecurityConfig for Spring Security as follows:
package com.cicoding; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } }
- Open Spring Security via the @EnableWebSecurity annotation
- Inherit the WebSecurityConfigurerAdapter and override its methods to set some web security details
- onfigure(HttpSecurity http) method
- authorizeRequests() defines which URL s need to be protected and which do not.For example, the code above specifies that / and / home can be accessed without any authentication, and other paths must be authenticated.
- formLogin() defines the login page to go to when a user is required to log in.
- The configureGlobal(AuthenticationManagerBuilder auth) method creates a user in memory with the name user, password, and user role USER.
Add Logon Request and Page
After completing the Spring Security configuration, we are still missing login related content.
New/login requests in HelloController map to login.html
@Controller public class HelloController { // Omit the previous content... @RequestMapping("/login") public String login() { return "login"; } }
New login page: src/main/resources/templates/login.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Spring Security Example </title> </head> <body> <div th:if="${param.error}"> Wrong username or password </div> <div th:if="${param.logout}"> You have logged off successfully </div> <form th:action="@{/login}" method="post"> <div><label> User name : <input type="text" name="username"/> </label></div> <div><label> Password : <input type="password" name="password"/> </label></div> <div><input type="submit" value="Sign in"/></div> </form> </body> </html>
As you can see, a simple login method is implemented that submits to/login with a user name and password.
Depending on the configuration, Spring Security provides a filter to intercept requests and authenticate users.If user authentication fails, the page is redirected to / login?error, and the corresponding error information is displayed on the page.If the user wants to log off, he or she can access/login?logout request and display the corresponding success message on the page after the logoff is completed.
Here, we enable the application and access http://localhost:8080/, which is normally accessible.However, when accessing http://localhost:8080/hello, it was redirected to the http://localhost:8080/login page because there was no login and the user did not have access rights. After logging in by entering username and password, he jumped to the Hello World page and then completed the logout operation by accessing http://localhost:8080/login?logout.
To make the process more complete, we can modify hello.html to output something and provide a link to "log off".
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Hello World!</title> </head> <body> <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1> <form th:action="@{/logout}" method="post"> <input type="submit" value="Cancellation"/> </form> </body> </html>
This article completes security control of Web applications with a simplest example, and Spring Security provides more than that. See more about using Spring Security Spring Security Reference.
Be accomplished!
Applause!