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

How to do it...

The following steps will guide you to configure an Authorization Server and a Resource Server using Spring Security OAuth2:

  1. 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
  2. After creating the client-credentials-server project, import it to your IDE. If 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:
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
  1. Open application.properties and add the same content that we have added for the first recipe to configure the user's credentials.
  2. 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).
  3. Open UserController class and replace the value for @RequestMapping annotation with "/user" instead of "/api/profile".
  4. 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;
}
}
  1. 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/**");
}
}
  1. 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");
}
}
  1. 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();
}
}
  1. Now run the application through your IDE actions or by running the Maven mvn spring-boot:run command.
主站蜘蛛池模板: 平武县| 卢氏县| 丰原市| 沅江市| 平原县| 佳木斯市| 东丽区| 谷城县| 邯郸县| 贵州省| 安义县| 宿松县| 陕西省| 竹山县| 卢龙县| 射阳县| 麻栗坡县| 阿尔山市| 筠连县| 扎赉特旗| 耿马| 丰镇市| 永春县| 遵义市| 镇巴县| 乐清市| 东安县| 石门县| 崇仁县| 美姑县| 平罗县| 尚志市| 余干县| 鄂尔多斯市| 菏泽市| 筠连县| 南丹县| 侯马市| 广平县| 枣阳市| 兴和县|