- 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.
推薦閱讀
- C++ Primer習題集(第5版)
- Ceph Cookbook
- Spring技術內幕:深入解析Spring架構與設計
- arc42 by Example
- Programming ArcGIS 10.1 with Python Cookbook
- PostgreSQL 11從入門到精通(視頻教學版)
- Mastering Swift 2
- Android 應用案例開發(fā)大全(第3版)
- D3.js 4.x Data Visualization(Third Edition)
- Java網絡編程核心技術詳解(視頻微課版)
- D3.js By Example
- Everyday Data Structures
- C編程技巧:117個問題解決方案示例
- Java多線程并發(fā)體系實戰(zhàn)(微課視頻版)
- Getting Started with Windows Server Security