- OAuth 2.0 Cookbook
- Adolfo Eloy Nascimento
- 617字
- 2021-07-08 09:35:07
How to do it...
The following steps will guide you to configure an Authorization Server and a Resource Server using Spring Security OAuth2, which prevents you from having to write an OAuth 2.0 Provider from scratch (which would be very unproductive and prone to security failures):
- Create the initial project using Spring Initializr as we did for the 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 auth-code-server
- Add Web and Security as dependencies for this project
- After creating the auth-code-server project, import it to your IDE. If you are 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 (to use an up-to-date Spring Security OAuth2 version, we have to override the version provided by Spring Boot):
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
- Open the application.properties file and add the following content to configure the user of the auth-code-server application (you can use a different user of course, but remember to change it whenever appropriate):
security.user.name=adolfo
security.user.password=123
- As we want to protect the user's resources through OAuth 2.0, we need to create something to be protected. To do so, create the UserController.java and UserProfile.java classes within the com.packt.example.authcodeserver.api package.
- Open the UserProfile.java class and make sure to add the following attributes (do not forget to create appropriate getters and setters for each attribute):
public class UserProfile {
private String name;
private String email;
// getters and setters hidden for brevity
}
- Open the UserController.java class and add the @Controller annotation at the head of the class declaration as follows:
As you might notice, Spring provides us some annotations such as @Controller, @Service, and @Component. Some annotations such as @Service and @Component just defines a declared class as a Spring managed bean (to be managed by Spring which allows for dependency injection mechanism). The @Controller annotation is a specialization of @Component annotation adding semantics for a web controller that can map endpoints to Java source code.
@Controller
public class UserController {
}
- Now, let's add the respective method that will provide the endpoint which will be protected by OAuth 2.0, as presented in the following code (import the User class from package org.springframework.security.core.userdetails):
@RequestMapping("/api/profile")
public ResponseEntity<UserProfile> profile() {
User user = (User) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
String email = user.getUsername() + "@mailinator.com";
UserProfile profile = new UserProfile();
profile.setName(user.getUsername());
profile.setEmail(email);
return ResponseEntity.ok(profile);
}
- Once we have the endpoint to be OAuth 2.0 protected, let's create the OAuth 2.0 Authorization Server configuration by creating the OAuth2AuthorizationServer class within the com.packt.example.authcodeserver.config package.
- Add the following annotations to OAuth2AuthorizationServer class and extend the AuthorizationServerConfigurerAdapter class which comes from the Spring Security OAuth2 project:
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends
AuthorizationServerConfigurerAdapter {
}
- To configure all the client details data, override the configure method which allows you to customize the ClientDetailsServiceConfigurer instance:
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("clientapp").secret("123456")
.redirectUris("http://localhost:9000/callback")
.authorizedGrantTypes("authorization_code")
.scopes("read_profile", "read_contacts");
}
- At the moment, the application is ready to start issuing access tokens, given the user grants permission. But to be allowed to access the user's resources (the Resource Owner profile for this recipe), we need to create the Resource Server's configuration by declaring the OAuth2ResourceServer class within the same package as OAuth2AuthorizationServer.
- Then add the following annotations at the class level for OAuth2ResourceServer as follows:
@Configuration
@EnableResourceServer
public class OAuth2ResourceServer
extends ResourceServerConfigurerAdapter {
}
- And to start protecting the user's profile endpoint, add the following configuration method within the OAuth2ResourceServer class:
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and()
.requestMatchers().antMatchers("/api/**");
}
- The application is ready for access token issuing as well as access token validation through the API's usage.
推薦閱讀
- Java Web基礎與實例教程(第2版·微課版)
- HTML5+CSS3基礎開發教程(第2版)
- C語言程序設計實訓教程
- 數據結構(Python語言描述)(第2版)
- Python Geospatial Development(Second Edition)
- 正則表達式經典實例(第2版)
- Java程序設計
- ANSYS Fluent 二次開發指南
- 精通MATLAB(第3版)
- 大數據分析與應用實戰:統計機器學習之數據導向編程
- Unity 2018 Shaders and Effects Cookbook
- Illustrator CS6設計與應用任務教程
- 超簡單:用Python讓Excel飛起來(實戰150例)
- Joomla!Search Engine Optimization
- 軟技能2:軟件開發者職業生涯指南