ホームページ >Java >&#&チュートリアル >Java API開発でのOAuth2認証の使用
Java API の開発において、認証は避けられない問題です。 OAuth2 は、アクセスを許可することで API リソースを保護する一般的な認証方法です。この記事では、Java API開発における認証にOAuth2を使用する方法を紹介します。
OAuth2 の紹介
OAuth2 は、認証情報を共有することなく、サードパーティのアプリケーションがサーバー リソースにアクセスすることをユーザーが承認できるようにする承認のオープン スタンダードです。 OAuth2 標準には次の役割が含まれています:
OAuth2 の認可プロセスには次のステップが含まれます:
OAuth2 は、認可コード モード、パスワード モード、クライアント モード、暗黙的認可モードなどを含む複数の認可タイプをサポートします。 Java APIの開発では、通常、認可コードモードとパスワードモードが使用されます。
OAuth2 認可コード モード
認可コード モードは、OAuth2 で最も一般的に使用される認可タイプであり、次の手順が含まれます:
Java API 開発では、Spring Security OAuth2 フレームワークを使用して認可コード モード認証を実装できます。
まず、pom.xml ファイルに次の依存関係を追加する必要があります:
<dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.4.RELEASE</version> </dependency>
次に、Spring MVC 構成ファイルに次の構成を追加します:
<security:http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="authenticationManager" xmlns="http://www.springframework.org/schema/security"> <security:intercept-url pattern="/oauth/token" access="isAuthenticated()" method="POST" /> <security:anonymous enabled="false" /> <security:http-basic entry-point-ref="clientAuthenticationEntryPoint" /> <security:custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER" /> <security:access-denied-handler ref="oauthAccessDeniedHandler" /> </security:http> <security:http pattern="/api/**" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint" access-decision-manager-ref="accessDecisionManager" xmlns="http://www.springframework.org/schema/security"> <security:anonymous enabled="false" /> <security:intercept-url pattern="/api/**" access="ROLE_USER" /> <security:custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" /> <security:access-denied-handler ref="oauthAccessDeniedHandler" /> </security:http> <bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"> <property name="realmName" value="spring-boot-oauth2" /> <property name="typeName" value="Basic" /> </bean> <bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"> <property name="realmName" value="spring-boot-oauth2" /> <property name="typeName" value="Bearer" /> </bean> <bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" /> <bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"> <property name="authenticationManager" ref="authenticationManager" /> </bean> <bean id="resourceServerFilter" class="org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter"> <property name="authenticationManager" ref="authenticationManager" /> </bean> <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased" xmlns="http://www.springframework.org/schema/beans"> <constructor-arg> <list> <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" /> <bean class="org.springframework.security.access.vote.RoleVoter" /> <bean class="org.springframework.security.access.vote.AuthenticatedVoter" /> </list> </constructor-arg> </bean> <security:authentication-manager id="authenticationManager"> <security:authentication-provider user-service-ref="userDetailsService" /> </security:authentication-manager> <bean id="userDetailsService" class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl"> <property name="dataSource" ref="dataSource" /> </bean>
Among /oauth/token はアクセス トークンの取得に使用されるパス、/api/** は認証が必要なパスです。
OAuth2RestTemplate を使用してリクエストを送信する場合、最初にアクセス トークンを取得する必要があります。コードは次のとおりです:
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(client, context); AuthorizationCodeResourceDetails details = (AuthorizationCodeResourceDetails)client.getResource(); AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider(); Authentication auth = new UsernamePasswordAuthenticationToken(username, password); AccessTokenRequest tokenRequest = provider.createAccessTokenRequest(details, auth); OAuth2AccessToken accessToken = provider.obtainAccessToken(details, tokenRequest); restTemplate.getOAuth2ClientContext().setAccessToken(accessToken);
このうち、クライアントは OAuth2ProtectedResourceDetails 型のオブジェクトであり、次のような情報が含まれています。クライアント ID とクライアント シークレットとして。
OAuth2 パスワード モード
パスワード モードは、クライアントを信頼するのに適した OAuth2 の承認タイプであり、次の手順が含まれます:
Java API 開発では、Spring Security OAuth2 フレームワークを使用してパスワード モード認証を実装できます。
まず、pom.xml ファイルに次の依存関係を追加する必要があります:
<dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.4.RELEASE</version> </dependency>
次に、Spring MVC 構成ファイルに次の構成を追加します:
<security:http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="authenticationManager" xmlns="http://www.springframework.org/schema/security"> <security:intercept-url pattern="/oauth/token" access="isAuthenticated()" method="POST" /> <security:anonymous enabled="false" /> <security:http-basic entry-point-ref="clientAuthenticationEntryPoint" /> <security:custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER" /> <security:access-denied-handler ref="oauthAccessDeniedHandler" /> </security:http> <security:http pattern="/api/**" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint" access-decision-manager-ref="accessDecisionManager" xmlns="http://www.springframework.org/schema/security"> <security:anonymous enabled="false" /> <security:intercept-url pattern="/api/**" access="ROLE_USER" /> <security:custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" /> <security:access-denied-handler ref="oauthAccessDeniedHandler" /> </security:http> <bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"> <property name="realmName" value="spring-boot-oauth2" /> <property name="typeName" value="Basic" /> </bean> <bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"> <property name="realmName" value="spring-boot-oauth2" /> <property name="typeName" value="Bearer" /> </bean> <bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" /> <bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter"> <property name="authenticationManager" ref="authenticationManager" /> </bean> <bean id="resourceServerFilter" class="org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter"> <property name="authenticationManager" ref="authenticationManager" /> </bean> <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased" xmlns="http://www.springframework.org/schema/beans"> <constructor-arg> <list> <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" /> <bean class="org.springframework.security.access.vote.RoleVoter" /> <bean class="org.springframework.security.access.vote.AuthenticatedVoter" /> </list> </constructor-arg> </bean> <security:authentication-manager id="authenticationManager"> <security:authentication-provider user-service-ref="userDetailsService" /> </security:authentication-manager> <bean id="userDetailsService" class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl"> <property name="dataSource" ref="dataSource" /> </bean>
Among /oauth/token はアクセス トークンの取得に使用されるパス、/api/** は認証が必要なパスです。
OAuth2RestTemplate を使用してリクエストを送信する場合、最初にアクセス トークンを取得する必要があります。コードは次のとおりです:
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(details, new DefaultOAuth2ClientContext()); restTemplate.getOAuth2ClientContext().setAccessToken(accesstoken);
このうち詳細は、クライアント ID を含む ResourceOwnerPasswordResourceDetails 型のオブジェクトです。 、クライアント シークレット、ユーザー名とパスワードなど。
概要
Java API 開発での認証に OAuth2 を使用すると、API リソースのセキュリティが保護され、ユーザーがサードパーティ アプリケーションのサーバー リソースへのアクセスを簡単に承認できるようになります。この記事では、OAuth2 の認可コード モードとパスワード モードを紹介し、Spring Security OAuth2 フレームワークを使用して認証を実装するためのサンプル コードを提供します。 Java API 開発者にとって役立つことを願っています。
以上がJava API開発でのOAuth2認証の使用の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。