如何使Spring Security接受JSON而不是表单参数?

Mat*_*ble 7 java spring-security spring-boot jhipster

我正在尝试更改JHipster,因此它使用JSON对象进行身份验证而不是表单参数.我已经成功地为其JWT认证机制做了这项工作.现在我想为其他身份验证选项做这件事.

是否有一种简单的方法可以更改Spring Security的默认安全配置以允许此操作?以下是JHipster现在使用的内容:

.and()
    .rememberMe()
    .rememberMeServices(rememberMeServices)
    .rememberMeParameter("remember-me")
    .key(env.getProperty("jhipster.security.rememberme.key"))
.and()
    .formLogin()
    .loginProcessingUrl("/api/authentication")
    .successHandler(ajaxAuthenticationSuccessHandler)
    .failureHandler(ajaxAuthenticationFailureHandler)
    .usernameParameter("j_username")
    .passwordParameter("j_password")
    .permitAll()
Run Code Online (Sandbox Code Playgroud)

我想发送以下作为JSON而不是表单参数:

{username: "admin", password: "admin", rememberMe: true}
Run Code Online (Sandbox Code Playgroud)

jlu*_*etu 0

我就做过这样的事。解决方案并不困难,但我做了主要基于 UserNamePasswordAuthenticationFilter 创建自定义安全过滤器的技巧。

实际上,您应该重写attemptsAuthentication方法。仅重写 getPassword 和 acquireUsername 可能还不够,因为您想要读取请求正文,并且必须同时对这两个参数执行此操作(如果您不创建一种多读取 HttpServletRequest 包装器)

解决方案必须是这样的:

    public class JsonUserNameAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
    //[...]
    public Authentication attemptAuthentication(HttpServletRequest request,
                HttpServletResponse response) throws AuthenticationException {
            if (postOnly && !request.getMethod().equals("POST")) {
                throw new AuthenticationServiceException(
                        "Authentication method not supported: " + request.getMethod());
            }

    UsernamePasswordAuthenticationToken authRequest =
            this.getUserNamePasswordAuthenticationToken(request);

            // Allow subclasses to set the "details" property
            setDetails(request, authRequest);

            return this.getAuthenticationManager().authenticate(authRequest);
        }
        //[...]

protected UserNamePasswordAuthenticationToken(HttpServletRequest request){
    // here read the request body and retrieve the params to create a UserNamePasswordAuthenticationToken. You may use jackson of whatever you like most
}
//[...]
}
Run Code Online (Sandbox Code Playgroud)

然后您必须对其进行配置。对于这种复杂的配置,我总是使用基于 xml 的配置,

    <beans:bean id="jsonUserNamePasswordAuthenticationFilter" 
                class="xxx.yyy.JsonUserNamePasswordAuthenticationFilter">
            <beans:property name="authenticationFailureHandler>
                <beans:bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
                    <!-- set the failure url to a controller request mapping returning failure response body.
                    it must be NOT secured -->
                </beans:bean>
            </beans:property>
            <beans:property name="authenticationManager" ref="mainAuthenticationManager" />
            <beans:property name="authenticationSuccessHandler" >
                <beans:bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
                    <!-- set the success url to a controller request mapping returning success response body.
                    it must be secured -->
                </beans:bean>
            </beans:property>
        </beans:bean>

        <security:authentication-manager id="mainAuthenticationManager">                
            <security:authentication-provider ref="yourProvider" />
        </security:authentication-manager>

<security:http pattern="/login-error" security="none"/>
    <security:http pattern="/logout" security="none"/>

<security:http pattern="/secured-pattern/**" auto-config='false' use-expressions="false"
        authentication-manager-ref="mainAuthenticationManager" 
        create-session="never" entry-point-ref="serviceAccessDeniedHandler">
        <security:intercept-url pattern="/secured-pattern/**" access="ROLE_REQUIRED" />
        <security:custom-filter ref="jsonUserNamePasswordAuthenticationFilter" 
            position="FORM_LOGIN_FILTER" />     
        <security:access-denied-handler ref="serviceAccessDeniedHandler"/>
        <security:csrf disabled="true"/>
    </security:http>
Run Code Online (Sandbox Code Playgroud)

您可以创建一些额外的对象作为访问拒绝处理程序,但这是最简单的部分