SpringBoot+SpringSecurity+SpringCloudOauth2密码模式使用(二)

本文详细介绍了OAuth2中的密码模式,包括用户向客户端提供凭据的过程、客户端如何向授权服务器请求访问令牌,以及授权服务器验证后的响应流程。此外还提供了Spring Boot项目中实现密码模式的具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

密码模式介绍

相关代码和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_typepassword(密码模式)
client_idclients(客户端id)
usernameadmin
password123456
scopeall

如图

在这里插入图片描述

设置好相关的权限参数

在这里插入图片描述

通过send获取到相关的access_token

在这里插入图片描述

然后就可以拿着access_token来获取相关的资源信息

在这里插入图片描述

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

麦片王子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值