基于授权码模式去修改:
https://www.yuque.com/docs/share/27959146-cdc4-43ec-a96a-c0969e1ac2d7?# 《授权码模式入门Demo》
代码地址
https://gitee.com/zjj19941/ZJJ_Neaten5.10/tree/master/ZJJ_SpringCloud_Oauth2/demo02
代码
修改WebSecurityConfig,增加AuthenticationManager
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().permitAll()
.and().authorizeRequests()
.antMatchers("/oauth/**").permitAll()
.anyRequest().authenticated()
.and().logout().permitAll()
.and().csrf().disable();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
修改AuthorizationServerConfig配置
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig2 extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AuthenticationManager authenticationManagerBean;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManagerBean) //使用密码模式需要配置
.allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST); //支持GET,POST请求
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
//允许表单认证
security.allowFormAuthenticationForClients();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
/**
*授权码模式
*http://localhost:8080/oauth/authorize?response_type=code&client_id=client&redirect_uri=http://www.baidu.com&scope=all
*http://localhost:8080/oauth/authorize?response_type=code&client_id=client
*
* password模式
* http://localhost:8080/oauth/token?username=fox&password=123456&grant_type=password&client_id=client&client_secret=123123&scope=all
*
* 客户端模式
* http://localhost:8080/oauth/token?grant_type=client_credentials&scope=all&client_id=client&client_secret=123123
*/
clients.inMemory()
//配置client_id
.withClient("client")
//配置client-secret
.secret(passwordEncoder.encode("123123"))
//配置访问token的有效期
.accessTokenValiditySeconds(3600)
//配置刷新token的有效期
.refreshTokenValiditySeconds(864000)
//配置redirect_uri,用于授权成功后跳转
.redirectUris("http://www.baidu.com")
//配置申请的权限范围
.scopes("all")
/**
* 配置grant_type,表示授权类型
* authorization_code: 授权码
* password: 密码
* client_credentials: 客户端
*/
.authorizedGrantTypes("authorization_code","password","client_credentials");
}
}
测试
get请求获取access_token
通过浏览器测试,需要配置支持get请求和表单验证
返回结果直接带access_token
{
“access_token”: “5370d3af-78c8-4c90-8e65-617ca4714d7c”,
“token_type”: “bearer”,
“expires_in”: 3040,
“scope”: “all”
}
post请求获取access_token
http://localhost:8080/oauth/token
grant_type:password
username:fox
password:123456
结果:
{
“access_token”: “5370d3af-78c8-4c90-8e65-617ca4714d7c”,
“token_type”: “bearer”,
“expires_in”: 2908,
“scope”: “all”
}