我试图使用spring boot编写OAuth提供商,但我得到了以下问题,我使用Postman使用/oauth/token,但它返回401 Unauthorized,没有响应。
以下是我试图遵循的例子链接: Spring Cloud Security - OAuth2 Authorization using Jdbc Token Store | Codeaches
在我的需求中,我需要使用MS SQL Server数据库,所以我按照链接中的脚本,尝试转换为SQL Server脚本,这里也是我尝试的代码部分。
WebSecurityConfig.java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
@Override
@Bean("userDetailsService")
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean("authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> cfg = auth.jdbcAuthentication()
.passwordEncoder(passwordEncoder()).dataSource(dataSource);
cfg.getUserDetailsService().setEnableGroups(true);
cfg.getUserDetailsService().setEnableAuthorities(false);
}
}
CustomTokenEnhancer.java
public class CustomTokenEnhancer implements TokenEnhancer {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
((DefaultOAuth2AccessToken) accessToken).setTokenType("Bearer");
return accessToken;
}
}
OAuth2AuthorizationServer
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
DataSource dataSource;
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Bean
public TokenEnhancer tokenEnhancer() {
return new CustomTokenEnhancer();
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer()));
endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.passwordEncoder(passwordEncoder).tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
}
我知道有些代码已经过时了,但根据我的要求,它不能与外界连接(我认为他们不想为此打开防火墙。
回到问题上来,我有什么遗漏吗?
StackOverflow:java - Spring boot custom OAuth Provider didn't return any response with status code 401 - Stack Overflow