详解SpringBoot Oauth2 Server搭建Oauth2认证服务
1. 概述
OAuth,全称是“开放授权”,是一种用于授权的开放标准。在Web应用中,OAuth用于授权用户第三方应用访问资源的操作,比如在不需要输入用户名和密码的情况下授权第三方应用获取用户的个人信息。OAuth提供了一个安全的、开放的方式实现对用户的授权。
SpringBoot Oauth2 Server 是SpringBoot下基于Oauth2实现的认证服务。通过搭建Oauth2认证服务,用户可以获取到访问所需资源的令牌,实现对用户操作行为的授权管理。
2. 搭建步骤
2.1 添加依赖
在 pom.xml 文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-server</artifactId>
</dependency>
2.2 配置文件
在 application.yml 文件中添加以下配置:
spring:
security:
oauth2:
client:
registration:
my-client:
client-id: my-client-id
client-secret: my-client-secret
# 客户端的授权类型
authorization-grant-type: authorization_code
redirect-uri: https://example.com/callback
provider:
my-auth-server:
authorization-uri: https://auth-server.com/oauth/authorize
token-uri: https://auth-server.com/oauth/token
user-info-uri: https://auth-server.com/userinfo
# 客户端需要获取的用户信息作用域
scope: openid,profile,email
2.3 实现认证服务
创建一个类,实现AuthorizationServerConfigurer
接口,完成实现认证服务的相关逻辑:
@Configuration
@EnableAuthorizationServer
public class MyAuthorizationServerConfig implements AuthorizationServerConfigurer {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private TokenStore tokenStore;
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("my-client-id")
.secret("{noop}my-client-secret")
.authorizedGrantTypes("authorization_code", "refresh_token")
.scopes("openid", "profile", "email")
.autoApprove(true)
.redirectUris("https://example.com/callback");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.authenticationManager(authenticationManager)
.tokenStore(tokenStore)
.accessTokenConverter(jwtAccessTokenConverter)
.userDetailsService(userDetailsService);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
}
2.4 实现安全配置
创建一个类,实现SecurityConfigurerAdapter接口,完成安全配置的相关逻辑:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password("{noop}password")
.roles("USER");
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
3. 示例
3.1 实现认证
创建一个控制器,实现认证的相关逻辑:
@RestController
public class AuthController {
@GetMapping("/login")
public String login() {
return "Please login";
}
@PostMapping("/login")
public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password) {
return "login success";
}
}
用户访问/login,将跳转到登录页面,然后在客户端,用户访问授权 URL,即 /oauth/authorize,并提供您的客户端 ID 和其他必要信息。Oauth2服务器会跳转到授权服务器并展示授权页面。
3.2 获取令牌
客户端需要获取访问资源的令牌,可以发送POST请求到 /oauth/token 端点以获取令牌:
POST /oauth/token HTTP/1.1
Host: localhost:8080
Content-Type: application/x-www-form-urlencoded
Authorization: Basic bXktY2xpZW50LWlkOm15LWNsaWVudC1zZWNyZXQ=
grant_type=authorization_code&code=6f9f3279-9c69-40f9-a3f2-d655141386b4&redirect_uri=https://example.com/callback
成功获取到令牌后,在访问资源时需要在请求头中添加令牌信息:
GET /api/users HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaXNzIjoiaHR0cHM6Ly9hdXRoLXNlcnZlci5jb20iLCJhdWQiOiJteS1jbGllbnQtaWQiLCJpYXQiOjE1MTYyMzkwMjIsImV4cCI6MTUxNjI0MzYyMn0.O8aXp-FNKO6GiPgbKDdY5GEwIhFc5-cGc01fhz9KnGqfuNyhOt-OI9Orrh4a-T3lIkSxO3sMFc9a3w6V_jYaPqfFjkIbuXYhsBAvU9CYoybjAGvyMxqv_0RfKK2AKt3hbM8erWvml-eN04DN1-Oc_4Zn3ZmgK5qlsJ3fCnYIc
以上就是搭建Oauth2认证服务的完整攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:详解Springboot Oauth2 Server搭建Oauth2认证服务 - Python技术站