Spring security中怎么自定义登录页面

发布时间:2021-06-18 15:22:18 作者:Leah
来源:亿速云 阅读:270

这篇文章将为大家详细讲解有关Spring security中怎么自定义登录页面,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

实现步骤

1. 复制上一示例的源码

重命名包名 case2 为 case3

重命名 Case2Application.java 为 Case3Application.java

2. 在 WebSecurityConfig 中配置登录页

在 config(HttpSecurity http) 方法中对 formLogin 选项进行配置。需要包含以下设置:

完整代码如下:

package net.txt100.learn.springsecurity.base.case3.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;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Title: WebSecurityConfig
 * Package: net.txt100.learn.springsecurity.base.case3.config
 * Creation date: 2019-08-11
 * Description:
 *
 * @author <a href="zgjt_tongl@thunis.com">Tonglei</a>
 * @since 1.0
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 配置密码的保护策略,spring security 默认使用 bcrypt 加密算法。
        // 此处只要显式声明 BCryptPasswordEncoder Bean 即可
        return new BCryptPasswordEncoder();
    }

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

        UsernamePasswordAuthenticationFilter up;

        http
            .csrf().disable() // 关闭 CSRF 保护功能,否则不支持 Post 请求
            .authorizeRequests() // 针对 HttpServletRequest 进行安全配置
                .antMatchers("/login.html").permitAll() // login.html 页面无需登录即可访问
                .anyRequest().authenticated() // 对所有 Request 均需安全认证
            .and().formLogin()
                .loginPage("/login.html") // 每当需要登录时浏览器跳转到 login.html 页面
                .loginProcessingUrl("/login") // 自定义登录提交地址,默认地址是 /login, 默认处理器是 UsernamePasswordAuthenticationFilter
//                 .usernameParameter("/phone_number") // 自定义登录用户ID参数,默认是 username
//                 .passwordParameter("/check_code") // 自定义登录口令参数,默认是 password
            .and().httpBasic(); // 定义如何验证用户,此项代表弹出浏览器认证窗口
    }
}

3. 创建 login.html 页面

新建目录 src/main/webapp,并在该目录下创建文件 login.html。需要至少包含:

关于Spring security中怎么自定义登录页面就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. 基于Spring Boot+Spring Security+JWT+Vue前后端分离的开源项目
  2. spring boot Security 简单使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring security

上一篇:DNS的特点和作用是什么

下一篇:python清洗文件中数据的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》