How can I authenticate a system user for scheduled processes in Spring?

杀马特。学长 韩版系。学妹 提交于 2019-11-28 07:13:34

问题


we have a Quartz/Spring Batch job, that for audit logging purposes we'd like to have it "authenticated" as a system user. Some of our methods rely on fetching the SecurityContext to do this. The ways of running this job are trusted (or authenticated). We don't want to actually use a password or other token (since the process is basically always spawned by quartz).

I tried this

private void authenticate() {
    UserDetails admin = userDetailsService.loadUserByUsername( "admin" );

    RunAsUserToken token = new RunAsUserToken(
            UUID.randomUUID().toString(), admin, admin.getAuthorities(), null , null );

    Authentication user = authenticationManager.authenticate( token );

    if ( user.isAuthenticated() ) {
        SecurityContext sc = new SecurityContextImpl();
        sc.setAuthentication( user );
        SecurityContextHolder.setContext( sc );
    }
}

but it resulted in

org.springframework.security.authentication.ProviderNotFoundException: No AuthenticationProvider found for org.springframework.security.access.intercept.RunAsUserToken

and I'm not sure what some of RunAsUserToken parameters do (e.g. key) or what I should be giving it in regards to Credentials.

How can I authenticate or otherwise set the security context as if it was authenticated as this user?


回答1:


I'm not sure yet about the RunAsUserToken. I think it is intended to be used when someone is already authenticated, but the application what to execute something as another user.

I found an example of using it here.

But, maybe you don't really need that. If it is the case, you could just do :

Authentication auth = new UsernamePasswordAuthenticationToken(admin.getUsername(), admin.getPassword(), admin.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);

And then admin will be authenticated. Also, you don't need to use admin.getPassword() since it won't be checked anyway.

Note that you don't have to create the security context : it already exists. I think it is ThreadLocal by default.



来源:https://stackoverflow.com/questions/29684505/how-can-i-authenticate-a-system-user-for-scheduled-processes-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!