使用 Basic Auth 授权每个请求 Spring Boot

时间:2021-06-08 16:37:29

标签: spring basic-authentication

我正在构建一个具有不同路径的 REST api,用于控制来自移动应用程序的数据输入(您猜对了,它扮演前端的角色)。我仍处于应用程序开发的第一阶段,现在我正在测试我的授权会话。我选择了基本身份验证(httpBasic() - 作为方法的名称),我希望移动应用程序向服务器发出的每个请求都经过身份验证。因为,目前,如果我认证一次,下次不需要发送认证数据。这可能吗?这是授权的功能:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/**").hasAuthority("ROLE_USER")
                .anyRequest().authenticated()
                .and()
                .httpBasic()
                .and().logout()
                    .clearAuthentication(true)
                    .invalidateHttpSession(true)
                    .logoutSuccessUrl("/")
                    .permitAll();
    }

1 个答案:

答案 0 :(得分:1)

您可以编写自定义 Success Handler 来处理它。

喜欢:

.logout()
    .logoutSuccessHandler(new LogoutSuccessHandler() {

        @Override
        public void onLogoutSuccess(HttpServletRequest request,
                    HttpServletResponse response, Authentication authentication)
                throws IOException, ServletException {
            CustomerUserDetails userDetails = (CustomerUserDetails) authentication.getPrincipal();
            String username = userDetails.getUsername();

            System.out.println("The user " + username + " has logged out.");

            response.sendRedirect(request.getContextPath());
        }
    })
    .permitAll();

检查一下 - Here

相关问题