Spring Boot整合Spring Security简记-B

作者: 78240024406c | 来源:发表于2018-01-17 21:25 被阅读233次

    new無语 转载请注明原创出处,谢谢!

    Spring Security学习目录

    目前大多数都是前后端分离系统等服务器端无状态的应用。之前的认证方式可能不是太适用。这章写一下这种无状态环境下的用户Basic认证。

    简言之,Basic Auth是配合RESTful API 使用的最简单的认证方式,只需提供用户名密码即可,但由于有把用户名密码暴露给第三方客户端的风险,在生产环境下被使用的越来越少。因此,在开发对外开放的RESTful API时,尽量避免采用Basic Auth。一般Basic验证适用于开发阶段。

    BasicAuthenticationFilter


    BasicAuthenticationFilter负责处理HTTPHeader中的基本认证信息。
    工作原理:在header中获取特定key和特定形式的value(Authorization、Basic [Token]),获取的到,即使用当前过滤器进行验证身份信息。获取不到,则继续执行正常的过滤链。
    在使用无状态认证时,需要关闭CSRF。

    http.csrf().disable()
    

    配置方式,添加一个BasicAuthenticationFilter到过滤链中:

    http.and().httpBasic();
    
        @Bean
        public BasicAuthenticationFilter basicAuthenticationFilter(AuthenticationManager authenticationManager, AuthenticationEntryPoint basicAuthenticationEntryPoint) {
            return new BasicAuthenticationFilter(authenticationManager, basicAuthenticationEntryPoint);
        }
    
        @Bean
        public AuthenticationEntryPoint basicAuthenticationEntryPoint() {
            BasicAuthenticationEntryPoint basicAuthenticationEntryPoint = new BasicAuthenticationEntryPoint();
            //网站域名
            basicAuthenticationEntryPoint.setRealmName("www.jianshu.com");
            return basicAuthenticationEntryPoint;
        }
    

    认证信息以Authorization : Basic [Token]方式填充进HTTPHeader。Token组成方式为username:password 进行base64转码。

    ========================样例Token=============================
    testuser1:password
    ========================base64转码后==========================
    dGVzdHVzZXIxOnBhc3N3b3Jk
    ========================请求header============================
    Authorization:Basic dGVzdHVzZXIxOnBhc3N3b3Jk
    

    运行项目进行操作,测试一下是否生效。


    Postman运行图

    图上显示404找不到当前路径,已经认证通过。

    yml配置

    security:
      basic:
        enabled: true
        realm: www.jianshu.com
    

    相关文章

      网友评论

      • 宁静致远Sam:过时了,spring boot 2.0已经不支持这种配置:
        security:
        basic:
        enabled: true
        sunny_Lee:确实不支持了,麻烦问下,针对前后端分离,RESTful API 认证这一块现在一般都采用什么?

      本文标题:Spring Boot整合Spring Security简记-B

      本文链接:https://www.haomeiwen.com/subject/yesuoxtx.html