spring-boot-security使用json请求登陆

1、在网上找了一些别人的作法,发现都没有实现我的效果,看来只能自己写呢
2、我要的效果是我在postman发post登录请求,返回一个jsessionId,我用这个jsessionId可以再次发起别的请求,我用网上别人提到的一些方法都没有实现,可能是我操作不对。今天自己实现了一方法,记录下,也方便需要使用这种功能的人,减少它搜索的时间。

3、说下我的环境,spring-boot-starter-parent用的是3.0.6,引入spring-boot-starter-web,spring-boot-starter-security
4、我的securityconfig的配置如下:

 @Bean
    SecurityFilterChain  configure(HttpSecurity http) throws Exception {
    
    
            http.addFilterAt(CustomFilter, UsernamePasswordAuthenticationFilter.class)
                .authorizeHttpRequests(authoriz -> authoriz.requestMatchers("/login").permitAll()
                        .anyRequest().authenticated());
                   http .csrf().disable();
        return http.build();
    }

5、需要自定义一个过滤器,代码如下:


```java
@Service
public class CustomFilter extends AbstractAuthenticationProcessingFilter implements InitializingBean {
    
    

    @Resource
    CustomUserDetailsService customUserDetailsService;


    public CustomFilter() {
    
    
        super(new AntPathRequestMatcher("/login", "POST"));

    }

    @Override
    public void afterPropertiesSet() {
    
    
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(customUserDetailsService);
        ProviderManager providerManager = new ProviderManager(daoAuthenticationProvider);
        setAuthenticationManager(providerManager);
        setSecurityContextRepository(new HttpSessionSecurityContextRepository());
        setSessionAuthenticationStrategy(new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()));

    }




    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException{
    
    

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                request.getParameter("username"), request.getParameter("password"));
        this.authenticationDetailsSource.buildDetails(request);
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}

上面的代码说明一下,我把这个过滤器放入spring容器了,为的就是使用它的JPA的功能,也就是引入CustomUserDetailsService这个服务,这个服务就是查我自定义的用户表,我不想写的太多的代码跟文字,这样你们就不太愿意看这个文章。如果你们是使用框架自带的用户表,你们可以去掉daoAuthenticationProvider.setUserDetailsService(customUserDetailsService);
6、关键的代码就是afterPropertiesSet()方法里后面三行(3个set方法)
7、需要在controller文件中加入“/"的请求处理,我使用的是RestController注解,如下:

	@GetMapping("/")
    public ResponseBody home(){
    
    
        ResponseBody responseBody = new ResponseBody();
        responseBody.setMsg("登陆成功!");
        responseBody.setCode("200");
        responseBody.setData(null);
        return responseBody;
    }

按这个配置就可以了。

猜你喜欢

转载自blog.csdn.net/u013326684/article/details/130475527