zoukankan      html  css  js  c++  java
  • Spring Security学习笔记(一)

    认证和权限控制

    AuthenticationManager是认证的主要接口,它只有一个authenticate方法,可以做3件事情。

    • 返回一个认证信息(Authentication),表示认证成功
    • 抛一个AuthenticationException异常,如果认证不成功
    • 返回null,如果不能确定是否认证成功

    最常见的AuthenticationManager实现是ProviderManager(经常看到一些AuthenticationProvider实例)。有时候应用的保护资源有逻辑分组,每组都有自己的认证方式,也就是说分别有各自的ProviderManager。他们共享一个parent。

    @Configuration
    public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

    ... // web stuff here

    @Autowired
    public initialize(AuthenticationManagerBuilder builder, DataSource dataSource) {

    builder.jdbcAuthentication().dataSource(dataSource).withUser("dave")
    .password("secret").roles("USER");
    }

    }

    如果AuthenticationManagerBuilder以autowired方式生成实例,那就是创建了一个global/parent的 AuthenticationManager实例。

    授权(Authorization)或权限控制(Access Control)
    一旦认证成功,我们继而可以进行权限控制。

    web security(网络安全)

    web层面的spring security是基于Filters Servlet。

    客户端发送一个请求到app, 容器根据请求url决定使用哪些filters。通常,一个servlet可以处理一个请求,因此filters是顺序执行的。filter的顺序很重要,Spring Boot实用两种机制来处理filter的顺序。

    • @Bean的Filter可以有@Order声明或者实现Ordered。
    • 成为一个已经有order的FilterRegistrationBean的一部分。

    spring security在filter chain中作为一个单独的filter,它实际的类型是FilterChainProxy(是一系列的Filter构成的)。

    FilterChainProxy通过filters chain实现所有security逻辑。所有的filter都implement Servlet Spec的Filter 接口。

    请求的匹配规则

    一个security filter chain(WebSecurityConfigurerAdapter)有一个请求matcher用来决定filter规则是否应用到该请求。一旦有一个特定的filter chain,其他的filter chain就不work了。一个filter chain你可以定义多种规则。

    • java config方式配置security filter chain。以global(@Autowired)的方式生成一个AuthenticationManager实例,该实例为自定义的AuthenticationManager,即UsernameAndPasswordAuthenticationProvider的一个实例。该自定义的UsernameAndPasswordAuthenticationProvider主要实现一个自定义的authentication方法。

    • 然后在spring filter chain添加一个自定义的filter,该filter处理主要的认证过程。

    • 该filter主要干了两件事:

      • 将http request的请求body的值,转为AuthenticationTocken。
      • 然后AuthenticationManager(这里是UsernameAndPasswordAuthenticationProvider)的authentication方法处理认证逻辑。
    • UsernameAndPasswordAuthenticationProvider的authentication方法具体实现:

    这里注意support方法默认返回false,这样就不会掉用自定义的authentication方法。需要逻辑判断调用条件。

    这样就使用spring security实现了一个简单的自定义authentication策略的认证流程。

    代码地址:
    https://github.com/Rying/twitter-clone.git

  • 相关阅读:
    docker in docker
    docker社区的geodata/gdal镜像dockerfile分析
    howto:在构建基于debian的docker基础镜像时,更换国内包源
    使用Visual Studio 2017构建.Net Core的Docker镜像
    步骤:asp.net core中使用identifyserver4颁发令牌
    部署:阿里云ECS部署Docker CE
    问题:调用 ASP.Net Core WebAPI的HTTP POST方法时,从 [FromBody] 中读取的 MongoDB GeoJsonObjectModel成员总是null
    《.NET 微服务:适用于容器化 .NET 应用的体系结构》关键结论
    SQL数据库注入防范 ASP.NET Globle警告
    数据库中的恶意字符批处理
  • 原文地址:https://www.cnblogs.com/holiday2000/p/9667263.html
Copyright © 2011-2022 走看看