【问题标题】:I have set up oauth2 properties in application.properties, How to use them in the code?我在 application.properties 中设置了 oauth2 属性,如何在代码中使用它们?
【发布时间】:2017-01-31 05:54:58
【问题描述】:

在我的 Spring Boot 应用程序中,我使用 google oauth2 让用户从他们的 gmail 帐户登录。我已经使用我的帐户详细信息获取并设置了客户端 ID、机密和范围,并测试了该程序。
但是现在我需要在一个单独的环境中运行它,所以所有硬编码的配置都必须消失。
我在我的 application.properties 文件中添加了客户端 ID、密码和范围,如下所示,

security.oauth2.client.id= 5******-5**bd***a6.apps.googleusercontent.com
security.oauth2.client.client-secret=m******qb***H
security.oauth2.client.scope[0]=https://www.googleapis.com/auth/admin.directory.user.readonly 

现在如何在我的 java 类中使用这些属性。对于示例

 public static String getToken() throws Exception {

    String clientId =  "5******-5**bd***a6.apps.googleusercontent.com";
    String clientSecret = "m******qb***H";
    String scope = "https://www.googleapis.com/auth/admin.directory.user.readonly ";

    AuthorizationCodeFlow flow=
            new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(),
                    new NetHttpTransport(),
                    new JacksonFactory(),
                    new GenericUrl(GoogleOAuthConstants.TOKEN_SERVER_URL),
                    new BasicAuthentication(clientId, clientSecret),
                    clientId,
                    GoogleOAuthConstants.AUTHORIZATION_SERVER_URL)
                    .setScopes(Collections.singleton(scope)).build();

我想创建一个配置类并从 .properties 文件中获取 id、secret、scope 值,然后在此处使用这些值。 所有这些都应该使用 Spring 完成,请不要通过文件读取。

【问题讨论】:

    标签: java spring spring-boot google-oauth properties-file


    【解决方案1】:

    您可以使用如下所示的@Value注解来读取属性

    @Value("${security.oauth2.client.id}")
    private String clientId;
    

    【讨论】:

      猜你喜欢
      • 2018-12-16
      • 2020-01-26
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 2012-10-30
      • 2021-11-13
      • 2021-05-27
      • 1970-01-01
      相关资源
      最近更新 更多