2

Servlet 3.0、Spring MVC、および Spring Security を使用して、安全な安らかな Web サービスを作成しようとしています。サーブレット コンテナーによって返されるデフォルトの HTML メッセージではなく、401 でカスタム JSON メッセージを返したいと考えています。

いくつかのアプローチを試しましたが、これを機能させることができないようです。

私のコントローラーは次のようになります::

@Controller
@RequestMapping("/")
public class ApplicationController {

    private ApplicationFactory applicationFactory;

    @Inject
    public ApplicationController(ApplicationFactory applicationFactory) {
        super();
        this.applicationFactory = applicationFactory;
    }

    @RequestMapping(method = GET)
    @ResponseBody
    @Secured("ROLE_USER")
    public Application getApplicationInfo() {
        return applicationFactory.buildApplication(this);
    }

}

そして、私の Spring Security コンテキストは次のようになります。

<security:global-method-security secured-annotations="enabled" mode="aspectj" />

<security:http auto-config="true" use-expressions="true">
<security:http-basic />
</security:http>

私は以下を追加しようとしました:

@ExceptionHandler(AccessDeniedException.class)
@ResponseBody
public Application accessDenied() {
    return applicationFactory.buildApplication(this);
}

しかし、それは無視されます。"access-denied-page="/denied"" を security:http タグに追加して、コントローラーで次のようにしました。

@RequestMapping(value = "/denied", method = GET)
@ResponseBody
public Application accessDenied() {
    return applicationFactory.buildApplication(this);
}

しかし、それは無視されます。次のように、カスタムのアクセス拒否ハンドラーを試しました。

<security:http auto-config="true" use-expressions="true">
<security:http-basic />
<security:access-denied-handler ref="jsonAccessDeniedHandler" />
</security:http>

機能しているように見える唯一のことは次のとおりです。

@ExceptionHandler(Exception.class)
@ResponseBody
public Application accessDenied() {
    return applicationFactory.buildApplication(this);
}

しかし、これはすべてをキャッチし、失敗した認証のみをカスタマイズしたいと考えています。

最後に、これを私の web.xml に追加することもできます:

<error-page>
<error-code>401</error-code>
<location>/401</location>
</error-page>

しかし、プログラムまたは注釈を使用して、できるだけ多くの構成をしたいと思います。

4

2 に答える 2

4

Spring 3.0 にはアノテーション ResponseStatus があります

この注釈を次のように使用します。

@ResponseStatus(value = 401)
@ExceptionHandler(value = HttpMessageNotReadableException.class)
@ResponseBody
public ErrorResponse handleJsonMappingException(HttpMessageNotReadableException e) {

これは役に立ちましたか?

于 2012-07-12T09:17:40.357 に答える
0

@ResponseBody を使用して応答ヘッダーを操作するには、次のようにします。

@RequestMapping(value = "/url", method = RequestMethod.GET, headers = { "Accept=application/json" })
public @ResponseBody
List handle(HttpServletResponse response,
@RequestHeader("headerID") String headerString) {
response.setHeader("responseHeaderProperty", String);
return service.doSomething();
}
于 2012-07-12T11:26:54.503 に答える