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

自定义登陆页面

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

实现步骤

1. 复制上一示例的源码

重命名包名 case2 为 case3java

重命名 Case2Application.java 为 Case3Application.javaweb

2. 在 WebSecurityConfig 中配置登陆页

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

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

完整代码以下:spring

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,能够看到进入自定义的登陆界面安全

  2. 输入正确用户名密码,能够访问到被保护资源cookie

总结

spring security 中,开发者能够自定义登陆页的app

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

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

相关文章
相关标签/搜索