首页 > 解决方案 > 使用 Basic Auth 授权每个请求 Spring Boot

问题描述

我正在构建一个 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();
    }

标签: springbasic-authentication

解决方案


您可以编写自定义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();

检查它 -在这里


推荐阅读