ouath2资源认证服务器已经搭建好,但密码模式访问提示Unsupported grant type: password
http://localhost:9001/oauth/token?username=admin&password=admin&grant_type=password&client_id=client&client_secret=secret
原因:密码模式需要在认证服务器中设置 中配置AuthenticationManager
/**
* Oauth2服务配置,此模块为认证服务器
*/
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
/**
* 这个如果配置支持allowFormAuthenticationForClients的,且url中有client_id和client_secret的会走ClientCredentialsTokenEndpointFilter来保护
* 如果没有支持allowFormAuthenticationForClients或者有支持但是url中没有client_id和client_secret的,走basic认证保护
*
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client")
.redirectUris("http://www.baidu.com")
//此处的scopes是无用的,可以随意设置
.scopes("all", "read", "write")
.secret("secret")//401错误,我的解决办法是这个,仅供参考
.authorizedGrantTypes("password", "authorization_code", "refresh_token");
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
.tokenKeyAccess("permitAll()")
.checkTokenAccess("permitAll()")
.allowFormAuthenticationForClients();
}
/**
* Spring security5中新增加了加密方式,并把原有的spring security的密码存储格式改了
*
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
}
这时启动会报错找不到AuthenticationManager Bean,在Security中定义这个Bean
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/v2/api-docs"
, "/swagger-resources/**"
, "/swagger-ui.html**"
, "/webjars/**"
, "/oauth/token/*"
, "/v1.0/userLogin/login"
, "/v1.0/user/create")
.permitAll()
.antMatchers("/**/*").permitAll()
.anyRequest().authenticated()
// 没有下面这句会报/login 404
.and().csrf().disable()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(passwordEncoder())
.withUser("admin")
.password("admin").roles("USER");
}
@Bean
public static PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
成功请求