2012-05-04 10 views
0

マイセットアップSpring Security:コンテキストBeanのinitメソッドから保護されたサービスにアクセスするには?

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

私は豆のinit()メソッドからこのサービスを利用しようとしている:Spring MVCの3.1アプリケーションで

は、私は春のセキュリティ保護されたサービスを持っています私のコンテキスト内に宣言:

<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はどのようにしてサービスを使用できるように "認証"できますか?

答えて

0

ユーザーが認証されていない場合、自分の役割を確認する方法はありません。メソッドを呼び出す前にそのBeanを認証したい場合は、次のようにして試してみてください。

SecurityContextHolder.getContext().setAuthentication(new user here); 
User test = userService.getUser(1); 
+0

"internal"アクションではこれを行う必要はありませんでしたが、確かに! ROLE_SYSTEMロールを持つ「システム」ユーザーを作成し、そのユーザーを自分のシステム・アクションに使用します。ありがとう。 – electrotype

関連する問題