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

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.
主站蜘蛛池模板: 鱼台县| 泽州县| 吉安市| 巢湖市| 乐昌市| 桂林市| 承德市| 高阳县| 司法| 大名县| 无锡市| 吉林省| 灵璧县| 肃南| 蛟河市| 东光县| 沙田区| 鲁甸县| 屏山县| 洪湖市| 尤溪县| 古蔺县| 汝州市| 嘉荫县| 景东| 玛多县| 巢湖市| 合水县| 修武县| 肇源县| 新竹市| 卫辉市| 华阴市| 万年县| 江达县| 甘泉县| 阳春市| 思南县| 墨脱县| 东乡| 焉耆|