0

私は認証のためにそのようなコードを使用します:

@PreAuthorize("isAnonymous()")
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin(HttpServletRequest request) {
    try {
        Authentication req = new UsernamePasswordAuthenticationToken(request.getParameter("name"),
                request.getParameter("password"));
        Authentication result = authenticationManager.authenticate(req);
        SecurityContextHolder.getContext().setAuthentication(result);
        logger.debug("Success login");
        logger.debug(SecurityContextHolder.getContext().getAuthentication());
        return "index";
    } catch (AuthenticationException e) {
        e.printStackTrace();
        logger.debug("ACHTUNG! Success failed");
        return "index";
    }
}

ログインできます。動作します。ログに null 以外の認証オブジェクトが表示されます。次に、次のような保護されたページを閲覧しようとします。

@PreAuthorize("hasRole('user')")
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String user(ModelMap modelMap) {
    modelMap.addAttribute("user", SecurityContextHolder.getContext().getAuthentication().getCredentials().toString());
    return "index";
}

そして、getAuthentication() のために NullPointerException をスローします。これは、SecurityContextHolder.MODE_GLOBAL の使用とは異なり、SecurityContextHolder.MODE_INHERITABLETHREADLOCAL および SecurityContextHolder.MODE_INHERITABLETHREADLOCAL を使用すると発生します。

私は何を間違っていますか?SecurityContextHolder の MODE_GLOBAL 動作は必要ありません。

UPD:問題が発生することもあれば、同じセッションで発生しないこともあります。

4

1 に答える 1

1

ログを記録して、リクエストのたびにセキュリティ フィルタが実行されていることを確認します。

request.getAttribute("__spring_security_scpf_applied");

しない。何をしているのか完全にわかっていない限り、SecurityContextHolderStrategy を置き換えないでください。これは、ThreadLocal に基づいて SecurityContext を見つけることに関係しています。したがって、非常に奇妙なサーブレット コンテナでない限り、デフォルトはほとんどの場合正しいものです。

また、リクエスト パスのインターセプターを作成する必要があります。@PreAuthorize は、必要ではないメソッド呼び出しhttp://static.springsource.org/spring-security/site/docs/3.0.x/reference/el-access.htmlにのみ適用されます。

代わりに、セキュリティ アプリケーション コンテキストで次のようなものが必要です。

<http> ...
        <intercept-url pattern="/user**" access="hasRole('user')" />
</http>
于 2012-04-17T15:46:50.183 に答える