0

私のセットアップ

Spring MVC 3.1アプリケーションには、SpringSecurityで保護されたサービスがあります。

@PreAuthorize("isAnonymous()") // ("hasRole('USER')") doesn't work either
public interface UserService extends UserDetailsService, PasswordEncoder

私は自分のコンテキストで宣言されたBeanのinit()メソッドからこのサービスを使用しようとしています:

<bean class="com.xxx.scripts.FillDbWithInitialValues" init-method="contextInit" />

クラス :

public class FillDbWithInitialValues
{
    @Autowired
    UserService userService;

    public void contextInit()
    {
        User test = userService.getUser(1);
    }
}

私のsecurity.xmlファイルの抽出:

<sec:global-method-security pre-post-annotations="enabled" />   

<sec:http auto-config="true" use-expressions="true">
    (...)
</sec:http>

<sec:authentication-manager alias="authManager">
    <sec:authentication-provider user-service-ref="userService">
        <sec:password-encoder ref="userService" />
    </sec:authentication-provider>
</sec:authentication-manager>

問題

アプリケーションを起動すると、例外が発生します。

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext

なぜこうなった?Beanを「認証」して、サービスを使用できるようにするにはどうすればよいですか?

4

1 に答える 1

0

認証されたユーザーがいない場合、その役割を確認する方法はありません。メソッドを呼び出す前にその Bean を認証したい場合は、次の方法で何かを試すことができると思います。

SecurityContextHolder.getContext().setAuthentication(new user here);  
User test = userService.getUser(1);
于 2012-05-04T21:10:56.417 に答える