【认证与受权】Spring Security自定义页面

在前面的篇幅中,咱们对认证和受权流程大体梳理了一遍。在这个过程当中咱们一直都是使用系统生成的默认页面,登陆成功后也是直接调转到根路径页面。而在实际的开发过程当中,咱们是须要自定义登陆页面的,有时还会添加各种验证机制,在登陆成功后会跳转至指定页面,还会进行各类美化,甚至是先后端分离的方式。这时,就须要咱们对自定义登陆进行实现。html

本章节使用spring-security-custom-loginjava

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>自定义登陆页面</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>

咱们引入了thymeleaf,也是官方推荐的作法。web

二、application.yml

server:
  port: 8080

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

很是的熟悉,端口、基础用户等信息spring

三、启动类Application

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

2、自定义SecurityConfig

自定义SecurityConfig需继承WebSecurityConfigurerAdapter并重写相关配置便可,因为今天只涉及到自定义页面的信息,因此咱们只须要重写configure(HttpSecurity http) 方法便可。在重写这个方法前,咱们先来看一下原来这个方法是干什么的。apache

protected void configure(HttpSecurity http) throws Exception {
		http
            // 1 声明ExpressionUrlAuthorizationConfigurer,要求全部URL必须登陆认证后才能访问
			.authorizeRequests().anyRequest().authenticated()
			.and()
            // 2 声明一个默认的FormLoginConfigurer
			.formLogin()
            .and()
            // 3 声明一个默认的HttpBasicConfigurer
			.httpBasic();
	}
  1. 对任何请求要求用户已认证(通俗地讲,用户必须先登陆才能访问任何资源);
  2. 启用用户名密码表单登陆认证机制;
  3. 启用Http Basic认证机制;

下面咱们就经过重写上述的方法来作到自定义登陆页面等信息后端

@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();
    }
}

咱们发现其实和缺省方法中并无太大的差异,只有三处的变化springboot

  • loginPage()中将指定自定义登陆页面的请求路径
  • loginProcessingUrl() 为认证的请求接口,也就是咱们常说的form表单中的action。若是不指定,将采用loginPage中的值。
  • defaultSuccessUrl()为认证成功后跳转的页面地址

3、自定义页面

在springboot中使用html页面这里就不过多赘述,通常状况下在resource下新建templates文件下,将须要的页面放到该文件下便可。个人路径为app

_resource
  |_templates
	|_login.html
	|_index.html

一、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}">
    用户名或密码错误
</div>
<div th:if="${param.logout}">
    你已经退出
</div>
<form th:action="@{/loginAction}" method="post">
    <div><label> 帐号 : <input type="text" name="username"/> </label></div>
    <div><label> 密码 : <input type="password" name="password"/> </label></div>
    <div><input type="submit" value="登陆"/></div>
</form>
</body>
</html>

这里我将action与loginProcessingUrl()对应,你也能够本身尝试更换或使用默认或与loginPage()一致的。前后端分离

到这里咱们就完成了一个最简单的表单提交的页面了。当咱们点击submit按钮时,正确的请求路径将是curl

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

这里可能会有个疑问了,为啥你的参数就是username和password呢?嗯~ 固然能够本身指定的啊,由于在FormLoginConfigurer中默认的指定参数

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

二、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>

这是个认证成功后的欢迎页面,比较简单,显示当前登陆用户便可

4、BaseContoller

上面咱们定义了各种路径和请求地址,接下来咱们须要定义若是将这些页面映射出来

@Controller
public class BaseController {
    // loginPage("/login") 将跳转到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、测试

到这里咱们已经完成了一个简单的自定义登陆页面的改造了。固然,在实际的项目中须要自定义的东西还有不少不少,好比,当认证不经过时若是操做,当用户退出登陆时若是操做,这些都没有去实现。

还有人会说,这都什么年代了,先后端分离啊,这些均可以经过一步步的改造来实现的。

(完)

相关文章
相关标签/搜索