Spring security自定义登录界面

介绍

通常情况下,Spring security提供的默认登录界面不一定符合我们的需求,所以我们需要自定义一个登录界面,下面会说明主要步骤。如果不清楚springboot如何集成Spring security, 请先看一下Springboot集成Spring security

开发步骤

    • 介绍
    • 1、SecurityConfig继承WebSecurityConfigurerAdapter
    • 2、自定义login.html
    • 3、效果查看
    • 4、登录失败处理

1、SecurityConfig继承WebSecurityConfigurerAdapter

在configure()方法中进行权限管控,以及指定登录成功后转发的请求,这里为/welcome

package com.example.springsecurity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 获取加密后密码
     * @return
     */
    @Bean
    public PasswordEncoder getPass(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 表单认证
        http.formLogin() .loginProcessingUrl("/login") //当发现/login 时认为是登录,需 要执行 UserDetailsServiceImpl
        .successForwardUrl("/welcome") //登录成功后,跳转到指定请求(此处是 post 请求)
        .failureForwardUrl("/loginFail")//登录失败
        .loginPage("/login.html");

        // url 拦截
        http.authorizeRequests()
                .antMatchers("/login.html").permitAll() //login.html 不需要被认证
                .antMatchers("/loginfail.html").permitAll() //loginfail.html 不需要被认证
        .anyRequest().authenticated();//所有的请求都必须被认证。必须登录 后才能访问。

        // 关闭 csrf 防护
        http.csrf().disable(); }

}


2、自定义login.html

在resources目录下的static文件夹中,创建login.html模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/login"method="post">
        用户名:<input type="text" name="username" /><br/>
        密码:<input type="password" name="password" /><br/>
        <input type="submit" value="登录" />
    </form>
</body>
</html>

3、效果查看

1、启动App,任意请求一下,会成功跳转至自定义登录界面
Spring security自定义登录界面_第1张图片
2、登录成功:输入admin/admin,即可跳转至welcome界面
Spring security自定义登录界面_第2张图片

4、登录失败处理

1、在resources目录下的static文件夹中,创建loginfail.html模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录失败</title>
</head>
<body>
    登录失败<a href="/login.html">重新登录</a>
</body>
</html>

2、在controller中增加loginFail()方法

 @RequestMapping("/loginFail")
    public String loginFail(){
        System.out.println("登录失败");
        return "redirect:/loginfail.html";
    }

3、效果查看
Spring security自定义登录界面_第3张图片

你可能感兴趣的:(#,Springboot,spring)