欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用Spring Boot和OAuth构建安全的SPA

程序员文章站 2024-02-05 16:53:34
最近一段时间都在闭关学习,过程还是有点艰辛的,幸运的是还有优锐课老师带着,少走了很多弯路。很久也没有更新文章了,这篇想和大家分享的是,了解如何在使用Spring Boot入门程序的同时使用Spring Boot和OAuth构建安全的SPA,以获得对验证和权限映射的其他支持。 即使是最基本的JavaS ......

最近一段时间都在闭关学习,过程还是有点艰辛的,幸运的是还有优锐课老师带着,少走了很多弯路。很久也没有更新文章了,这篇想和大家分享的是,了解如何在使用spring boot入门程序的同时使用spring boot和oauth构建安全的spa,以获得对验证和权限映射的其他支持。

即使是最基本的javascript单页应用程序(spa),也很可能需要安全地从源应用程序访问资源,并且如果你是像我这样的java开发人员,则可能是spring boot应用程序,并且你可能想使用oauth 2.0隐式流。通过此流程,你的客户端将在每个请求中发送一个承载令牌,并且你的服务器端应用程序将使用身份提供者(idp)验证该令牌。

在本教程中,你将通过构建两个演示这些原理的小型应用程序来了解有关隐式流程的更多信息:一个带有一点jquery的简单spa客户端应用程序以及一个带有spring boot的后端服务。你将通过使用标准的spring oauth位开始,然后切换到okta spring boot starter并检查其添加的功能。前几节将与供应商无关,但是由于我并非一无所知,因此我将向你展示如何使用okta作为你的idp。

创建一个spring boot应用程序

如果你还没有尝试过start.spring.io,请立即单击以进行检查……单击几次,它将为你提供一个基本的,可运行的spring boot应用程序。

1 curl https://start.spring.io/starter.tgz \
2  -d artifactid=oauth-implicit-example  \
3  -d dependencies=security,web \
4  -d language=java \
5  -d type=maven-project \
6  -d basedir=oauth-implicit-example \
7  | tar -xzvf -

 

如果要从浏览器下载项目,请转到:start.spring.io搜索并选择“security”依存关系,然后单击绿色的“generate project”按钮。

解压缩项目后,应该可以在命令行中启动它:./mvnw spring-boot:run。该应用程序尚无法执行任何操作,但这是一项“so far so good”的检查。用^c终止该过程,让我们开始实际编写代码!

 

写一些代码!

好吧,差不多。首先,将spring oauth 2.0依赖项添加到pom.xml

1 <dependency>
2    <groupid>org.springframework.security.oauth</groupid>
3    <artifactid>spring-security-oauth2</artifactid>
4    <version>2.2.0.release</version>
5 </dependency>

 

打开demoapplication.java,如果你遵循(and you are right?),则应位于src/main/java/com/example/oauthimplicitexample中。不难发现,该项目仅包含两个java类,其中一个是测试。

@enableresourceserver注释该类,这将告诉spring security添加必要的过滤器和逻辑来处理oauth隐式请求。

接下来,添加一个控制器:

1 @restcontroller
2 public class messageofthedaycontroller {
3    @getmapping("/mod")
4    public string getmessageoftheday(principal principal) {
5        return "the message of the day is boring for user: " + principal.getname();
6    }
7 }

 

这就对了!基本上是hello world。使用./mvnw spring-boot:run启动你的应用程序备份。你应该可以访问:

1 curl -v http://localhost:8080/mod
2 http/1.1 401
3 content-type: application/json;charset=utf-8
4 www-authenticate: bearer realm="oauth2-resource", error="unauthorized", error_description="full authentication is required to access this resource"
5 {
6    "error": "unauthorized",
7    "error_description": "full authentication is required to access this resource"
8 }

 

401? 是的,默认情况下是安全的!另外,我们实际上并未提供oauth idp的任何配置详细信息。使用^c停止服务器,然后移至下一部分。

 

准备好你的oauth信息

如上所述,你将继续使用okta。你可以在上注册一个免费(永久)帐户。只需单击“注册”按钮并填写表格。完成此操作后,你将获得两件事,即okta基本url,看起来像:和一封有关如何激活帐户的说明的电子邮件。

激活你的帐户,当你仍然在okta开发人员控制台中时,最后一步是:创建okta spa应用程序。在顶部菜单栏上,单击“applications”,然后单击“add application”。选择spa,然后单击next

用以下值填写表格:

  • name: oauth implicit tutorial
  • base uris: 
  • login redirect uris: 

将其他所有内容保留为默认值,然后单击“done”。下一页的底部是你的客户id,你将在下一步中使用该id。

 

为spring配置oauth

生成的示例应用程序使用application.properties文件。我更喜欢yaml,因此我将文件重命名为application.yml

应用程序资源服务器仅需要知道如何验证访问令牌。由于oauth 2.0或oidc规范未定义访问令牌的格式,因此可以远程验证令牌。the generated sample application uses

1 security:
2  oauth2:
3    resource:
4      userinfouri: https://dev-123456.oktapreview.com/oauth2/default/v1/userinfo

 

此时,你可以启动应用程序并开始验证访问令牌!但是,当然,你将需要访问令牌来进行验证…

 

创建登录页面

为方便起见,你将重用现有的spring boot应用程序来托管spa。通常,这些资产可以托管在其他地方:另一个应用程序,cdn等。出于本教程的目的,将一个孤独的index.html文件托管在另一个应用程序中似乎有点过头了。

创建一个新文件src/main/resources/static/index.html并用以下内容填充它:

  1 <!doctype html>
  2 <html lang="en">
  3 <head>
  4    <meta charset="utf-8">
  5    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  6    <meta name="description" content="">
  7    <meta name="author" content="">
  8    <title>okta implicit spring-boot</title>
  9    <base href="/">
 10    <script src="https://ok1static.oktacdn.com/assets/js/sdk/okta-signin-widget/2.3.0/js/okta-sign-in.min.js" type="text/javascript"></script>
 11    <link href="https://ok1static.oktacdn.com/assets/js/sdk/okta-signin-widget/2.3.0/css/okta-sign-in.min.css" type="text/css" rel="stylesheet">
 12    <link href="https://ok1static.oktacdn.com/assets/js/sdk/okta-signin-widget/2.3.0/css/okta-theme.css" type="text/css" rel="stylesheet">
 13    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 14    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 15    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 16 </head>
 17 <body>
 18 <!-- render the login widget here -->
 19 <div id="okta-login-container"></div>
 20 <!-- render the rest response here -->
 21 <div id="cool-stuff-here"></div>
 22 <!-- and a logout button, hidden by default -->
 23 <button id="logout" type="button" class="btn btn-danger" style="display:none">logout</button>
 24 <script>
 25  $.ajax({
 26    url: "/sign-in-widget-config",
 27  }).then(function(data) {
 28    // we are priming our config object with data retrieved from the server in order to make this example easier to run
 29    // you could statically define your config like if you wanted too:
 30    /*
 31    const data = {
 32      baseurl: 'https://dev-123456.oktapreview.com',
 33      clientid: '00icu81200icu812w0h7',
 34      redirecturi: 'http://localhost:8080',
 35      authparams: {
 36        issuer: 'https://dev-123456.oktapreview.com/oauth2/default',
 37        responsetype: ['id_token', 'token']
 38      }
 39    }; */
 40    // we want the access token so include 'token'
 41    data.authparams.responsetype = ['id_token', 'token'];
 42    data.authparams.scopes = ['openid', 'email', 'profile'];
 43    data.redirecturi = window.location.href; // simple single page app
 44    // setup the widget
 45    window.oktasignin = new oktasignin(data);
 46    // handle the rest of the page
 47    doinit();
 48  });
 49  /**
 50   * makes a request to a rest resource and displays a simple message to the page.
 51   * @param accesstoken the access token used for the auth header
 52   */
 53  function doallthethings(accesstoken) {
 54    // include the bearer token in the request
 55    $.ajax({
 56      url: "/mod",
 57      headers: {
 58        'authorization': "bearer " + accesstoken
 59      },
 60    }).then(function(data) {
 61      // render the message of the day
 62      $('#cool-stuff-here').append("<strong>message of the day:</strong> "+ data);
 63    })
 64    .fail(function(data) {
 65      // handle any errors
 66      console.error("error!!");
 67      console.log(data.responsejson.error);
 68      console.log(data.responsejson.error_description);
 69    });
 70    // show the logout button
 71    $( "#logout" )[0].style.display = 'block';
 72  }
 73  function doinit() {
 74    $( "#logout" ).click(function() {
 75      oktasignin.signout(() => {
 76        oktasignin.tokenmanager.clear();
 77        location.reload();
 78      });
 79    });
 80    // check if we already have an access token
 81    const token = oktasignin.tokenmanager.get('my_access_token');
 82    // if we do great, just go with it!
 83    if (token) {
 84      doallthethings(token.accesstoken)
 85    } else {
 86      // otherwise show the login widget
 87      oktasignin.renderel(
 88        {el: '#okta-login-container'},
 89        function (response) {
 90          // check if success
 91          if (response.status === 'success') {
 92            // for our example we have the id token and the access token
 93            oktasignin.tokenmanager.add('my_id_token', response[0]);
 94            oktasignin.tokenmanager.add('my_access_token', response[1]);
 95            // hide the widget
 96            oktasignin.hide();
 97            // now for the fun part!
 98            doallthethings(response[1].accesstoken);
 99          }
100        },
101        function (err) {
102          // handle any errors
103          console.log(err);
104        }
105      );
106    }
107  }
108 </script>
109 </body>
110 </html>

 

此页面执行以下操作:

  • 显示okta登录小部件并获取访问令牌
  • 调用/sign-in-widget-config控制器来配置所述小部件(我们假设此文件由其他服务提供)
  • 用户登录后,页面将调用/mod控制器(带有访问令牌)并显示结果

为了支持我们的html,我们需要为/sign-in-widget-config端点创建一个新的controller

在与spring boot application类相同的包中,创建一个新的signinwidgetconfigcontrollerclass类:

 1 @restcontroller
 2 public class signinwidgetconfigcontroller {
 3    private final string issuerurl;
 4    private final  string clientid;
 5    public signinwidgetconfigcontroller(@value("#{@environment['okta.oauth2.clientid']}") string clientid,
 6                                        @value("#{@environment['okta.oauth2.issuer']}")   string issuerurl) {
 7        assert.notnull(clientid,  "property 'okta.oauth2.clientid' is required.");
 8        assert.notnull(issuerurl, "property 'okta.oauth2.issuer' is required.");
 9        this.clientid = clientid;
10        this.issuerurl = issuerurl;
11    }
12    @getmapping("/sign-in-widget-config")
13    public widgetconfig getwidgetconfig() {
14        return new widgetconfig(issuerurl, clientid);
15    }
16    public static class widgetconfig {
17        public string baseurl;
18        public string clientid;
19        public map<string, object> authparams = new linkedhashmap<>();
20        widgetconfig(string issuer, string clientid) {
21            this.clientid = clientid;
22            this.authparams.put("issuer", issuer);
23            this.baseurl = issuer.replaceall("/oauth2/.*", "");
24        }
25    }
26 }

 

将相应的配置添加到application.yml文件:

1 okta:
2  oauth2:
3    # client id from above step
4    clientid: 00icu81200icu812
5    issuer: https://dev-123456.oktapreview.com/oauth2/default

 

最后一件事是允许公众访问index.html页面和 /sign-in-widget-config

在你的应用程序中定义resourceserverconfigureradapter,以允许访问这些资源。

 1 @bean
 2 protected resourceserverconfigureradapter resourceserverconfigureradapter() {
 3    return new resourceserverconfigureradapter() {
 4        @override
 5        public void configure(httpsecurity http) throws exception {
 6            http.authorizerequests()
 7                    .antmatchers("/", "/index.html", "/sign-in-widget-config").permitall()
 8                    .anyrequest().authenticated();
 9        }
10    };
11 }

 

动起来!

使用./mvnw spring-boot:run再次启动你的应用程序,然后浏览至 。你应该可以使用新的okta帐户登录并查看当天的消息。

尝试okta spring boot starter

到现在为止(登录页面除外),你一直在使用spring security oauth 2.0的即用型支持。这样做是因为:标准!这种方法存在一些问题:

  • 对我们应用程序的每个请求都需要不必要的往返回oauth idp
  • 我们不知道创建访问令牌时使用了哪些范围
  • 在这种情况下,用户的组/角色不可用

这些可能对你的应用程序来说可能不是问题,但是解决它们就像向你的pom文件添加另一个依赖项一样简单:

1 <dependency>
2    <groupid>com.okta.spring</groupid>
3    <artifactid>okta-spring-boot-starter</artifactid>
4    <version>0.2.0</version>
5 </dependency>

 

如果需要,甚至可以缩减application.yml文件,其中任何security.* 属性将优先于 okta.* 属性:

1 okta:
2  oauth2:
3    clientid: 00icu81200icu812
4    issuer: https://dev-123456.oktapreview.com/oauth2/default

 

重新启动你的应用程序,已经解决了前两个问题!

最后一个需要额外的步骤,你将不得不向okta的访问令牌添加额外的数据:

回到okta developer console,在菜单栏上单击api > authorization server。在此示例中,我们一直在使用“default”授权服务器,因此请单击“edit”,然后选择“claims”标签。点击“add claim”,然后使用以下值填写表单:

  • name: groups
  • include in token type: access token
  • value type: groups
  • filter: regex - .*

将其余的保留为默认设置,然后点击“create”。

okta-spring-boot-starter会自动将组声明中的值映射到spring security authority。以标准的spring security方式,我们可以注释我们的方法来配置访问级别。

要启用@preauthorize批注,你需要将@enableglobalmethodsecurity添加到spring boot application。如果还要验证oauth范围,则需要添加oauth2methodsecurityexpressionhandler。只需将以下代码片段放入你的spring boot应用程序即可。

 

1 @enableglobalmethodsecurity(prepostenabled = true)
2 protected static class globalsecurityconfiguration extends globalmethodsecurityconfiguration {
3    @override
4    protected methodsecurityexpressionhandler createexpressionhandler() {
5        return new oauth2methodsecurityexpressionhandler();
6    }
7 }

 

最后,使用@preauthorize更新messageofthedaycontroller(在这种情况下,你允许“所有人”或“电子邮件”范围内的任何人)。

1 @restcontroller
2 public class messageofthedaycontroller {
3    @getmapping("/mod")
4    @preauthorize("hasauthority('everyone') || #oauth2.hasscope('email')")
5    public string getmessageoftheday(principal principal) {
6        return "the message of the day is boring for user: " + principal.getname();
7    }
8 }

 

感谢阅读~