spring security笔记

原理教程

https://www.bilibili.com/video/av73730658?p=18

spring security 结构

spring security笔记_第1张图片
image.png

spring security 认证流程

spring security笔记_第2张图片
image.png

spring security + jwt github demo

https://github.com/shuaicj/zuul-auth-example

spring security搭建

  • 引入

            org.springframework.boot
            spring-boot-starter-security

  • 配置,认证和授权
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 定制请求的授权规则
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests() // 认证请求
                .antMatchers("/", "/home").permitAll() // 路径匹配,permitAll()允许所有人访问
                .antMatchers("/private").hasRole("admin")// 指定可访问角色
                .anyRequest().authenticated()
                .and()
                .formLogin() // 开启登录模式,不设置就不需要登录
                .loginPage("/login") // 登录页面
                .permitAll()
                .and()
                .rememberMe() // 记住我功能,默认14天
                .and()
                .logout() // 注销,访问/loginout表示注销
                .permitAll()
                .and()
                .csrf().disable(); // 禁止csrf
    }

    /**
     * 定义认证规则
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // todo 通过数据库
        auth.inMemoryAuthentication().withUser("admin").password("admin");
    }
}

你可能感兴趣的:(spring security笔记)