SpringSecurity自定义登录界面

2023-01-21 0 780

为什么需要自定义登录界面

答:因为SpringBoot整合SpringSecurity时,只需要一个依赖,无需其他配置,就可以实现认证功能。但是它的认证登录界面是固定那样的,如下图所示,但是我们希望自己搞个好看的登录界面,所以需要自定义登录界面。

SpringSecurity自定义登录界面

第一步:创建springboot项目

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd\">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-security-03</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-security-03</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <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-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

第二步:添加配置application.properties

#修改springSecurity默认用户名和密码
spring.security.user.name=root
spring.security.user.password=root

#设置 thymeleaf 缓存为false,表示立即生效
spring.thymeleaf.cache=false

第三步:Controller

package com.example.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping(\"/hello\")
    public String hello(){
        System.out.println(\"hello spring security\");
        return \"hello spring security\";
    }
}
package com.example.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IndexController {

    @RequestMapping(\"/index\")
    public String hello(){
        System.out.println(\"hello index\");
        return \"hello index\";
    }
}
package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController {

    @RequestMapping(\"/loginHtml\")
    public String loginHtml(){
        return \"login\";
    }
}

第四步:login.html

<!DOCTYPE html>
<html xmlns:th=\"http://www.thymeleaf.org/\" lang=\"en\">
<head>
    <meta charset=\"UTF-8\">
    <title>用户登录</title>
</head>
<body>
    <h1>用户登录</h1>
    <form th:action=\"@{/doLogin}\" method=\"post\">
        用户名:<input type=\"text\" name=\"username\"> <br>
        密码:<input type=\"text\" name=\"password\"><br>
        <input type=\"submit\" value=\"登录\">
    </form>
</body>
</html>

第五步:配置自定义登录界面

package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {


    @Override
    public void configure(HttpSecurity http) throws Exception {

        //【注意事项】放行资源要放在前面,认证的放在后面
        http.authorizeRequests()
                .mvcMatchers(\"/index\").permitAll() //代表放行index的所有请求
                .mvcMatchers(\"/loginHtml\").permitAll() //放行loginHtml请求
                .anyRequest().authenticated()//代表其他请求需要认证
                .and()
                .formLogin()//表示其他需要认证的请求通过表单认证
                //loginPage 一旦你自定义了这个登录页面,那你必须要明确告诉SpringSecurity日后哪个url处理你的登录请求
                .loginPage(\"/loginHtml\")//用来指定自定义登录界面,不使用SpringSecurity默认登录界面  注意:一旦自定义登录页面,必须指定登录url
                //loginProcessingUrl  这个doLogin请求本身是没有的,因为我们只需要明确告诉SpringSecurity,日后只要前端发起的是一个doLogin这样的请求,
                //那SpringSecurity应该把你username和password给捕获到
                .loginProcessingUrl(\"/doLogin\")//指定处理登录的请求url
                .and()
                .csrf().disable(); //禁止csrf 跨站请求保护
    }
}

5.1 请求参数名修改

上面的login.html用户名必须为username,密码必须为password,如果我们想要使用自定义的属性名,按照如下修改

5.1.1 修改login.html

<!DOCTYPE html>
<html xmlns:th=\"http://www.thymeleaf.org/\" lang=\"en\">
<head>
    <meta charset=\"UTF-8\">
    <title>用户登录</title>
</head>
<body>
    <h1>用户登录</h1>
    <form th:action=\"@{/doLogin}\" method=\"post\">
        用户名:<input type=\"text\" name=\"uname\"> <br>
        密码:<input type=\"text\" name=\"passwd\"><br>
        <input type=\"submit\" value=\"登录\">
    </form>
</body>
</html>

5.1.2 修改配置类

package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {


    @Override
    public void configure(HttpSecurity http) throws Exception {

        //【注意事项】放行资源要放在前面,认证的放在后面
        http.authorizeRequests()
                .mvcMatchers(\"/index\").permitAll() //代表放行index的所有请求
                .mvcMatchers(\"/loginHtml\").permitAll() //放行loginHtml请求
                .anyRequest().authenticated()//代表其他请求需要认证
                .and()
                .formLogin()//表示其他需要认证的请求通过表单认证
                //loginPage 一旦你自定义了这个登录页面,那你必须要明确告诉SpringSecurity日后哪个url处理你的登录请求
                .loginPage(\"/loginHtml\")//用来指定自定义登录界面,不使用SpringSecurity默认登录界面  注意:一旦自定义登录页面,必须指定登录url
                //loginProcessingUrl  这个doLogin请求本身是没有的,因为我们只需要明确告诉SpringSecurity,日后只要前端发起的是一个doLogin这样的请求,
                //那SpringSecurity应该把你username和password给捕获到
                .loginProcessingUrl(\"/doLogin\")//指定处理登录的请求url
                .usernameParameter(\"uname\") //指定登录界面用户名文本框的name值,如果没有指定,默认属性名必须为username
                .passwordParameter(\"passwd\")//指定登录界面密码密码框的name值,如果没有指定,默认属性名必须为password
                .and()
                .csrf().disable(); //禁止csrf 跨站请求保护
    }
}

5.1 认证成功跳转路径

修改配置类successForwardUrl

package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {


    @Override
    public void configure(HttpSecurity http) throws Exception {

        //【注意事项】放行资源要放在前面,认证的放在后面
        http.authorizeRequests()
                .mvcMatchers(\"/index\").permitAll() //代表放行index的所有请求
                .mvcMatchers(\"/loginHtml\").permitAll() //放行loginHtml请求
                .anyRequest().authenticated()//代表其他请求需要认证
                .and()
                .formLogin()//表示其他需要认证的请求通过表单认证
                //loginPage 一旦你自定义了这个登录页面,那你必须要明确告诉SpringSecurity日后哪个url处理你的登录请求
                .loginPage(\"/loginHtml\")//用来指定自定义登录界面,不使用SpringSecurity默认登录界面  注意:一旦自定义登录页面,必须指定登录url
                //loginProcessingUrl  这个doLogin请求本身是没有的,因为我们只需要明确告诉SpringSecurity,日后只要前端发起的是一个doLogin这样的请求,
                //那SpringSecurity应该把你username和password给捕获到
                .loginProcessingUrl(\"/doLogin\")//指定处理登录的请求url
                .usernameParameter(\"uname\") //指定登录界面用户名文本框的name值,如果没有指定,默认属性名必须为username
                .passwordParameter(\"passwd\")//指定登录界面密码密码框的name值,如果没有指定,默认属性名必须为password
                .successForwardUrl(\"/index\")//认证成功 forward 跳转路径
                .and()
                .csrf().disable(); //禁止csrf 跨站请求保护
    }
}

SpringSecurity自定义登录界面

修改配置类defaultSuccessUrl

package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {


    @Override
    public void configure(HttpSecurity http) throws Exception {

        //【注意事项】放行资源要放在前面,认证的放在后面
        http.authorizeRequests()
                .mvcMatchers(\"/index\").permitAll() //代表放行index的所有请求
                .mvcMatchers(\"/loginHtml\").permitAll() //放行loginHtml请求
                .anyRequest().authenticated()//代表其他请求需要认证
                .and()
                .formLogin()//表示其他需要认证的请求通过表单认证
                //loginPage 一旦你自定义了这个登录页面,那你必须要明确告诉SpringSecurity日后哪个url处理你的登录请求
                .loginPage(\"/loginHtml\")//用来指定自定义登录界面,不使用SpringSecurity默认登录界面  注意:一旦自定义登录页面,必须指定登录url
                //loginProcessingUrl  这个doLogin请求本身是没有的,因为我们只需要明确告诉SpringSecurity,日后只要前端发起的是一个doLogin这样的请求,
                //那SpringSecurity应该把你username和password给捕获到
                .loginProcessingUrl(\"/doLogin\")//指定处理登录的请求url
                .usernameParameter(\"uname\") //指定登录界面用户名文本框的name值,如果没有指定,默认属性名必须为username
                .passwordParameter(\"passwd\")//指定登录界面密码密码框的name值,如果没有指定,默认属性名必须为password
//                .successForwardUrl(\"/index\")//认证成功 forward 跳转路径,forward代表服务器内部的跳转之后,地址栏不变 始终在认证成功之后跳转到指定请求
                .defaultSuccessUrl(\"/index\")//认证成功 之后跳转,重定向 redirect 跳转后,地址会发生改变  根据上一保存请求进行成功跳转
                .and()
                .csrf().disable(); //禁止csrf 跨站请求保护
    }
}

访问http://localhost:8080/hello,认证后

SpringSecurity自定义登录界面

发现并没有到/index的情况,这是defaultSuccessUrl一特性,如果你想硬跳到/index,修改java defaultSuccessUrl("/index",true)即可

访问http://localhost:8080/loginHtml,认证后

SpringSecurity自定义登录界面

defaultSuccessUrl和successForwardUrl区别

1、successForwardUrl是forward跳转,defaultSuccessUrl是重定向redirect跳转
2、successForwardUrl始终在认证成功之后跳转到指定请求,defaultSuccessUrl根据上一保存请求进行成功跳转

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

:本文采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可, 转载请附上原文出处链接。
1、本站提供的源码不保证资源的完整性以及安全性,不附带任何技术服务!
2、本站提供的模板、软件工具等其他资源,均不包含技术服务,请大家谅解!
3、本站提供的资源仅供下载者参考学习,请勿用于任何商业用途,请24小时内删除!
4、如需商用,请购买正版,由于未及时购买正版发生的侵权行为,与本站无关。
5、本站部分资源存放于百度网盘或其他网盘中,请提前注册好百度网盘账号,下载安装百度网盘客户端或其他网盘客户端进行下载;
6、本站部分资源文件是经压缩后的,请下载后安装解压软件,推荐使用WinRAR和7-Zip解压软件。
7、如果本站提供的资源侵犯到了您的权益,请邮件联系: 442469558@qq.com 进行处理!

猪小侠源码-最新源码下载平台 Java教程 SpringSecurity自定义登录界面 http://www.20zxx.cn/462763/xuexijiaocheng/javajc.html

猪小侠源码,优质资源分享网

常见问题
  • 本站所有资源版权均属于原作者所有,均只能用于参考学习,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,建议提前注册好百度网盘账号,使用百度网盘客户端下载
查看详情

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务