Spring Boot整合Spring Security简记-匿

作者: 78240024406c | 来源:发表于2018-01-17 23:30 被阅读412次

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

    Spring Security学习目录

    对于匿名访问的用户,Spring Security支持为其建立一个匿名的AnonymousAuthenticationToken存放在SecurityContextHolder中,这就是所谓的匿名认证。

    Spring Security 3.0 之后,会自动提供匿名支持,但是为了基础的认识,还是在这里记录下来。

    与匿名认证相关的类有三个
    • AnonymousAuthenticationToken
    • AnonymousAuthenticationProvider
    • AnonymousAuthenticationFilter

    配置


        public AnonymousAuthenticationFilter anonymousAuthenticationFilter(){
            AnonymousAuthenticationFilter anonymousAuthenticationFilter = new AnonymousAuthenticationFilter("foobar");
            return anonymousAuthenticationFilter;
        }
    
        @Bean
        public AnonymousAuthenticationProvider anonymousAuthenticationProvider(){
            return new AnonymousAuthenticationProvider("foobar");
        }
    

    key设置为"foobar",key用于指定一个在AuthenticationFilter和AuthenticationProvider之间共享的值。
    匿名用户名和权限使用默认值anonymousUserROLE_ANONYMOUS
    添加一条权限路径进行测试匿名访问。

      .antMatchers("/anonymous/**").hasRole("ANONYMOUS")
    

    之后启动项目,访问http://localhost:8080/anonymous/123,返回404就是配置成功了。

    AuthenticationTrustResolver


    完成匿名认证检验的是AuthenticationTrustResolver接口和相应的AuthenticationTrustResolverImpl实现。该接口提供了一种isAnonymous(Authentication)方法,检验Authentication是否为一个匿名认证用户主体。

       /**
         * Indicates whether the passed <code>Authentication</code> token represents an
         * anonymous user. Typically the framework will call this method if it is trying to
         * decide whether an <code>AccessDeniedException</code> should result in a final
         * rejection (i.e. as would be the case if the principal was non-anonymous/fully
         * authenticated) or direct the principal to attempt actual authentication (i.e. as
         * would be the case if the <code>Authentication</code> was merely anonymous).
         *
         * @param authentication to test (may be <code>null</code> in which case the method
         * will always return <code>false</code>)
         *
         * @return <code>true</code> the passed authentication token represented an anonymous
         * principal, <code>false</code> otherwise
         */
        boolean isAnonymous(Authentication authentication);
    

    相关文章

      网友评论

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

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