SpringOauth2.0 用户名密码验证方式(二)

1.Oauth2.0 用户名密码认证流程

image

  • (A)用户向客户端提供用户名和密码。
  • (B)客户端将用户名和密码发给认证服务器,向后者请求令牌。
  • (C)认证服务器确认无误后,向客户端提供访问令牌。
    请求示例
  • (B)步骤:客户端发出https请求

用户名密码认证方式,其实是对Code认证方式的高度封装,将其中的用户确认授权的步骤直接整合到:用户向客户端提供用户名和密码

在这种模式下,用户必须对客户端绝对信任,才能提供用户名和密码认证。

2.代码实现

在上一片文章中:
SpringOauth2 Authorization_code 模式(一)实现了对code码的认证,其中核心代码client配置模块如下:

@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer
                .realm("oauth2-resources")
                //url:/oauth/token_key,exposes public key for token verification if using JWT tokens
                .tokenKeyAccess("permitAll()")
                //url:/oauth/check_token allow check token
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client")
                .secret(passwordEncoder.encode("secret"))
                .redirectUris("http://example.com")
                // 客户端认证方式兼容了5种模式
                .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token",
                        "password", "implicit")
                .scopes("all")
                .resourceIds("oauth2-resource")
                .accessTokenValiditySeconds(1200)
                .refreshTokenValiditySeconds(50000);
    }
}

认证方式兼容了5种认证方式,用户名密码模式直接用上述代码即可。

3.请求认证
3.1 请求认证access_token
curl -i -d "grant_type=password&username=hello1&password=123456&scope=all" -u "client:secret" -X POST http://localhost:8080/oauth/token

参数说明:

grant_type:授权类型,此处的值固定为"password",必选项。  
username:用户名,必选项。  
password:用户的密码,必选项。  
scope:权限范围,可选项。

返回结果:

{
    "access_token": "99430e52-9d76-4f2c-af98-b1667657eb23",
    "token_type": "bearer",
    "refresh_token": "8b6c262d-22cb-4e5b-af08-a32cbee5c5c2",
    "expires_in": 1199,
    "scope": "all"
}

结果参数说明:

access_token:访问令牌,必选项。  
token_type:令牌类型,该值大小写不敏感,必选项。  
expires_in:过期时间,单位为秒。如果省略该参数,必须其他方式设置过期时间。
refresh_token:更新令牌,用来获取下一次的访问令牌,可选项。
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值