OAuth2是現代應用程式中廣泛使用的身份驗證和授權協定之一。它允許用戶授權第三方應用程式存取其資源,同時保護用戶敏感資訊不被洩露。在本文中,我們將介紹如何使用Java後端開發基於OAuth2建置安全性的API。
OAuth2是一種流行的授權協議,旨在解決應用程式間授權問題。它允許用戶授權第三方應用程式存取其資源,例如Google雲端硬碟或Facebook帳戶,同時保護用戶憑證不被洩露。 OAuth2中包含4種角色:資源擁有者、客戶端、授權伺服器和資源伺服器。資源擁有者是具有被保護資源的使用者或實體;客戶端是請求存取資源的應用程式;授權伺服器是驗證資源擁有者身分並頒發存取權杖的伺服器;資源伺服器是儲存和提供資源的伺服器。 OAuth2透過授權伺服器發出令牌,客戶端使用令牌向資源伺服器請求資源。
OAuth2流程包含下列步驟:
要建置安全性的API,我們需要實作下列步驟:
以下是基於Java和Spring框架的OAuth2範例:
@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); }
}
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(); }
#建立客戶端:
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; }
建立資源伺服器:
@GetMapping("/resource") public ResponseEntity<String> getResource() { return ResponseEntity.ok("resource"); }
驗證存取權杖:
@Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/oauth/**").permitAll() .anyRequest().authenticated() .and() .oauth2ResourceServer() .jwt(); }
綜述
以上是Java後端開發:基於OAuth2建置安全性的API的詳細內容。更多資訊請關注PHP中文網其他相關文章!