0
点赞
收藏
分享

微信扫一扫

Spring Security密码认证源码级讲解

一、前言

二、debug启动springboot应用

1、由于我们在MvcConfig配置文件中进行如下配置,所以访问localhost:9090会跳转home.html

/**
 * @author yunqing
 */
@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        //注意:这里配置了 / 跳转home.html页面
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
    }

}

1.1、application.yml中配置了端口为9090

server:
  port: 9090

1.2、我在WebSecurityConfig中配置了不需要认证就可以访问的页面,其中包含 / 和/home

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                // 所有用户均可访问的资源
                .antMatchers("/css/**", "/js/**","/images/**", "/webjars/**", "**/favicon.ico", "/index").permitAll()
                .antMatchers(HttpMethod.POST, "/user/registration").permitAll()
                .antMatchers("/", "/home","/user/registration","/hello").permitAll()
                //剩下的任何请求都需要进行认证
                .anyRequest().authenticated()
                .and()
                //表单登录
                .formLogin()
                //登录请求页面
                .loginPage("/login")
                //自定义登录成功和失败处理器
                .successHandler(ajaxAuthSuccessHandler)
                .failureHandler(ajaxAuthFailHandler)
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

2、看完上面的基本介绍,接下来我们进入了第一个断点

2.1、这里扩展一下spring security过滤器链

2.2、通过获取共享在多个请求之间的用户信息

/**
 * @author yunqing
 * @Date 2019/12/15 16:44
 */
@Slf4j
@RestController
@RequestMapping("/api/account")
public class SecurityController {

    @GetMapping("/me")
    public Object getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}

2.3、获取当前认证用户信息

#返回结果,证明当前认证成功的是匿名用户

{"authorities":[{"authority":"ROLE_ANONYMOUS"}],"details":
{"remoteAddress":"0:0:0:0:0:0:0:1","sessionId":"45C0AA46462B773A0606D24C91D70722"},
"authenticated":true,"principal":"anonymousUser","keyHash":431445726,"credentials":"",
"name":"anonymousUser"}

3、正式开始讲解数据库中的用户认证

3.1、点击Sign In登录跳转到第一个断点UsernamePasswordAuthenticationFilter

举报

相关推荐

0 条评论