首页
学习
活动
专区
圈层
工具
发布

Spring security笔记3/4: 自定义登录页面

自定义登录页面

在之前的示例基础上,自定义认证的返回。 对于来自浏览器的请求,将页面重定向到自定义的登录页。 对于来自其他客户端的请求 (比如APP),已 Json 形式返回认证结果。

实现步骤

1. 复制上一示例的源码

重命名包名 case2 为 case3

重命名 Case2Application.java 为 Case3Application.java

2. 在 WebSecurityConfig 中配置登录页

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

  • 放行自定义登录页 url,例如: /login.html;
  • 设置登录跳转页 url, 例如: /login.html;
  • 禁用 csrf 保护。如不添加此项,则需要每次从 cookie 中获取 csrftoken 的值并随表单一同提交到服务端。

完整代码如下:

代码语言:javascript
复制
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。需要至少包含:

  • form 标签,并且 action 赋值为 WebSecurityConfig 中 loginProcessingUrl 配置地址 (默认: "/login");
  • 用户名参数,与 WebSecurityConfig 中 usernameParameter 配置一致(默认:"username");
  • 密码参数,与 WebSecurityConfig 中 passwordParameter 配置一致(默认:"password")。

4. 登录测试

  1. 访问 http://localhost:8080/user/all,可以看到进入自定义的登录界面
  1. 输入正确用户名密码,可以访问到被保护资源

总结

spring security 中,开发者可以自定义登录页的

  • 访问地址
  • 认证地址
  • 用户名参数
  • 密码参数

最后不要忘记放开登录页的访问权限。

下一篇
举报
领券