Spring Javascript WebApp 的安全 Oauth2 身份验证
Spring Security Oauth2 Authentication for Javascript WebApp
我目前正在开发一个后端带有 Spring Boot REST API 的 React WebApp。我想使用 OAuth2 来保护 API(并提高我的知识)。但是,我对要使用的正确身份验证流程有一些疑问。
由于前端正在使用 JavaScript 我不应该使用需要客户端密码的流程。
Spring 中唯一不需要客户端密码的流程是隐式流程。但是,对于此流程,Spring 不支持刷新令牌。这意味着一段时间后用户将自动注销并需要再次授权 WebApp。
我看到的另一个选项是创建一个没有密码的客户端,然后使用授权码流程。但是我有点怀疑这是否是正确的方法。
所以我的问题基本上是:当我不希望用户在一段时间后注销时,哪种 OAuth2 流程最适合与 Javascript 前端一起使用?
WebSecurityConfig
@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();
}
}
ResourceServerConfig
@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);
}
}
Implicit flow
用于 JavaScript 根据 OAuth2 spec
实施
隐式流程不支持刷新令牌。 spring 实施遵循 Oauth2 spec.
在 Javascript 客户端实现的情况下,令牌存储在客户端上。使用刷新令牌时,需要将刷新令牌持久化在客户端,以便日后获取新的访问令牌。如果是这种情况,您不妨发布一个(更)持久的访问令牌而不是刷新令牌。在客户端工作时,使用刷新令牌没有任何优势。
我目前正在开发一个后端带有 Spring Boot REST API 的 React WebApp。我想使用 OAuth2 来保护 API(并提高我的知识)。但是,我对要使用的正确身份验证流程有一些疑问。
由于前端正在使用 JavaScript 我不应该使用需要客户端密码的流程。
Spring 中唯一不需要客户端密码的流程是隐式流程。但是,对于此流程,Spring 不支持刷新令牌。这意味着一段时间后用户将自动注销并需要再次授权 WebApp。
我看到的另一个选项是创建一个没有密码的客户端,然后使用授权码流程。但是我有点怀疑这是否是正确的方法。
所以我的问题基本上是:当我不希望用户在一段时间后注销时,哪种 OAuth2 流程最适合与 Javascript 前端一起使用?
WebSecurityConfig
@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();
}
}
ResourceServerConfig
@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);
}
}
Implicit flow
用于 JavaScript 根据 OAuth2 spec
隐式流程不支持刷新令牌。 spring 实施遵循 Oauth2 spec.
在 Javascript 客户端实现的情况下,令牌存储在客户端上。使用刷新令牌时,需要将刷新令牌持久化在客户端,以便日后获取新的访问令牌。如果是这种情况,您不妨发布一个(更)持久的访问令牌而不是刷新令牌。在客户端工作时,使用刷新令牌没有任何优势。