zoukankan      html  css  js  c++  java
  • 使用java代码配置 Spring Boot 中的 Spring Security 和 Rember me, Cookie记住密码

    前言

    Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。 [ 百度百科 ]

    开始

    1 .使用maven 引用spring security 等相关jar包

    2 .在配置文件中编写如下代码,其中csrf表示提交方式,禁用后logout用get即可访问

                http
                        .authenticationProvider(formAuthenticationProvider)
                        .authorizeRequests()
                        .antMatchers("/error", "/favicon.ico", "/content/**", "/login", "/user/login", "/user/register").permitAll()
                        .anyRequest().hasRole("USER")
                        .and().formLogin().loginPage("/user/login").loginProcessingUrl("/user/login").failureHandler(formAuthenticationFailureHandler)
                        .and().logout().logoutUrl("/user/logout").logoutSuccessUrl("/user/login").invalidateHttpSession(true)
                        .and().rememberMe().key("demo").tokenValiditySeconds(30 * 24 * 60 * 60).userDetailsService(formDetailsService)
                        .and().csrf().disable();

    3 .然后新建如下类,来自定义处理用户登录结果,其中FormAuthenticationProvider是登录的时候,验证用户名、密码用的。FormDetailsServiceImpl是用户关闭浏览器,再次打开会调用此方法,来获取当前用户,切身份已经验证通过的。FormAuthenticationFailureHandler是登录失败,来处理不同的返回消息

            private final FormAuthenticationProvider formAuthenticationProvider;
            private final FormDetailsServiceImpl formDetailsService;
            private final FormAuthenticationFailureHandler formAuthenticationFailureHandler;

    4 .具体三个类实现,请看GitHub,FormAuthenticationProviderFormAuthenticationFailureHandlerFormDetailsServiceImpl


    结束

    附上成功图片:
    这里写图片描述

  • 相关阅读:
    [001]
    SpringBoot默认首页跳转设置
    Tomcat网站根目录设置
    SpringBoot获取前端传递JSON的几种方法
    MySQL调优性能监控之show profile
    MySQL新特性MTS
    Java线程池拒绝策略
    快速排序与荷兰国旗及Partition问题
    数据结构与算法之返回最小和问题
    MySQL之谓词下推
  • 原文地址:https://www.cnblogs.com/alvis/p/9438829.html
Copyright © 2011-2022 走看看