[authentication and authorization] Spring Security custom page

In the previous part, we have roughly combed the authentication and authorization process. In this process, we always use the default page generated by the system. After logging in successfully, we also directly transfer to the root path page. In the actual development process, we need to customize the login page, and sometimes add various authentication mechanisms. After the login is successful, we will jump to the specified page, beautify it, and even separate the front and back ends. At this time, we need to implement the custom login.

This chapter uses spring security custom login

1, Project preparation

1,pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>security-study</artifactId>
        <groupId>cn.wujiwen.security</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <description>Custom login page</description>
    <artifactId>spring-security-custom-login</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>
</project>

We have introduced thmeleaf, which is also the official recommended practice.

2,application.yml

server:
  port: 8080

spring:
  security:
    user:
      name: admin
      password: admin
      roles: ADMIN

Very familiar with port, basic user and other information

3. Start class Application

@SpringBootApplication
public class SecurityLoginApplication {
    public static void main(String[] args) {
        SpringApplication.run(SecurityLoginApplication.class,args);
    }
}

2, Custom SecurityConfig

To customize the SecurityConfig, we need to inherit the WebSecurityConfigurerAdapter and rewrite the relevant configuration. Today, we only need to rewrite the configure(HttpSecurity http) method because we only need to customize the page information. Before rewriting this method, let's take a look at what the original method does.

	protected void configure(HttpSecurity http) throws Exception {
		http
            // 1 declare ExpressionUrlAuthorizationConfigurer. All URL s must be logged in for authentication to access
			.authorizeRequests().anyRequest().authenticated()
			.and()
            // 2 declare a default FormLoginConfigurer
			.formLogin()
            .and()
            // 3 declare a default HttpBasicConfigurer
			.httpBasic();
	}
  1. For any request, the user must be authenticated (generally speaking, the user must log in first to access any resource);
  2. Enable the user name password form login authentication mechanism;
  3. Enable Http Basic authentication mechanism;

Now we can customize the login page and other information by rewriting the above methods

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().anyRequest().authenticated()
                .and().httpBasic().and()
            	// 1
                .formLogin().loginPage("/login")
                // 2
            	.loginProcessingUrl("/loginAction")
            	// 3
                .defaultSuccessUrl("/index")
                .permitAll();
    }
}

We find that there is not much difference between the default method and the default method, but only three changes

  • Request path for custom login page will be specified in loginPage()
  • loginProcessingUrl() is the request interface for authentication, which is often referred to as the action in the form form form. If not specified, the value in loginPage is used.
  • Defaultsuccessusurl() is the page address to jump after the authentication succeeds

3, Custom page

Using html pages in springboot is just a little more detailed here. In general, under the new templates file under resource, you can put the required pages under the file. My path is

_resource
  |_templates
	|_login.html
	|_index.html

1,login.thml

<!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 user name or password
</div>
<div th:if="${param.logout}">
    You've quit
</div>
<form th:action="@{/loginAction}" method="post">
    <div><label> Account number : <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>

Here I'll match the action with loginProcessingUrl(). You can also try to replace or use the default or the same as loginPage().

Here we have finished a simple form submission page. When we click the submit button, the correct request path will be

curl -x POST -d "username=admin&password=admin" http://127.0.0.1:8080/loginAction

There may be a question here. Why are your parameters username and password? Of course, you can specify it by yourself, because the default parameter is specified in FormLoginConfigurer

public FormLoginConfigurer() {
		super(new UsernamePasswordAuthenticationFilter(), null);
		usernameParameter("username");
		passwordParameter("password");
	}

2,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 Example</title>
</head>
    <body>
        <h2>Welcome <b th:text="${username}"></b></h2>
    </body>
</html>

This is a welcome page after successful authentication. It's relatively simple. It can display the current login user

4, Basecontroller

We have defined various paths and request addresses. Next, we need to define how to map these pages

@Controller
public class BaseController {
    // loginPage("/login") will jump to login.html
    @GetMapping("/login")
    public String login() {
        return "login";
    }
	// index.html
    @RequestMapping("/index")
    public String index(Model model, HttpServletRequest request) {
        model.addAttribute("username",request.getUserPrincipal().getName());
        return "index";
    }
}

5, Testing

Here we have completed a simple custom login page transformation. Of course, there are many things that need to be customized in the actual project, for example, if the authentication fails, if the user logs out, if the operation, these are not implemented.

Some people will say, what time is it? The front and back ends are separated. These can be achieved through step-by-step transformation.

(end)

Tags: Java Spring Thymeleaf Maven Apache

Posted on Fri, 08 May 2020 11:03:31 -0700 by fabby