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

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.
主站蜘蛛池模板: 玉林市| 长宁区| 大英县| 岳普湖县| 甘德县| 南溪县| 定陶县| 探索| 休宁县| 乌什县| 芜湖县| 马龙县| 图木舒克市| 冕宁县| 斗六市| 厦门市| 定结县| 南溪县| 武胜县| 玉林市| 佛冈县| 元谋县| 承德市| 巩留县| 罗甸县| 高密市| 乐清市| 建昌县| 曲周县| 武邑县| 金乡县| 沾益县| 崇仁县| 中江县| 恩施市| 蚌埠市| 辽阳县| 偏关县| 北宁市| 文化| 仁寿县|