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();
}
}
成功請求