Spring Security With Okta – 使用Okta的Spring安全

最后修改: 2020年 5月 10日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Okta provides features like authentication, authorization, and social login for web, mobile, or API services. Additionally, it has robust support for the Spring Framework to make integrations quite straightforward.

Okta为Web、移动或API服务提供认证、授权和社交登录等功能。此外,它还拥有强大的对Spring框架的支持,使整合变得相当简单。

Now that Stormpath has joined forces with Okta to provide better Identity APIs for developers, it’s now a popular way to enable authentication in a web application.

现在,Stormpath已经与Okta联手为开发人员提供了更好的身份识别API,它现在是在Web应用程序中启用认证的一种流行方式。

In this tutorial, we’ll explore Spring Security with Okta along with a minimalistic setup of the Okta developer account.

在本教程中,我们将探讨Spring Security与Okta的关系,以及Okta开发者账户的最小化设置。

2. Setting Up Okta

2.设置Okta

2.1. Developer Account Sign Up

2.1.开发者账户注册

First, we’ll sign up for a free Okta developer account that provides access for up to 1k monthly active users. However, we can skip this section if we already have one:

首先,我们将注册一个免费的Okta开发人员帐户,该帐户可提供多达1千名月度活跃用户的访问权限。但是,如果我们已经有了一个账户,则可以跳过这一部分。

2.2. Dashboard

2.2 仪表板

Once logged in to the Okta developer account, we’ll land at the dashboard screen that briefs us about the number of users, authentications, and failed logins.

一旦登录到Okta开发者账户,我们就会进入仪表盘界面,向我们介绍用户数量、认证情况和登录失败情况。

Additionally, it also shows detailed log entries of the system:

此外,它还显示系统的详细日志条目。

 

Further, we’ll note the Org URL at the upper-right corner of the Dashboard, required for Okta setup in our Spring Boot App that we’ll create later.

此外,我们将注意仪表板右上角的Org URL,这是我们稍后创建的Spring Boot App中的Okta设置所需要的。

2.3. Create a New Application

2.3.创建一个新的应用程序

Then, let’s create a new application using the Applications menu to create OpenID Connect (OIDC) app for Spring Boot.

然后,让我们使用应用程序菜单创建一个新的应用程序,为Spring Boot创建OpenID Connect(OIDC)应用程序

Further, we’ll choose the Web platform out of available options like Native, Single-Page App, and Service:

此外,我们将在NativeSingle-Page AppService等可用选项中选择Web平台。

2.4. Application Settings

2.4.应用程序设置

Next, let’s configure a few application settings like Base URIs and Login redirect URIs pointing to our application:

接下来,让我们配置一些应用程序的设置,如基础URI登录重定向URI,以指向我们的应用程序。

Also, make sure to mark Authorization code for the Grant type allowed, required to enable OAuth2 authentication for a web application.

此外,请确保为授权代码标记允许的授权类型,需要为Web应用程序启用OAuth2认证

2.5. Client Credentials

2.5.客户端凭证

Then, we’ll get values for the Client ID and Client secret associated with our app:

然后,我们将得到与我们的应用程序相关的客户端ID客户端秘密的值。

Please keep these credentials handy because they are required for Okta setup.

请保留这些凭证,因为它们是Okta设置所需要的。

3. Spring Boot App Setup

3.Spring Boot应用程序的设置

Now that our Okta developer account is ready with essential configurations, we’re prepared to integrate Okta security support in a Spring Boot App.

现在,我们的Okta开发者账户已经准备好了基本配置,我们准备在Spring Boot应用程序中整合Okta安全支持。

3.1. Maven

3.1. Maven

First, let’s add the latest okta-spring-boot-starter Maven dependency to our pom.xml:

首先,让我们把最新的okta-spring-boot-starter Maven依赖性添加到我们的pom.xml

<dependency>
    <groupId>com.okta.spring</groupId>
    <artifactId>okta-spring-boot-starter</artifactId>
    <version>1.4.0</version>
</dependency>

3.2. Gradle

3.2 Gradle

Similarly, when using Gradle, we can add the okta-spring-boot-starter dependency in the build.gradle:

同样,当使用Gradle时,我们可以在build.gradle中添加okta-spring-boot-starter依赖项。

compile 'com.okta.spring:okta-spring-boot-starter:1.4.0'

3.3. application.properties

3.3.application.properties

Then, we’ll configure Okta oauth2 properties in the application.properties:

然后,我们将在application.properties中配置Okta oauth2属性。

okta.oauth2.issuer=https://dev-example123.okta.com/oauth2/default
okta.oauth2.client-id=1230oaa4yncmaxaQ90ccJwl4x6
okta.oauth2.client-secret=hjiyblEzgT0ItY91Ywcdzwa78oNhtrYqNklQ5vLzvruT123
okta.oauth2.redirect-uri=/authorization-code/callback

Here, we can use the default authorization server (if none available) for the issuer URL that points to the {orgURL}/oauth2/default.

在这里,我们可以使用default授权服务器(如果没有的话)的issuer URL指向{orgURL}/oauth2/default

Also, we can create a new Authorization server in the Okta developer account by using the API menu:

另外,我们可以通过使用API菜单在Okta开发者账户中创建一个新的授权服务器。

Then, we’ll add the Client Id and Client secret of our Okta app that was generated in the previous section.

然后,我们将添加上一节中生成的Okta应用程序的客户端标识客户端秘密

Last, we’ve configured the same redirect-uri that is being set in the Application Settings.

最后,我们配置了与应用程序设置中设置的相同的redirect-uri

4. HomeController

4.HomeController

After that, let’s create the HomeController class:

之后,让我们创建HomeController类。

@RestController
public class HomeController {
    @GetMapping("/")
    public String home(@AuthenticationPrincipal OidcUser user) {
        return "Welcome, "+ user.getFullName() + "!";
    }
}

Here, we’ve added the home method with Base Uri (/) mapping, configured in the Application Settings.

在这里,我们添加了home方法与Base Uri(/)映射,在应用程序设置中进行了配置。

Also, the argument of the home method is an instance of the OidcUser class provided by Spring Security for accessing the user information.

另外,home方法的参数是OidcUser类的一个实例,该类由Spring Security提供,用于访问用户信息

That’s it! Our Spring Boot App is ready with Okta security support. Let’s run our app using the Maven command:

这就是了!我们的Spring Boot应用已经准备好支持Okta安全了。让我们用Maven命令来运行我们的应用程序。

mvn spring-boot:run

When accessing the application at localhost:8080, we’ll see a default sign-in page provided by Okta:

当在localhost:8080访问应用程序时,我们将看到Okta提供的一个默认的登录页面。

Once logged in using the registered user’s credentials, a welcome message with the user’s full name will be shown:

一旦使用注册用户的凭证登录,就会显示一个带有用户全名的欢迎信息。

Also, we’ll find a “Sign up” link at the bottom of the default sign-in screen for self-registration.

另外,我们会在默认的签到界面的底部发现一个 “注册 “链接,用于自我注册。

5. Sign Up

注册

5.1. Self-Registration

5.1.自行登记

For the first time, we can create an Okta account by using the “Sign up” link, and then providing information like email, first name, and last name:

第一次,我们可以通过使用 “注册 “链接创建一个Okta账户,然后提供电子邮件、名字和姓氏等信息。

5.2. Create a User

5.2.创建一个用户

Or, we can create a new user from the Users menu in the Okta developer account:

或者,我们可以从Okta开发者账户的Users菜单中创建一个新用户。

5.3. Self-Service Registration Settings

5.3.自助服务注册设置

Additionally, sign-up and registration settings can be configured from the Users menu in the Okta developer account:

此外,注册和登记设置可以从Okta开发者账户的Users菜单中进行配置。

6. Okta Spring SDK

6 Okta Spring SDK

Now that we’ve seen Okta security integration in the Spring Boot App, let’s interact with the Okta management API in the same app.

现在我们已经看到Okta在Spring Boot应用程序中的安全集成,让我们在同一个应用程序中与Okta管理API进行交互。

First, we should create a Token by using the API menu in the Okta developer account:

首先,我们应该通过使用Okta开发者账户中的API菜单创建一个Token

Make sure to note down the Token as it is shown only once after generation. Then, it’ll be stored as a hash for our protection.

请确保记下Token,因为它在生成后只显示一次。然后,它将被存储为哈希值,以保护我们。

6.1. Setup

6.1.设置

Then, let’s add the latest okta-spring-sdk Maven dependency to our pom.xml:

然后,让我们把最新的okta-spring-sdk Maven依赖性添加到我们的pom.xml

<dependency>
    <groupId>com.okta.spring</groupId>
    <artifactId>okta-spring-sdk</artifactId>
    <version>1.4.0</version>
</dependency>

6.2. application.properties

6.2.application.properties

Next, we’ll add a few essential Okta client properties:

接下来,我们将添加一些基本的Okta客户端属性。

okta.client.orgUrl=https://dev-example123.okta.com
okta.client.token=00TVXDNx1e2FgvxP4jLlONbPMzrBDLwESSf9hZSvMI123

Here, we’ve added the token noted in the previous section.

在这里,我们已经添加了上一节中提到的令牌。

6.3. AdminController

6.3.AdminController

Last, let’s create the AdminController, injected with the Client instance:

最后,让我们创建AdminController,用Client实例注入。

@RestController
public class AdminController {
    @Autowired
    public Client client;
}

That’s it! We’re ready to call methods on the Client instance to make requests to the Okta API.

这就是了!我们已经准备好调用Client实例上的方法,向Okta API发出请求。

6.4. List Users

6.4 列表用户

Let’s create the getUsers method to fetch a list of all users in our organization, using the listUsers method that returns a UserList object:

让我们创建getUsers方法来获取我们组织中所有用户的列表,使用listUsers方法来返回一个UserList对象。

public class AdminController {
    // ...

    @GetMapping("/users") 
    public UserList getUsers() { 
        return client.listUsers(); 
    }
}

After that, we can access localhost:8080/users to receive a JSON response containing all users:

之后,我们可以访问localhost:8080/users来接收包含所有用户的JSON响应。

{
    "dirty":false,
    "propertyDescriptors":{
        "items":{
            "name":"items",
            "type":"com.okta.sdk.resource.user.User"
        }
    },
    "resourceHref":"/api/v1/users",
    "currentPage":{
        "items":[
            {
                "id":"00uanxiv7naevaEL14x6",
                "profile":{
                    "firstName":"Anshul",
                    "lastName":"Bansal",
                    "email":"anshul@bansal.com",
                    // ...
                },
                // ...
            },
            { 
                "id":"00uag6vugXMeBmXky4x6", 
                "profile":{ 
                    "firstName":"Ansh", 
                    "lastName":"Bans", 
                    "email":"ansh@bans.com",
                    // ... 
                }, 
                // ... 
            }
        ]
    },
    "empty":false,
    // ...
}

6.5. Search User

6.5.搜索用户

Similarly, we can filter users using the firstName, lastName, or email as query parameters:

同样,我们可以使用firstNamelastNameemail作为查询参数过滤用户

@GetMapping("/user")
public UserList searchUserByEmail(@RequestParam String query) {
    return client.listUsers(query, null, null, null, null);
}

Let’s search for a user by email using localhost:8080/user?query=ansh@bans.com:

让我们通过email搜索一个用户,使用localhost:8080/user?query=ansh@bans.com

{
    "dirty":false,
    "propertyDescriptors":{
        "items":{
            "name":"items",
            "type":"com.okta.sdk.resource.user.User"
        }
    },
    "resourceHref":"/api/v1/users?q=ansh%40bans.com",
    "currentPage":{
        "items":[
            {
                "id":"00uag6vugXMeBmXky4x6",
                "profile":{
                    "firstName":"Ansh",
                    "lastName":"Bans",
                    "email":"ansh@bans.com",
                    // ...
                },
                // ...
            }
        ]
    },
    // ...
}

6.6. Create User

6.6.创建用户

Also, we can create a new user by using the instance method of the UserBuilder interface:

另外,我们可以通过使用UserBuilder接口的instance方法创建一个新用户。

@GetMapping("/createUser")
public User createUser() {
    char[] tempPassword = {'P','a','$','$','w','0','r','d'};
    User user = UserBuilder.instance()
        .setEmail("normal.lewis@email.com")
        .setFirstName("Norman")
        .setLastName("Lewis")
        .setPassword(tempPassword)
        .setActive(true)
        .buildAndCreate(client);
    return user;
}

So, let’s access localhost:8080/createUser and verify new user’s details:

因此,让我们访问localhost:8080/createUser并验证新用户的详细信息。

{
    "id": "00uauveccPIYxQKUf4x6",   
    "profile": {
        "firstName": "Norman",
        "lastName": "Lewis",
        "email": "norman.lewis@email.com"
    },
    "credentials": {
        "password": {},
        "emails": [
            {
                "value": "norman.lewis@email.com",
                "status": "VERIFIED",
                "type": "PRIMARY"
            }
        ],
        // ...
    },
    "_links": {
        "resetPassword": {
            "href": "https://dev-example123.okta.com/api/v1/users/00uauveccPIYxQKUf4x6/lifecycle/reset_password",
            "method": "POST"
        },
        // ...
    }
}

Similarly, we can perform a range of operations like listing all applications, creating an application, listing all groups, and creating a group.

同样,我们可以执行一系列操作,如列出所有应用程序,创建一个应用程序,列出所有组,以及创建一个组

7. Conclusion

7.结语

In this quick tutorial, we explored Spring Security with Okta.

在这个快速教程中,我们探讨了Spring Security与Okta。

First, we set up the Okta developer account with essential configurations. Then, we created a Spring Boot App and configured the application.properties for Spring Security integration with Okta.

首先,我们用基本配置设置了Okta开发者账户。然后,我们创建了一个Spring Boot应用程序,并配置了application.properties,以便Spring Security与Okta集成。

Next, we integrated the Okta Spring SDK to manage Okta API. Last, we looked into features like listing all users, searching a user, and creating a user.

接下来,我们集成了Okta Spring SDK来管理Okta API。最后,我们研究了列出所有用户、搜索用户和创建用户等功能。

As usual, all the code implementations are available over on GitHub.

像往常一样,所有的代码实现都可以在GitHub上找到