Getting Start

官方文档学习

基本概念

  • Spring security解决的问题
    1. 认证(你是谁)
    2. 授权(你能干什么)
    3. 开启一些主要的安全防护功能

Web Security

  • Maven dependency
    1. org.springframework.security : spring-security-web
    2. org.springframework.security : spring-security-config
  • @EnableWebSecurity
    1. 为所有的URL加入身份认证,并提供一个登陆界面
    2. 防止CSRF[Cross-Site Request Forgery] : 跨站域请求伪造
    3. 防止Session Fixation : 通过修改登录后的Session id防止Session 固定
    4. Security Header integration
      1. 开启HSTS功能,使浏览器使用https
      2. X-Content-Type-Options: nosniff :禁用浏览器类型猜测
      3. X-XSS-Protection: 1; mode=block : 开启浏览器XSS保护
      4. x-frame-options: DENY: 开启点击挟持保护,不允许被任何页面嵌入
      5. Cache-Control: no-cache, no-store, max-age=0, must-revalidate : 禁止浏览器缓存
    5. 整合了HttpServletRequest的以下方法
      1. login(username, password)/logout()
      2. getRemoteUser()/getUserPrincipal()
      3. isUserInRole(role)

认证/授权详解

创建用户

  • UserBuilder
    1. User.withDefaultPasswordEncoder() : 测试时可以使用这个方法创建UserBuilder
    2. username/password/roles
  • AuthenticationManagerBuilder
    1. spring security 会自动实例化一个对象
    2. withUser : 接受username和UserBuilder
    3. password/roles

认证匹配和授权

  • WebSecurityConfigurerAdapter
    1. configure(HttpSecurity http) : 提供了HttpSecurity
    2. 通过继承覆盖configure方法来自定义HttpSecurity
  • HttpSecurity
    1. authorizeRequests()
      1. anyRequest() : 匹配所以请求
        1. permitAll() : 无需认证
        2. authenticated() : 认证后访问
        3. hasRole/hasAnyRole : 某些用户角色可以访问
        4. hasAuthority/hasAntAuthority : 某些用户角色可以访问,role前面要加ROLE_
        5. hasIpAddress : 限定某个ip,只能指定一个
        6. fullyAuthenticated : 禁止Remember-Me功能,只能进行手动认证
        7. access() : 复合表达式:"hasRole('ADMIN') and hasRole('DBA')"
      2. antMatchers(antPatterns) : 匹配某些路径
      3. antMatchers(method) : 匹配某种HttpMethod
      4. antMatchers(method, antPatterns) :结合以上两种方式
      5. rememberMe() : 自动登录
        1. https://blog.csdn.net/zeketao/article/details/79608229
    2. httpBasic() : 允许用户进行http访问
    3. formLogin() : 提供一个自带的登录页面
      1. loginPage(url) : 自定义url
      2. failureUrl(url) : 自定义登录失败页面
    4. logout()
      1. POST请求发送/logout
      2. logoutUrl(url) : 自定义url
      3. logoutSuccessUrl(url) : 自定义返回url
      4. 使用GET:logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))

Spring security with Spring boot

  • spring boot会自动监测classpath下的spring security依赖包,如果有,会自动启动@EnableWebSecurity
  • 除了与@EnableWebSecurity具有相同功能外,会自动创建一个User,名字是user,Password随机打印于启动日志
  • 修改User/Password
    1. spring.security.user.name
    2. spring.security.user.password