SpringBoot集成SpringSecurity(七、退出成功响应Json)

前言

前面介绍了登录失败时候响应的Json,下面接着介绍退出成功时响应Json

实现

跟之前一样,新建一个SignOutSuccessHandler类,实现以下代码

@Component
public class SignOutSuccessHandler implements LogoutSuccessHandler {
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication
            authentication) throws IOException {
        Result success = Result.ok().message("退出成功!");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(JsonUtil.toJsonString(success));
    }
}

还是在SpringSecurityConfig类中,首先注入SignOutSuccessHandler对象,然后进行配置

    @Autowired
    SignOutSuccessHandler signOutSuccessHandler;
	http.logout()
   		.logoutSuccessHandler(signOutSuccessHandler);

启动项目,在浏览器先进行登录,然后通过http://localhost:8080/logout进行退出
在这里插入图片描述

完整代码

@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    SignInSuccessHandler signInSuccessHandler;

    @Autowired
    SignInFailureHandler signInFailureHandler;

    @Autowired
    SignOutSuccessHandler signOutSuccessHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user")
                .password(passwordEncoder().encode("123"))
                .authorities("user");
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password(passwordEncoder().encode("123"))
                .authorities("admin");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .successHandler(signInSuccessHandler)
                .failureHandler(signInFailureHandler);
        http.logout()
                .logoutSuccessHandler(signOutSuccessHandler);
        http.authorizeRequests()
                .antMatchers("/user").hasAuthority("user")
                .antMatchers("/admin").hasAuthority("admin")
                .anyRequest().authenticated();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值