1

这个问题是在 Ratpack RequestFixtureSpock 测试的上下文中,用于通过 进行身份验证的 Ratpack 链RatpackPac4j#requireAuth,并对缺少的WWW-Authenticate标头采用解决方法(如本问题的答案中所述)

我遇到的问题是,我发现从(的包装器)#beforeSend获得响应时似乎没有调用它。解决方法取决于此工作,因此我无法对其进行测试。有没有办法在返回的响应上调用?GroovyRequestFixture#handleRequestFixture#handle#beforeSendHandlingResult

例如,此测试用例会因断言存在WWW-Authenticate标头而失败,即使改编自此的代码在实际应用程序中调用时正确插入了标头。被测链是testChain,跳到最后失败的断言:

package whatever

import com.google.inject.Module
import groovy.transform.Canonical
import groovy.transform.CompileDynamic
import groovy.transform.CompileStatic
import org.pac4j.core.profile.jwt.JwtClaims
import org.pac4j.http.client.direct.HeaderClient
import org.pac4j.jwt.config.encryption.EncryptionConfiguration
import org.pac4j.jwt.config.encryption.SecretEncryptionConfiguration
import org.pac4j.jwt.config.signature.SecretSignatureConfiguration
import org.pac4j.jwt.config.signature.SignatureConfiguration
import org.pac4j.jwt.credentials.authenticator.JwtAuthenticator
import org.pac4j.jwt.profile.JwtGenerator
import org.pac4j.jwt.profile.JwtProfile
import ratpack.groovy.handling.GroovyChainAction
import ratpack.groovy.test.handling.GroovyRequestFixture
import ratpack.guice.Guice
import ratpack.http.Response
import ratpack.http.Status
import ratpack.jackson.Jackson
import ratpack.pac4j.RatpackPac4j
import ratpack.registry.Registry
import ratpack.session.SessionModule
import ratpack.test.handling.HandlerExceptionNotThrownException
import ratpack.test.handling.HandlingResult
import spock.lang.Specification

@CompileStatic
class AuthenticatorTest extends Specification {
    static byte[] salt = new byte[32] // dummy salt

    static SignatureConfiguration signatureConfiguration = new SecretSignatureConfiguration(salt)
    static EncryptionConfiguration encryptionConfiguration = new SecretEncryptionConfiguration(salt)
    static JwtAuthenticator authenticator = new JwtAuthenticator(signatureConfiguration, encryptionConfiguration)
    static JwtGenerator generator = new JwtGenerator(signatureConfiguration, encryptionConfiguration)
    static HeaderClient headerClient = new HeaderClient("Authorization", "bearer ", authenticator)

    /** A stripped down user class */
    @Canonical
    static class User {
        final String id
    }

    /** A stripped down user registry class */
    @Canonical
    static class UserRegistry {
        private final Map<String, String> users = [
            'joebloggs': 'sekret'
        ]

        User authenticate(String id, String password) {
            if (password != null && users[id] == password)
               return new User(id)
            return null
        }
    }

    /** Generates a JWT token for a given user
     *
     * @param userId - the name of the user
     * @return A JWT token encoded as a string
     */
    static String generateToken(String userId) {
        JwtProfile profile = new JwtProfile()
        profile.id = userId
        profile.addAttribute(JwtClaims.ISSUED_AT, new Date())
        String token = generator.generate(profile)
        token
    }

    static void trapExceptions(HandlingResult result) {
        try {
            Throwable t = result.exception(Throwable)
            throw t
        }
        catch (HandlerExceptionNotThrownException ignored) {
        }
    }

    /** Composes a new registry binding the module class passed
     * as per SO question https://stackoverflow.com/questions/50814817/how-do-i-mock-a-session-in-ratpack-with-requestfixture
     */
    static Registry addModule(Registry registry, Class<? extends Module> module) {
        Guice.registry { it.module(module) }.apply(registry)
    }

    GroovyChainAction testChain = new GroovyChainAction() {
        @Override
        @CompileDynamic
        void execute() throws Exception {

            register addModule(registry, SessionModule)

            all RatpackPac4j.authenticator(headerClient)

            all {
                /*
                 * This is a workaround for an issue in RatpackPac4j v2.0.0, which doesn't
                 * add the WWW-Authenticate header by itself.
                 *
                 * See https://github.com/pac4j/ratpack-pac4j/issues/3
                 *
                 * This handler needs to be ahead of any potential causes of 401 statuses
                 */
                response.beforeSend { Response response ->
                    if (response.status.code == 401) {
                        response.headers.set('WWW-Authenticate', 'bearer realm="authenticated api"')
                    }
                }
                next()
            }

            post('login') { UserRegistry users ->
                parse(Jackson.fromJson(Map)).then { Map data ->
                    // Validate the credentials
                    String id = data.user
                    String password = data.password
                    User user = users.authenticate(id, password)
                    if (user == null) {
                        clientError(401) // Bad authentication credentials
                    } else {
                        response.contentType('text/plain')

                        // Authenticates ok. Issue a JWT token to the client which embeds (signed, encrypted)
                        // certain standardised metadata of our choice that the JWT validation will use.
                        String token = generateToken(user.id)
                        render token
                    }
                }
            }

            get('unprotected') {
                render "hello"
            }

            // All subsequent paths require authentication
            all RatpackPac4j.requireAuth(HeaderClient)

            get('protected') {
                render "hello"
            }

            notFound()
        }
    }

    @CompileDynamic
    def "should be denied protected path, unauthorised..."() {
        given:
        def result = GroovyRequestFixture.handle(testChain) {
            uri 'protected'
            method 'GET'
        }

        expect:
        result.status == Status.of(401) // Unauthorized


        // THIS FAILS BECAUSE Response#beforeSend WASN'T INVOKED BY GroovyRequestFixture
        result.headers['WWW-Authenticate'] == 'bearer realm="authenticated api"'

        // If the server threw, rethrow that
        trapExceptions(result)
    }
}
4

1 回答 1

1

迄今为止的最佳答案......或者更严格地说,避开 , 限制的解决方法RequestFixture是:不要使用RequestFixture. 利用GroovyEmbeddedApp

(归功于 Ratpack 松弛频道上的Dan Hyun )

RequestFixture 仅用于检查处理程序的行为,它不会做很多事情 - 它不会序列化响应。EmbeddedApp可能是大多数测试的方式。你会更关心整体交互而不是单个处理程序如何做某事,除非它是一个高度重用的组件或者是其他应用程序使用的中间件

上面示例的修改版本如下,我在评论中标记了修改的部分:

package whatever

import com.google.inject.Module
import groovy.transform.Canonical
import groovy.transform.CompileDynamic
import groovy.transform.CompileStatic
import org.pac4j.core.profile.jwt.JwtClaims
import org.pac4j.http.client.direct.HeaderClient
import org.pac4j.jwt.config.encryption.EncryptionConfiguration
import org.pac4j.jwt.config.encryption.SecretEncryptionConfiguration
import org.pac4j.jwt.config.signature.SecretSignatureConfiguration
import org.pac4j.jwt.config.signature.SignatureConfiguration
import org.pac4j.jwt.credentials.authenticator.JwtAuthenticator
import org.pac4j.jwt.profile.JwtGenerator
import org.pac4j.jwt.profile.JwtProfile
import ratpack.groovy.test.embed.GroovyEmbeddedApp
import ratpack.guice.Guice
import ratpack.http.Response
import ratpack.http.Status
import ratpack.http.client.ReceivedResponse
import ratpack.jackson.Jackson
import ratpack.pac4j.RatpackPac4j
import ratpack.registry.Registry
import ratpack.session.SessionModule
import ratpack.test.handling.HandlerExceptionNotThrownException
import ratpack.test.handling.HandlingResult
import ratpack.test.http.TestHttpClient
import spock.lang.Specification

@CompileStatic
class TempTest extends Specification {
    static byte[] salt = new byte[32] // dummy salt

    static SignatureConfiguration signatureConfiguration = new SecretSignatureConfiguration(salt)
    static EncryptionConfiguration encryptionConfiguration = new SecretEncryptionConfiguration(salt)
    static JwtAuthenticator authenticator = new JwtAuthenticator(signatureConfiguration, encryptionConfiguration)
    static JwtGenerator generator = new JwtGenerator(signatureConfiguration, encryptionConfiguration)
    static HeaderClient headerClient = new HeaderClient("Authorization", "bearer ", authenticator)

    /** A stripped down user class */
    @Canonical
    static class User {
        final String id
    }

    /** A stripped down user registry class */
    @Canonical
    static class UserRegistry {
        private final Map<String, String> users = [
            'joebloggs': 'sekret'
        ]

        User authenticate(String id, String password) {
            if (password != null && users[id] == password)
                return new User(id)
            return null
        }
    }

    /** Generates a JWT token for a given user
     *
     * @param userId - the name of the user
     * @return A JWT token encoded as a string
     */
    static String generateToken(String userId) {
        JwtProfile profile = new JwtProfile()
        profile.id = userId
        profile.addAttribute(JwtClaims.ISSUED_AT, new Date())
        String token = generator.generate(profile)
        token
    }

    static void trapExceptions(HandlingResult result) {
        try {
            Throwable t = result.exception(Throwable)
            throw t
        }
        catch (HandlerExceptionNotThrownException ignored) {
        }
    }

    /** Composes a new registry binding the module class passed
     * as per SO question https://stackoverflow.com/questions/50814817/how-do-i-mock-a-session-in-ratpack-with-requestfixture
     */
    static Registry addModule(Registry registry, Class<? extends Module> module) {
        Guice.registry { it.module(module) }.apply(registry)
    }

    /*** USE GroovyEmbeddedApp HERE INSTEAD OF GroovyResponseFixture ***/
    GroovyEmbeddedApp testApp = GroovyEmbeddedApp.ratpack {
        bindings {
            module SessionModule
        }

        handlers {
            all RatpackPac4j.authenticator(headerClient)

            all {
                /*
                 * This is a workaround for an issue in RatpackPac4j v2.0.0, which doesn't
                 * add the WWW-Authenticate header by itself.
                 *
                 * See https://github.com/pac4j/ratpack-pac4j/issues/3
                 *
                 * This handler needs to be ahead of any potential causes of 401 statuses
                 */
                response.beforeSend { Response response ->
                    if (response.status.code == 401) {
                        response.headers.set('WWW-Authenticate', 'bearer realm="authenticated api"')
                    }
                }
                next()
            }

            post('login') { UserRegistry users ->
                parse(Jackson.fromJson(Map)).then { Map data ->
                    // Validate the credentials
                    String id = data.user
                    String password = data.password
                    User user = users.authenticate(id, password)
                    if (user == null) {
                        clientError(401) // Bad authentication credentials
                    } else {
                        response.contentType('text/plain')

                        // Authenticates ok. Issue a JWT token to the client which embeds (signed, encrypted)
                        // certain standardised metadata of our choice that the JWT validation will use.
                        String token = generateToken(user.id)
                        render token
                    }
                }
            }

            get('unprotected') {
                render "hello"
            }

            // All subsequent paths require authentication
            all RatpackPac4j.requireAuth(HeaderClient)

            get('protected') {
                render "hello"
            }

            notFound()
        }
    }


    /*** THIS NOW ALTERED TO USE testApp ***/
    @CompileDynamic
    def "should be denied protected path, unauthorised..."() {
        given:
        TestHttpClient client = testApp.httpClient
        ReceivedResponse response = client.get('protected')

        expect:
        response.status == Status.of(401) // Unauthorized
        response.headers['WWW-Authenticate'] == 'bearer realm="authenticated api"'
    }
}
于 2018-06-21T08:46:03.223 回答