zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Spring Cloud Security OAuth2的授权模式授权码模式(二)

SpringCloud模式 授权 Security OAuth2
2023-06-13 09:18:31 时间

配置资源服务器

在配置类中还需要添加资源服务器的配置:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/api/**").authenticated()
            .anyRequest().permitAll();
    }

}

这个配置类将启用资源服务器并配置 HTTP 安全性,使得只有经过身份验证的用户才能访问 /api 路径下的资源。

配置安全性

最后,在 Spring Boot 应用程序的配置文件中添加以下内容:

spring:
  security:
    oauth2:
      client:
        registration:
          my-client:
            client-id: my-client
            client-secret: my-secret
            authorization-grant-type: authorization_code
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            scope: read,user_info
        provider:
          my-provider:
            authorization-uri: https://my-provider.com/oauth2/authorize
            token-uri: https://my-provider.com/oauth2/token
            user-info-uri: https://my-provider.com/oauth2/userinfo
            user-name-attribute: name

这个配置文件指定了 OAuth2 客户端的详情、OAuth2 提供者的详情以及受保护资源的范围。

测试授权码模式

现在,您已经完成了 Spring Cloud Security OAuth2 授权码模式的配置。您可以使用下面的代码在您的 Spring Boot 应用程序中测试授权码模式:

@RestController
public class TestController {

    @GetMapping("/api/test")
    public String test() {
        return "Hello World!";
    }

}

这个控制器定义了一个 /api/test 的端点,只有经过身份验证的用户才能访问。

您可以使用以下 URL 向您的应用程序发出授权请求:

https://localhost:8080/oauth2/authorize?client_id=my-client&response_type=code&redirect_uri=https://localhost:8080/login/oauth2/code/my-client&scope=read,user_info

该 URL 将重定向用户到认证服务器的授权页面,要求用户输入用户名和密码,并批准授权请求。如果用户批准授权请求,认证服务器将向用户发回授权码,并将用户重定向回应用程序。

应用程序现在可以使用以下代码将授权码交换为访问令牌:

@RestController
public class OAuth2Controller {

    @Autowired
    private OAuth2AuthorizedClientService authorizedClientService;

    @GetMapping("/oauth2/token")
    public String token(OAuth2AuthenticationToken authentication) {
        OAuth2AuthorizedClient authorizedClient =
            authorizedClientService.loadAuthorizedClient(
                authentication.getAuthorizedClientRegistrationId(),
                authentication.getName());

        return authorizedClient.getAccessToken().getTokenValue();
    }

}

该代码使用 Spring Security OAuth2 提供的 OAuth2AuthorizedClientService 来获取访问令牌,并将其返回给客户端。