Home > Backend Development > PHP Tutorial > Java backend development: Building secure APIs based on OAuth2

Java backend development: Building secure APIs based on OAuth2

王林
Release: 2023-06-17 10:42:01
Original
1563 people have browsed it

OAuth2 is one of the widely used authentication and authorization protocols in modern applications. It allows users to authorize third-party applications to access their resources while protecting users' sensitive information from being leaked. In this article, we will introduce how to build a secure API based on OAuth2 using Java backend development.

  1. What is OAuth2?

OAuth2 is a popular authorization protocol designed to solve inter-application authorization problems. It allows users to authorize third-party applications to access their resources, such as Google Drive or Facebook accounts, while protecting user credentials from being compromised. OAuth2 contains 4 roles: resource owner, client, authorization server and resource server. The resource owner is the user or entity with the protected resource; the client is the application that requests access to the resource; the authorization server is the server that verifies the identity of the resource owner and issues an access token; the resource server is the server that stores and provides resources. OAuth2 issues a token through an authorization server, and the client uses the token to request resources from the resource server.

  1. OAuth2 process

The OAuth2 process consists of the following steps:

  1. The client makes a request to the authorization server, including its identifier and Directed URI.
  2. The authorization server verifies the client's identity and requires the resource owner to authorize the client to access its resources.
  3. The resource owner authorizes the client to access its resources.
  4. The authorization server issues an access token to the client.
  5. The client uses the access token to request access to resources from the resource server.
  6. The resource server verifies whether the access token is valid and provides the resource.
  7. Build a secure API based on OAuth2

To build a secure API, we need to implement the following steps:

  1. Create an OAuth2 server: We need to create an OAuth2 The server issues access tokens, authenticates clients, and authorizes requests.
  2. Configuring Spring Security: Spring Security is the security framework in the Spring ecosystem that handles authentication and authorization. We need to configure the OAuth2 authentication and authorization flow for Spring Security.
  3. Create client: We need to create a client to request access to the resource server and obtain an access token from the OAuth2 server.
  4. Create resource server: We need to create resource server to store and serve protected resources.
  5. Verify access token: We need to verify whether the access token is valid in the resource server and provide the corresponding resources according to the scope of the token.

The following is an OAuth2 example based on Java and Spring framework:

  1. Create an OAuth2 server:

@EnableAuthorizationServer
@Configuration
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

private final PasswordEncoder passwordEncoder;
private final AuthenticationManager authenticationManager;
private final UserDetailsService userDetailsService;

@Autowired
public OAuth2AuthorizationConfig(
        PasswordEncoder passwordEncoder,
        AuthenticationManager authenticationManager,
        UserDetailsService userDetailsService
) {
    this.passwordEncoder = passwordEncoder;
    this.authenticationManager = authenticationManager;
    this.userDetailsService = userDetailsService;
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
            .withClient("client")
            .secret(passwordEncoder.encode("secret"))
            .authorizedGrantTypes("authorization_code")
            .scopes("read", "write", "trust")
            .redirectUris("http://localhost:8080/login/oauth2/code/");
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.authenticationManager(authenticationManager)
            .userDetailsService(userDetailsService);
}
Copy after login

}

  1. Configure Spring Security:

@Configuration
@EnableWebSecurity
@ EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

private final UserDetailsService userDetailsService;
private final PasswordEncoder passwordEncoder;

@Autowired
public WebSecurityConfig(
        UserDetailsService userDetailsService,
        PasswordEncoder passwordEncoder
) {
    this.userDetailsService = userDetailsService;
    this.passwordEncoder = passwordEncoder;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/oauth/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .oauth2Login();
}
Copy after login

}

  1. Create client:

@RestController
public class ClientController {

private final OAuth2AuthorizedClientService authorizedClientService;

@Autowired
public ClientController(OAuth2AuthorizedClientService authorizedClientService) {
    this.authorizedClientService = authorizedClientService;
}

@GetMapping("/resource")
public ResponseEntity<String> getResource(OAuth2AuthenticationToken authentication) {
    OAuth2AuthorizedClient authorizedClient = authorizedClientService.loadAuthorizedClient(
            authentication.getAuthorizedClientRegistrationId(),
            authentication.getName()
    );
    HttpHeaders headers = new HttpHeaders();
    headers.setBearerAuth(authorizedClient.getAccessToken().getTokenValue());
    HttpEntity<String> entity = new HttpEntity<>(headers);
    ResponseEntity<String> response = new RestTemplate().exchange(
            "http://localhost:8081/resource",
            HttpMethod.GET,
            entity,
            String.class
    );
    return response;
}
Copy after login

}

  1. Create resource server:

@RestController
public class ResourceController {

@GetMapping("/resource")
public ResponseEntity<String> getResource() {
    return ResponseEntity.ok("resource");
}
Copy after login

}

  1. Verify access token:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/oauth/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .oauth2ResourceServer()
            .jwt();
}
Copy after login

}

  1. Overview

In this article, we introduce the process of the OAuth2 protocol and provide an example based on Java and Spring framework. By using OAuth2, we can build more secure APIs and protect users' sensitive information from being leaked. In API development, we should always pay attention to security to protect user data and application resources.

The above is the detailed content of Java backend development: Building secure APIs based on OAuth2. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template