密码模式介绍
相关代码和SpringBoot+SpringSecurity+SpringCloudOauth2授权码模式使用(一)是一样的不懂可私信博主或者看这篇文章
图解:
- (A)用户向客户端提供用户名和密码。
- (B)客户端将用户名和密码发给授权服务器,向后者请求令牌。
- (C)授权服务器确认无误后,向客户端提供访问令牌。
在授权服务配置类中增加相关代码
在
configure(ClientDetailsServiceConfigurer clients)
方法中的authorizedGrantTypes
里增加password密码模式,授权模式可以多种,自行配置用逗号隔开,在授权服务配置类中重写这个方法configure(AuthorizationServerEndpointsConfigurer endpoints)
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Lazy
@Autowired
private UserService userService;
@Autowired
private AuthenticationManager authenticationManager;
@Lazy
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// 设置相关
endpoints.authenticationManager(authenticationManager)
.userDetailsService(userService)
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
// 授权服务的名字
.withClient("clients")
// 授权码
.secret(passwordEncoder.encode("112233"))
// 重定向位置
.redirectUris("http://www.baidu.com")
// 授权范围
.scopes("all")
/**
* authorization_code 授权码模式
* password 密码模式
*
*/
.authorizedGrantTypes("authorization_code","password");
}
}
在Security配置类中增加bean
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
启动项目
这样就可以通过密码模式去访问相关的资源,还是使用postMan来获取相关的token,密码模式是服务器将我们的账号密码一同带到授权服务器中去获取相关的access_token通过
localhost:8081/oauth/token
这个链接来获取数据,参数如下
参数名 | 参数值 |
---|---|
grant_type | password(密码模式) |
client_id | clients(客户端id) |
username | admin |
password | 123456 |
scope | all |
如图
设置好相关的权限参数
通过send获取到相关的access_token
然后就可以拿着access_token来获取相关的资源信息