普歌 - SpringSecurity入门(4)

提示:学习本文需要具备springboot spring 前端页面 和Spring Security基础相关知识


一、登录页面回显提示信息

  1. 当提交登录表单数据认证失败后,通过 http://localhost/login/page?error 重定向回登录页,此时地址带有一
    个 error 参数,标识认证失败。
    并且当用户名或密码错误时,后台会响应提示信息 Bad credentials ,我们要将提示信息在登录页上回显。
  2. 默认情况下,提示信息默认都是英文的,其实是可配置成中文信息。

1.页面中使用thymeleaf进行回显

http://localhost/login/page?error 有 error 参数就是认证失败 th:if=" p a r a m . e r r o r " 2. l o g i n . h t m l 页 面 渲 染 提 示 信 息 t h : t e x t = " {param.error}" 2. login.html 页面渲染提示信息th:text=" param.error"2.login.htmlth:text="{session.SPRING_SECURITY_LAST_EXCEPTION?.message}

 <div th:if="${param.error}">
          <span th:text="${session.SPRING_SECURITY_LAST_EXCEPTION?.message}" style="color:red">用户名或密码错误</span>
        </div>

2.修改默认读取错误文件的地址

默认 ReloadableResourceBundleMessageSource 是加载了 messages.properties 英文配置文件,我们要改成messages_zh_CN.properties

/**
 * @author LIJW
 * @date 2021/3/27 6:18 下午
 * 加载认证信息配置类 把提示信息修改为中文
 */
@Configuration
public class ReloadMessageConfig {

    //默认 ReloadableResourceBundleMessageSource 是加载了 messages.properties 英文配置文件;
    @Bean
    public ReloadableResourceBundleMessageSource messageSource(){
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:org/springframework/security/messages_zh_CN");
        return messageSource;
    }


}

3. 测试

在这里插入图片描述

二、动态配置认证相关URL

1.引入application.yml 配置处理器包

        <!-- application.yml 配置处理器  在实现认证相关url可配置化时使用-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

2.配置yml文件

server:
  port: 80

spring:
  thymeleaf:
    cache: false #关闭thymeleaf缓存

puge:
  security:
    authentication:
      loginPage: /login/page #响应认证(登录)页面URL    修改后必须得使用方法进行匹配
      loginProcessingUrl: /login/form #登录表单提交处理Url
      usernameParameter: name #登录表单用户名的属性名
      passwordParameter: pwd #登录表单密码的属性名
      staticPaths:  #静态资源"/dist/**","modules/**","/plugins/**"
        - /dist/**
        - /modules/**
        - /plugins/**

3.创建读取配置类和javaBean

/**
 * @author LIJW
 * @date 2021/3/28 5:16 下午
 * 对应配置文件中的参数名   配置文件javaBean
 */
@Data
public class AuthenticationProperties {
    // application.yml 没配置取默认值
    private String loginPage = "/login/page";
    private String loginProcessingUrl = "/login/form";
    private String usernameParameter = "name";
    private String passwordParameter = "pwd";
    private String[] staticPaths = {"/dist/**", "/modules/**", "/plugins/**"};
}

要注意读取类中要封装的属性名一定要和yml中配置的最后一层相同

/**
 * @author LIJW
 * @date 2021/3/28 5:14 下午
 * 读取yml配置中的配置信息  实现动态配置认证相关路径
 */
@Component
@ConfigurationProperties(prefix = "puge.security")
public class securityProperties {

    //本属性名authentication要和yml配置中最后一层相同
    AuthenticationProperties authentication;


    /**
     * 重写get set为了方便获取authentication  只要将本类交给spring Ioc即可
     * @return
     */
    public AuthenticationProperties getAuthentication() {
        return authentication;
    }

    public void setAuthentication(AuthenticationProperties authentication) {
        this.authentication = authentication;
    }



}

4.将配置类注入安全配置类并动态读取

/**
 * @author LIJW
 * @date 2021/3/27 9:38 上午
 *  security 安全配置类
 *  继承于webSecurityConfigurerAdapter抽象类
 */
@Configuration
@EnableWebSecurity //启动 SpringSecurity 过滤器链功能
@Slf4j
public class springSecurity  extends WebSecurityConfigurerAdapter {

    //注入获取yml的配置类
    @Autowired
    private securityProperties securityProperties;
    


    /**
     * configure(HttpSecurity http) 资源权限配置(过滤器链)
     * 1.拦截的哪一些资源
     * 2.资源所对应的角色权限
     * 3.定制登录页面、登录请求地址、错误处理方式
     * 4.自定义 spring security 过滤器等
     * 5.定义认证方式:httpBasic httpForm
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //HttpBasic和HttpForm2种认证方式
       http.formLogin()//表单认证
               //注意不管是自定义登录页面还是请求地址开头都要加 /
               .loginPage(securityProperties.getAuthentication().getLoginPage())//交给/login/page响应认证(登陆)页面
               .loginProcessingUrl(securityProperties.getAuthentication().getLoginProcessingUrl())//登录表单处理url,默认是login
               .usernameParameter(securityProperties.getAuthentication().getUsernameParameter()) //修改默认的username   注:要和页面提交的字段名字一样
               .passwordParameter(securityProperties.getAuthentication().getPasswordParameter()) //修改默认的password
               .and()//链接符号
               .authorizeRequests() //认证请求
               .antMatchers(securityProperties.getAuthentication().getLoginPage()).permitAll()//放行跳转认证请求
               .anyRequest().authenticated() //所有进入应用的HTTP请求都要进行认证
            ;
    }


    /**
     * 释放静态资源
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(securityProperties.getAuthentication().getStaticPaths());
    }
}

5.测试

在这里插入图片描述
登录成功


喜欢的小伙伴可以点赞、关注、收藏哦

– 技术源于追求,技术改变生活 –


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值