oauth2支持授权的方式有四种:授权码模式(authorization_code)、密码模式(password)、隐式模式(implicit)、客户端模式(client_credentials)。其中,比较常见的就是授权码模式和密码模式。
需要说明的是,授权码模式的过程大致如下:
1、封装参数,访问授权服务器登录与授权接口
接口:http://localhost:8080/oauth/authorize
参数:response_type client_id scope redirect_uri state
返回值:code
2、拿到code,获取token
接口:http://localhost:8080/oauth/token
参数:client_id client_secret grant_type code redirect_uri state
返回值:access_token
3、根据token,访问资源
接口:http://localhost:8080/api/test/hello
参数:access_token
密码模式的过程如下:
1、根据用户名密码等参数直接获取token
接口:http://localhost:8080/oauth/token
参数:username password grant_type client_id client_secret redirect_uri
返回值:access_token
2、根据token,访问资源
接口:http://localhost:8080/api/test/hello
参数:access_token
可以看出,授权码模式和密码模式有些区别,授权码模式多了一步就是登陆。密码模式直接把用户名和密码交给授权服务器了,所以不用再人为登陆,这也要求用户非常信任该应用。
下面我们通过代码来实际感受一下他们的使用以及区别:
也是构建一个项目,这里就不用分开授权服务和资源服务,统一放在一起:
项目依赖主要还是security和oauth2:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
</dependencies>
项目结构:
主要的代码:
AuthServerConfiguration.java
package org.oauthsample.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.an

最低0.47元/天 解锁文章
2881

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



