使用spring authorization server完成登陆接口
时间: 2024-03-07 07:40:29 浏览: 170
好的,以下是使用 Spring Authorization Server 完成登陆接口的步骤:
1. 添加依赖
在 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-authorization-server</artifactId>
<version>0.2.1</version>
</dependency>
```
2. 配置数据源
在 application.yml 文件中配置数据源:
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: password
```
3. 配置 JWT 密钥
在 application.yml 文件中配置 JWT 密钥:
```yaml
spring:
security:
oauth2:
authorization:
jwt:
key-value: secret
```
4. 配置认证服务器
在 SecurityConfig 类中配置认证服务器:
```java
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorizeRequests ->
authorizeRequests
.anyRequest().authenticated()
)
.oauth2Login();
}
@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("client")
.clientSecret("secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("http://localhost:8080/login/oauth2/code/client")
.scope("read")
.build();
return new InMemoryRegisteredClientRepository(registeredClient);
}
@Bean
public ProviderSettings providerSettings() {
return ProviderSettings.builder()
.issuer("http://localhost:8080")
.build();
}
@Bean
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore());
return tokenServices;
}
@Bean
public JwtTokenStore tokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("secret");
return converter;
}
@Bean
public OAuth2AuthorizationService authorizationService(
RegisteredClientRepository registeredClientRepository,
OAuth2TokenRepository tokenRepository
) {
return new OAuth2AuthorizationServiceImpl(
registeredClientRepository,
tokenRepository,
clientDetailsService()
);
}
@Bean
public OAuth2AuthorizationEndpointFilter authorizationEndpointFilter(
OAuth2AuthorizationService authorizationService,
ProviderSettings providerSettings
) {
return new OAuth2AuthorizationEndpointFilter(
authorizationService,
providerSettings
);
}
@Bean
public OAuth2TokenEndpointFilter tokenEndpointFilter(
OAuth2AuthorizationService authorizationService,
ProviderSettings providerSettings
) {
return new OAuth2TokenEndpointFilter(
authorizationService,
providerSettings
);
}
@Bean
public OAuth2ClientAuthenticationFilter clientAuthenticationFilter(
OAuth2AuthorizationService authorizationService,
ProviderSettings providerSettings
) {
return new OAuth2ClientAuthenticationFilter(
authorizationService,
providerSettings
);
}
@Bean
public OAuth2AuthorizationEndpoint authorizationEndpoint(
OAuth2AuthorizationService authorizationService,
ProviderSettings providerSettings
) {
return new OAuth2AuthorizationEndpoint(
authorizationService,
providerSettings
);
}
@Bean
public OAuth2TokenEndpoint tokenEndpoint(
OAuth2AuthorizationService authorizationService,
ProviderSettings providerSettings,
DefaultTokenServices tokenServices
) {
return new OAuth2TokenEndpoint(
authorizationService,
providerSettings,
tokenServices
);
}
@Bean
public ClientDetailsService clientDetailsService() {
return new InMemoryClientDetailsService();
}
@Bean
public OAuth2TokenRepository tokenRepository() {
return new InMemoryOAuth2TokenRepository();
}
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
}
```
5. 启动应用程序
在启动应用程序之后,可以使用以下 URL 进行测试:
- 认证服务器:http://localhost:8080/oauth2/authorize?client_id=client&response_type=code&scope=read
- 回调 URL:http://localhost:8080/login/oauth2/code/client
在浏览器中访问认证服务器 URL 后,将会跳转到登陆页,输入正确的用户名和密码后,将会重定向到回调 URL,并且 URL 中将会包含一个授权码。将授权码复制到剪贴板中,然后使用以下命令获取访问令牌:
```bash
curl --location --request POST 'http://localhost:8080/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic Y2xpZW50OnNlY3JldA==' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'code=<授权码>' \
--data-urlencode 'redirect_uri=http://localhost:8080/login/oauth2/code/client'
```
以上命令中的 `Y2xpZW50OnNlY3JldA==` 是将 `client:secret` 进行 Base64 编码得到的结果,`<授权码>` 是从回调 URL 中获取到的授权码。成功获取访问令牌后,将会得到如下结果:
```json
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyIiwic2NvcGUiOlsiYXBpIl0sImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODA4MCIsImV4cCI6MTYzMjg3MjQ1NSwiYXV0aG9yaXRpZXMiOlsiUk9MRV9BRE1JTiJdLCJqdGkiOiJmMzUzZjRkMS0zNTc5LTQ1MjktYmVlZS0wMTU4Mjg5YmY2MzYiLCJjbGllbnRfaWQiOiJjbGllbnQifQ.AiN-a7K2QjUJ3m2D6GqZ9Wu0r3HJiJ6UZE1Ua4L2gGdDc8GKXBclu1g1kTbZxOqTnXQsK9lLW7hj4Qe2UzCk9e3p7u4xiX6sk8qRg7jSMAj1Ei4jUvz8Z8JhKvH5cQr1Jb2yKtG4KJb9y2gbt5zI0g6qBzTsHc0Z3Ox9Acp3VW5UzK1Pu6l2k5r1ZV5h6B7g5QY6L7Q4RdKqAB9QJ3fF7Cztv3nQZJwZL1z4qYcJP3f28Mv8w5Q3fHJZpah2B7wGnK6EJNEr9FO9jzXKu9OYnqB1p0cZCfOjL7b5yK0JlQXTvfNDRrxdv_5YHwxiJQwK5ZCqM5fK75Y0-LV1nhYbQvJg",
"token_type": "bearer",
"expires_in": 3599,
"scope": "api",
"jti": "f353f4d1-3579-4529-beee-0158289bf636"
}
```
其中 `access_token` 就是获取到的访问令牌。
阅读全文