- OAuth 2.0 Cookbook
- Adolfo Eloy Nascimento
- 523字
- 2021-07-08 09:35:10
How to do it...
The following steps will guide you to configure an Authorization Server and a Resource Server using Spring Security OAuth2:
- Create the initial project using Spring Initializr, as we did for other recipes in this book. Go to https://start.spring.io/ and define the following data:
- Set up the Group as com.packt.example
- Define the Artifact as client-credentials-server
- Add Web and Security as dependencies for this project
- After creating the client-credentials-server project, import it to your IDE. If using Eclipse, import it as a Maven project.
- Open the pom.xml file and add the following dependency as we will use the Spring Security OAuth2 project:
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
- Open application.properties and add the same content that we have added for the first recipe to configure the user's credentials.
- Although this recipe isn't focused on the user's experience, we still have to create the API to retrieve user profile. To keep users being able to access the application in a safe manner to access their own profile, create the UserProfile and UserController classes within the api sub-package. The content for both classes must be the same as that was provided in the first recipe (generate a constructor using fields for UserProfile class).
- Open UserController class and replace the value for @RequestMapping annotation with "/user" instead of "/api/profile".
- As we are using the Client Credentials grant type, we won't allow any client to access the user's profile. Instead of the user's profile, we will create an API where the client application is able to retrieve all the users registered on the application server that we are protecting with OAuth 2.0. Perhaps, this business rule does not make sense to you, but let's stay focused on how to use the Client Credentials grant type with Spring Security OAuth2 instead of focusing on the business product itself. So, create the AdminController class as presented in the following code within the package com.packt.example.clientcredentialsserver.api:
@Controller
@RequestMapping("/api")
public class AdminController {
@RequestMapping("/users")
public ResponseEntity<List<UserProfile>> getAllUsers() {
return ResponseEntity.ok(getUsers());
}
private List<UserProfile> getUsers() {
List<UserProfile> users = new ArrayList<>();
users.add(new UserProfile("adolfo", "adolfo@mailinator.com"));
users.add(new UserProfile("demigreite", "demigreite@mailinator.com"));
users.add(new UserProfile("jujuba", "jujuba@mailinator.com"));
return users;
}
}
- Now to protect this API, create the following Resource Server configuration class declared as OAuth2ResourceServer inside the com.packt.example.clientcredentialsserver.config package:
@Configuration
@EnableResourceServer
public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.requestMatchers()
.antMatchers("/api/**");
}
}
- And to issue access tokens, create the OAuth2AuthorizationServer within the same package as the OAuth2ResourceServer class (now configure a different client ID and client secret, as well as the authorizedGrantTypes):
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends
AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients)
throws Exception {
clients.inMemory()
.withClient("clientadmin")
.secret("123")
.authorizedGrantTypes("client_credentials")
.scopes("admin");
}
}
- Now to protect the /users API from users that are not registered, let's create the following Spring Security configuration class within the config package as we did for the OAuth 2.0 Provider configuration classes:
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated().and()
.antMatcher("/user/**")
.httpBasic()
.and()
.csrf().disable();
}
}
- Now run the application through your IDE actions or by running the Maven mvn spring-boot:run command.
推薦閱讀
- Vue.js設計與實現
- PyTorch Artificial Intelligence Fundamentals
- 概率成形編碼調制技術理論及應用
- SAP BusinessObjects Dashboards 4.1 Cookbook
- Visual C++開發入行真功夫
- Yii Project Blueprints
- SQL 經典實例
- Python全棧數據工程師養成攻略(視頻講解版)
- R用戶Python學習指南:數據科學方法
- 用案例學Java Web整合開發
- Microsoft 365 Certified Fundamentals MS-900 Exam Guide
- QGIS 2 Cookbook
- Illustrator CS6設計與應用任務教程
- Struts 2.x權威指南
- 實驗編程:PsychoPy從入門到精通