/oauth/token 生成token后会调用哪个表
时间: 2023-08-04 07:06:01 浏览: 181
在OAuth2.0协议中,/oauth/token接口通过授权服务器颁发访问令牌(access token)给客户端,而不是直接调用数据库表。访问令牌(access token)一般会包含以下信息:
- token值
- 过期时间
- 可访问的资源范围(scope)
- 令牌类型(token type)
授权服务器会将访问令牌(access token)存储在内存、数据库或者缓存中,以便在后续的请求中验证访问令牌的有效性。在存储访问令牌时,通常会将访问令牌相关的信息(如token值、过期时间、可访问的资源范围等)存储到一个特定的数据表中。这个数据表的具体实现方式可能因不同的授权服务器而异。
相关问题
spring-security-oauth2-authorization-server /oauth2/token
### 配置和使用 `/oauth2/token` 端点
在 Spring Security OAuth2 授权服务器中,正确配置和使用 `/oauth2/token` 端点涉及多个方面。以下是详细的说明:
#### 1. 添加依赖项
为了使应用程序能够处理 OAuth2 认证请求并提供令牌服务,需确保项目中的 `pom.xml` 或构建文件已包含必要的依赖项。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-authorization-server</artifactId>
</dependency>
```
#### 2. 启用授权服务器功能
通过创建一个配置类来启用授权服务器的功能,并指定支持的客户端认证方式以及授予类型。
```java
@Configuration(proxyBeanMethods = false)
public class AuthorizationServerConfig {
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("client-id")
.clientSecret("{noop}secret")
.scope(OidcScopes.OPENID)
.redirectUri("http://localhost:8080/login/oauth2/code/messaging-client-oidc")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.build();
return new InMemoryRegisteredClientRepository(registeredClient);
}
@Bean
public OAuth2AuthorizationService authorizationService(JdbcTemplate jdbcTemplate,
RegisteredClientRepository registeredClientRepository) {
return new JdbcOAuth2AuthorizationService(jdbcTemplate, registeredClientRepository);
}
}
```
此部分代码定义了一个内存中的注册客户端仓库,并设置了相应的授权服务实例[^1]。
#### 3. 定义安全配置
设置 HTTP 请求的安全策略,允许访问 `/oauth2/token` 路径下的资源仅限于经过身份验证后的客户端应用。
```java
@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final RegisteredClientRepository registeredClientRepository;
// 构造函数注入
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/actuator/**").permitAll()
.anyRequest().authenticated();
http.oauth2ResourceServer(oauth2 -> oauth2.jwt());
http.oauth2Login(Customizer.withDefaults());
http.formLogin(form ->
form.loginPage("/login")
.permitAll()
);
http.apply(new OAuth2AuthorizationServerConfigurer<>())
.and()
.authorizeRequests(authorizations ->
authorizations.mvcMatchers("/oauth2/token").permitAll());
http.csrf(csrf -> csrf.disable());
}
}
```
上述配置启用了基于 JWT 的资源服务器保护机制,并开放了对 `/oauth2/token` API 的无条件访问权限以便测试目的;实际部署时应根据需求调整安全性措施[^2]。
#### 4. 测试接口调用
完成以上步骤之后,可以利用 Postman 或其他工具向该 URL 发送 POST 请求来进行 token 获取操作。注意要携带正确的参数如 client_id 和 client_secret 进行基本认证。
---
/oauth/token 密码
### Spring Security OAuth2 `/oauth/token` 密码授权模式实现
#### 接口调用流程
当客户端通过 POST 请求访问 `/oauth/token` 并指定 `grant_type=password` 参数时,服务器会执行一系列操作来处理该请求。具体来说:
- 客户端发送包含必要参数(如 client_id, client_secret, username 和 password)的 HTTP POST 请求到 `/oauth/token` 端点[^4]。
```java
Map<String, String> parameters = new HashMap<>();
parameters.put("client_id", clientId);
parameters.put("client_secret", secret);
parameters.put("grant_type", "password");
parameters.put("username", user.getUsername());
parameters.put("password", user.getPassword());
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> form = new LinkedMultiValueMap<>(parameters);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(form, headers);
ResponseEntity<Map> response = restTemplate.exchange(
url,
HttpMethod.POST,
entity,
Map.class
);
```
#### 验证与令牌发放逻辑
收到上述请求后,服务端会对传入的数据进行验证并尝试授予访问令牌。这涉及到多个组件间的协作工作流:
- **ClientDetailsServiceImpl**: 负责校验客户端凭证的有效性和权限配置;
- **TokenGranter**: 根据不同的授权类型选择合适的策略来进行实际的身份认证和令牌创建过程;对于密码型授权,则由 PasswordTokenGranter 处理;
- **UserDetailsService**: 提供用户详情信息服务用于身份验证;
- **OAuth2ProviderTokenServices**: 实现了具体的令牌管理功能,比如存储、检索以及撤销等操作[^1]。
一旦成功完成这些步骤之后,系统将会返回给客户端一个有效的 JSON Web Token (JWT),其中包含了必要的 claims 信息以便后续资源访问控制使用[^2]。
#### 存储机制
关于如何保存生成后的 access_token,在某些情况下可能会采用 Redis 这样的内存数据库作为缓存层以提高性能效率。在这种场景下,每当有新的 token 创建出来以后都会被序列化成字节数组形式写入 redis 中去,并设置相应的过期时间戳。当下次接收到相同的 authentication 对象查询 request 的时候就可以直接从 cache 里读取而无需再次经历完整的鉴权流程[^3]。
```json
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer",
"expires_in": 7200,
"scope": "read write"
}
```
阅读全文
相关推荐
















