因为引入spring security之后,前端请求的所有路径都要进行登录才能响应,我现在我想用我自己的登录路径让用户登录,不用spring security内置的登录,怎么办呢?这就要放行你自己的login路径。
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
http
.authorizeHttpRequests((authz) -> authz
.requestMatchers(new AntPathRequestMatcher("/login2")).permitAll()
.anyRequest().authenticated()
).httpBasic(withDefaults()).csrf().disable()
;
return http.build();
}
注意一定要把csrf给禁用了!!
接下来仿造官网的认证过程:
1. 添加一个AuthenticationManager到Bean中
由上图可以看到用户名密码是由AuthenticationManager
来认证的,而ProviderManager
是其一个实现类:
所以这里要整一个ProviderManager
注意:打箭头的地方不能new一个UserDetailsService,要用之前写的那个注入进来
@Resource
CustomUserDetailsService userDetailsService;
@Bean
public AuthenticationManager authenticationManager(){
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
return new ProviderManager(daoAuthenticationProvider);
}
ProviderManager
的构造参数中要放什么东西?
ProviderManager
中可以注入多个AuthenticationProvider
,其中DaoAuthenticationProvider
是用来验证用户名和密码的一种AuthenticationProvider
2. 验证用户
根据途中的过程,第一步就是创建一个UsernamePasswordAuthenticationToken
,其中的构造参数就是用户名和密码。第二步就是交给创建好的AuthenticationManager
进行验证。
@Resource
AuthenticationManager authenticationManager;
@PostMapping("/login2")
public String login(@ModelAttribute LoginParams loginParams){
//1. 创建一个UsernamePasswordAuthenticationToken
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginParams.getUsername(), loginParams.getPassword());
//2. 使用authenticationManager进行认证
Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
//3. 检查是否认证成功:null就是不成功
if(authentication == null) return "failed";
return "success";
}