- 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.
推薦閱讀
- Advanced Splunk
- LabVIEW 2018 虛擬儀器程序設(shè)計(jì)
- Java系統(tǒng)分析與架構(gòu)設(shè)計(jì)
- 實(shí)戰(zhàn)Java程序設(shè)計(jì)
- Learning Linux Binary Analysis
- Mastering Rust
- 程序員修煉之道:通向務(wù)實(shí)的最高境界(第2版)
- Spring Boot Cookbook
- Building Machine Learning Systems with Python(Second Edition)
- Java語(yǔ)言程序設(shè)計(jì)教程
- 持續(xù)集成與持續(xù)交付實(shí)戰(zhàn):用Jenkins、Travis CI和CircleCI構(gòu)建和發(fā)布大規(guī)模高質(zhì)量軟件
- QGIS 2 Cookbook
- 從程序員角度學(xué)習(xí)數(shù)據(jù)庫(kù)技術(shù)(藍(lán)橋杯軟件大賽培訓(xùn)教材-Java方向)
- 人人都能開(kāi)發(fā)RPA機(jī)器人:UiPath從入門(mén)到實(shí)戰(zhàn)
- 從零開(kāi)始學(xué)UI:概念解析、實(shí)戰(zhàn)提高、突破規(guī)則