认证和授权-基于OAuth2
文章目录
一、OAuth2认证服务的搭建-基于内存方式
1、创建工程引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
上述依赖基于Cloud-Hoxton.SR12,Boot-2.3.12.RELEASE。依赖关系很重要,搭建时请参考官方文档。
2、配置认证服务器
/**
* OAuth2认证策略 客户端访问相关策略
*/
@Configuration
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
/**
* 先从容器中获取认证管理器 具体是什么待查询
*/
@Autowired
private AuthenticationManager authenticationManager;
/**
* 从容器中获取用户详细信息服务 直观来看就是获取用户信息的类
*/
@Autowired
private UserDetailsService userDetailsService;
/**
* 重写configure方法 注意这里配置的是客户端访问的认证和授权策略
* 所以参数是ClientDetailsServiceConfigurer
*
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception{
// 从内存中读取信息 当然严谨一些应当从数据库或者配置文件中获取这些配置信息
clients.inMemory()
// 客户端的id 相当于客户端的注册标识
.withClient("eate")
// 密码
.secret("zzc")
// 授权类型 token 密码 客户端凭证
.authorizedGrantTypes(
"refresh_token",
"password",
"client_credentials")
// 权限作用或者说是授权的范围
.scopes("webclient","mobileclient");
}
/**
* 定义认证授权要使用的容器组件 也就是从上面自动注入的组件
*
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception{
// 设置认证授权组件
endpoints
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
}
创建配置类OAuth2Config继承AuthorizationServerConfigurerAdapter类。
3、配置用户认证方式和信息
/**
* 配置完OAuth2的策略 来配置访问认证服务器的策略
*/
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 老规矩加密器 不配置就报错
*
* @return
*/
@Bean
public PasswordEncoder encoder(){
return NoOpPasswordEncoder.getInstance();
}
/**
* 这里选用Security默认的认证管理器
*
* @return
* @throws Exception
*/
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception{
return super.authenticationManager();
}
/**
* 选用默认的用户详细信息服务
*
* @return
* @throws Exception
*/
@Bean
@Override
public UserDetailsService userDetailsServiceBean() throws Exception{
return super.userDetailsServiceBean();
}
/**
* Security三大配置方法 重载该配置方法来配置用户相关信息
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.inMemoryAuthentication()
.withUser("john")
.password(

本文详细介绍了如何使用SpringCloud OAuth2搭建认证和授权服务,包括基于内存方式的认证服务和资源服务搭建,以及使用JWT实现认证服务端的详细步骤,涉及到依赖配置、注解使用、回调端点设定、访问策略等关键环节。
最低0.47元/天 解锁文章
2557

被折叠的 条评论
为什么被折叠?



