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.
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.
The OAuth2 process consists of the following steps:
To build a secure API, we need to implement the following steps:
The following is an OAuth2 example based on Java and Spring framework:
@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); }
}
@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(); }
}
@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; }
}
@RestController
public class ResourceController {
@GetMapping("/resource") public ResponseEntity<String> getResource() { return ResponseEntity.ok("resource"); }
}
@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(); }
}
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!