首页 > 解决方案 > Javascript WebApp的Spring Security Oauth2身份验证

问题描述

我目前正在后端开发一个带有 Spring Boot REST API 的 React WebApp。我想使用 OAuth2 来保护 API(并提高我的知识)。但是,我对要使用的正确身份验证流程有一些疑问。

由于前端使用的是 JavaScript,我不应该使用需要客户端密码的流。

Spring 中唯一不需要客户端密码的流是隐式流。但是,使用此流程,Spring 不支持刷新令牌。这意味着一段时间后,用户将自动注销并需要再次授权 WebApp。

我看到的另一个选项是创建一个没有秘密的客户端,然后使用授权码流程。但我怀疑这是否是正确的方法。

所以我的问题基本上是:当我不希望用户在一段时间后注销时,哪个是与 Javascript 前端一起使用的最佳 OAuth2 流程?

网络安全配置

@Configuration
@EnableWebSecurity
@Import(Encoders.class)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsServiceImpl;

    @Autowired
    private PasswordEncoder userPasswordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsServiceImpl).passwordEncoder(userPasswordEncoder);
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .formLogin().permitAll()
                .and()
                .authorizeRequests().antMatchers("/login", "/error**").permitAll()
                .anyRequest().authenticated();
    }
}

资源服务器配置

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "resource-server-rest-api";
    private static final String SECURED_READ_SCOPE = "#oauth2.hasScope('read')";
    private static final String SECURED_WRITE_SCOPE = "#oauth2.hasScope('write')";
    private static final String SECURED_PATTERN = "/api/**";

    @Autowired
    private DefaultTokenServices tokenServices;

    @Autowired
    private TokenStore tokenStore;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID)
            .tokenServices(tokenServices)
            .tokenStore(tokenStore);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.antMatcher(SECURED_PATTERN).authorizeRequests().anyRequest().authenticated();
    }
}

OAuth2Config

@Configuration
@PropertySource({"classpath:persistence.properties"})
@EnableAuthorizationServer
@Import(WebSecurityConfig.class)
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

    @Autowired
    private UserDetailsService userDetailsServiceImpl;

    @Autowired
    private PasswordEncoder oauthClientPasswordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;


    @Bean
    public OAuth2AccessDeniedHandler oauthAccessDeniedHandler() {
        return new OAuth2AccessDeniedHandler();
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(
                new ClassPathResource("mykeys.jks"),
                "mypass".toCharArray());

        converter.setKeyPair(keyStoreKeyFactory.getKeyPair("mykeys"));
        return converter;
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        defaultTokenServices.setTokenEnhancer(accessTokenConverter());
        return defaultTokenServices;
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients().tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                .passwordEncoder(oauthClientPasswordEncoder);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter()));

        endpoints
                .tokenStore(tokenStore())
                .tokenEnhancer(tokenEnhancerChain)
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsServiceImpl);
    }
}

标签: javaspring-securityoauth-2.0spring-security-oauth2

解决方案


Implicit flow适用于根据OAuth2 规范的 JavaScript 实现

隐式流不支持刷新令牌。spring 实现遵循Oauth2 规范

在 Javascript 客户端实现的情况下,令牌存储在客户端上。使用刷新令牌时,需要将刷新令牌持久化在客户端,以便日后获取新的访问令牌。如果是这种情况,您不妨发出一个长期(更)持久的访问令牌而不是刷新令牌。在客户端工作时,使用刷新令牌没有任何优势。


推荐阅读