java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springsecurity自定义登录页面

springsecurity自定义登录页面的实现示例

作者:shuair

本文主要介绍了springsecurity自定义登录页面的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

spring security框架使用

环境

jdk版本:jdk 17

依赖

<!-- spring boot 版本 3.2.0 -->

<!-- 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>3.2.0</version>
    <type>pom</type>
    <scope>import</scope>
</dependency>
-->

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</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-thymeleaf</artifactId>
</dependency>

登录认证

  1. 依赖spring-boot-starter-security后,服务启动时,控制台日志会输出自动生成的密码

    1. 日志信息如下

      Using generated security password: 2d9c8697-8ebd-4be7-afea-a6bc922a7d5b
      
      This generated password is for development use only. Your security configuration must be updated before running your application in production.
      
    2. 默认的用户名为:user

  2. 依赖spring-boot-starter-security后,调用接口时就会进行登录认证,会跳转到默认的登录页面:/login,该页面是框架自带的

    1. 页面加载较慢,样式加载不成功,但不影响功能使用。原因:会加载一些无法访问的css数据
    2. 输入默认的用户名和密码,进行登录认证,登录认证成功即可访问接口数据
    3. 该页面可自定义
  3. 默认的登出页面:/logout,该页面是框架自带的

    1. 页面加载较慢,样式加载不成功
    2. 该页面有一个确认登出按钮,点击后即可退出登录,调用接口时会重新进行登录认证
    3. 该页面可自定义

spring security自定义登录页面

使用浏览器自带的登录页面

添加一个配置类WebSecurityConfig.java,后续内容也会在此类中进行配置

package xin.yangshuai.springsecurity03.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
// @EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        // 开启授权保护
        http.authorizeRequests(new Customizer<ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry>() {
            @Override
            public void customize(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry) {

                expressionInterceptUrlRegistry
                        // 对所有请求开启授权保护
                        .anyRequest()
                        // 已经认证的请求会被自动授权
                        .authenticated();
            }
        });

        // 使用基本授权方式(浏览器自带的登录页面,无默认登出页)
        http.httpBasic(Customizer.withDefaults());

        return http.build();
    }
}

自定义登录页面

调整配置类WebSecurityConfig.java

package xin.yangshuai.springsecurity03.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
// @EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        // 开启授权保护
        http.authorizeRequests(new Customizer<ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry>() {
            @Override
            public void customize(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry) {

                expressionInterceptUrlRegistry
                        // 对所有请求开启授权保护
                        .anyRequest()
                        // 已经认证的请求会被自动授权
                        .authenticated();
            }
        });

        // 自定义登录页面
        http.formLogin(new Customizer<FormLoginConfigurer<HttpSecurity>>() {
            @Override
            public void customize(FormLoginConfigurer<HttpSecurity> httpSecurityFormLoginConfigurer) {
                // 自定义登录页,并且设置无需授权允许访问
                httpSecurityFormLoginConfigurer.loginPage("/login").permitAll();
                // 配置自定义表单的用户名参数,默认值:username
                httpSecurityFormLoginConfigurer.usernameParameter("myusername");
                // 配置自定义表单的密码参数,默认值:password
                httpSecurityFormLoginConfigurer.passwordParameter("mypassword");
                // 校验失败时跳转的地址,默认值:/login?error
                httpSecurityFormLoginConfigurer.failureUrl("/login?error");
            }
        });

        return http.build();
    }
}

配置登录页面接口

package xin.yangshuai.springsecurity03.controller;

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

@Controller
public class LoginController {

    @GetMapping("login")
    public String login(){
        return "login";
    }
}

配置登录页面

根据thymeleaf模板引擎,页面位置:src/main/resources/templates/login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<h1>登录</h1>
<div th:if="${param.error}">用户名或密码错误</div>

<!--
使用动态参数,th:action="@{/login}"
开启防止csrf攻击时,会自动生成_csrf隐藏字段
 -->

<form th:action="@{/login}" method="post">
    <div>
        <input type="text" name="myusername" placeholder="用户名">
    </div>
    <div>
        <input type="password" name="mypassword" placeholder="密码">
    </div>
    <input type="submit" value="登录">
</form>
</body>
</html>

到此这篇关于springsecurity自定义登录页面的实现示例的文章就介绍到这了,更多相关springsecurity自定义登录页面内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文