【问题标题】:Configure Spring Security to return JSON response after authentication配置 Spring Security 以在认证后返回 JSON 响应
【发布时间】:2020-07-21 22:30:55
【问题描述】:

我有一个在 Spring 4 中使用 UI 作为 JSP 的遗留应用程序。需要将表示层从 spring 移动到 react 应用程序。当我使用参数调用 /login 时,它给了我一个 HTML,如何更改我现有的 spring 安全逻辑,以便它返回一个 json 响应。

这里是代码sn-p

protected void configure(HttpSecurity http) throws Exception {      
        http.sessionManagement().maximumSessions(1).and().invalidSessionUrl(URLConstants.LOGIN_URL);
        http.csrf().disable();
        http.anonymous().disable()
                .authorizeRequests().antMatchers("/")
                .access("hasRole('USER') or hasRole('ADMIN') or hasRole('DC MANAGER')")
.and().formLogin()          .loginProcessingUrl(URLConstants.LOGIN_URL).usernameParameter("ssoId").passwordParameter("password").and()
.rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository)               .tokenValiditySeconds(18400).and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }

【问题讨论】:

    标签: spring session spring-security


    【解决方案1】:

    编写一个自定义的 AuthenticationSuccessHandler 来编写您的 JSON 并将其插入您的 formLogin()。

    .formLogin().successHandler(yourSucessHandlerBean);
    

    您的处理程序大致如下所示:

    @Component
    public class Securityhandler implements AuthenticationSuccessHandler {
    
     public void onAuthenticationSuccess(HttpServletRequest request,   HttpServletResponse response, Authentication authentication) throws IOException  {
        // write your JSON here, directly to the HttpServletResponse
     }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      相关资源
      最近更新 更多