官术网_书友最值得收藏!

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):

  1. 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
  2. After creating the auth-code-server project, import it to your IDE. If you are using Eclipse, import it as a Maven project.
  3. 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>
  1. 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
  1. 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.
  1. 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
}
  1. 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 {
}
  1. 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);
}
  1. 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.
  1. 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 {
}
  1. 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");
}
  1. 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.
  2. Then add the following annotations at the class level for OAuth2ResourceServer as follows:
@Configuration
@EnableResourceServer
public class OAuth2ResourceServer
extends ResourceServerConfigurerAdapter {
}
  1. 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/**");
}
  1. The application is ready for access token issuing as well as access token validation through the API's usage.
主站蜘蛛池模板: 儋州市| 黑龙江省| 麻阳| 兴业县| 临江市| 江西省| 达尔| 博乐市| 鄂州市| 拉萨市| 综艺| 佛教| 荣成市| 胶南市| 莱州市| 茶陵县| 资兴市| 泰安市| 鄂托克前旗| 花垣县| 景宁| 钟山县| 莒南县| 赞皇县| 彰化市| 城市| 始兴县| 繁峙县| 华宁县| 利津县| 元江| 新宁县| 阿拉善盟| 华亭县| 莆田市| 嘉荫县| 泽库县| 台前县| 贵南县| 横峰县| 陕西省|