使用inMemoryAuthentication的无状态会话(JWT)始终失败

时间:2018-09-10 10:21:37

标签: spring-security jwt in-memory

我正在尝试通过跟踪/复制https://github.com/murraco/spring-boot-jwt来实现JWT,但是由于我不需要多个用户,所以我想使用内置的inMemoryAuthentication

这是我的WebSecurityConfig

的精简版
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final JwtTokenProvider jwtTokenProvider;

    @Autowired
    public SecurityConfiguration(JwtTokenProvider jwtTokenProvider) {    
        this.jwtTokenProvider = jwtTokenProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .addFilterBefore(new JwtTokenFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class)
            .and()
            .exceptionHandling().authenticationEntryPoint((req, res, e) -> res.sendError(HttpServletResponse.SC_UNAUTHORIZED))            
            .authorizeRequests()
            .antMatchers("/test/**").hasRole("ROLE_TEST")
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("{noop}admin")
                .roles("ROLE_TEST");
    }

    @Bean
    public AuthenticationService authenticationService() throws Exception {
        return new AuthenticationService(jwtTokenProvider, authenticationManager());
    }

}

我将JwtTokenProvider修改为使用InMemoryUserDetailsManager,而不是连接到数据库的自定义用户详细信息服务。

现在,当我使用用户名和密码访问/login端点时,我会得到一个有效的jwt令牌,但是当我尝试在/test方法上使用该令牌时,它将失败,因为它找不到用户。调试中,我可以看到userDetailsManager

public Authentication getAuthentication(String token) {
    UserDetails userDetails = userDetailsManager.loadUserByUsername(getUsername(token));
    return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
}

不包含在WebSecurityConfig中添加的用户。 谁能告诉我为什么? InMemoryAuthentication仅适用于会话/状态认证方法吗?我以为它会将所有用户/信条存储在一个全局单例bean中,该bean随处可见...

0 个答案:

没有答案