「[[マイクロソフト系技術情報 Wiki>http://techinfoofmicrosofttech.osscons.jp/]]」は、「[[Open棟梁Project>https://github.com/OpenTouryoProject/]]」,「[[OSSコンソーシアム .NET開発基盤部会>https://www.osscons.jp/dotNetDevelopmentInfrastructure/]]」によって運営されています。

-[[戻る>ASP.NET IdentityによるSTS実装]]

* 目次 [#pa2f98f2]
#contents

*概要 [#d34062d7]
[[ASP.NET Identity]]の、[[OAuth]] 2.0によるセキュアトークンサービス(STS)のEndpoint追加実装。

*準備 [#m89963e5]
OAuth2.0 Server、Client共に以下からダウンロード可能。

-[[The ASP.NET Site - OWIN OAuth 2.0 Authorization Server>#e91aecfc]] - [[Download the sample code. >#a54340f2]]

このサンプルは、VS2013・2015で、そのままF5実行可能で非常に便利。

* 検証 [#q1e1dc7b]
ダウンロードしたサンプルを使用して、以下のシナリオの検証ができる。

**[[Authorization Codeグラント種別>OAuth#yfeb403d]] [#c10b1134]

**[[Implicitグラント種別>OAuth#m5c2d510]] [#q04bafc1]

**[[Resource Owner Password Credentialsグラント種別>OAuth#zfff6f89]] [#scc2faab]

**[[Client Credentialsグラント種別>OAuth#o9473080]] [#o67b23a6]

*ASP.NET IdentityでOAuth2のRFCに追加されている仕様 [#t66f37b0]

**RFCに規定のない認証の仕掛け [#dc5f8e84]
-認証には、(基本的に、)ASP.NET Identityを使用する。

-Bearer Tokenの発行には、ClaimsIdentityを使用する。

--ASP.NET MVCアプリケーションの認可エンドポイント上

---Cookie認証チケットからClaimsIdentityを生成できる。
 AuthenticateResult ticket = this.AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie).Result;
 ClaimsIdentity identity = (ticket != null) ? ticket.Identity : null;
 
---以下の方法でTokenを発行する。~
「Authorization Codeグラント種別」では仲介トークンを、~
「Implicitグラント種別」ではAccess Tokenを生成する。
 this.AuthenticationManager.SignIn(identity);

--OAuthAuthorizationServerProviderのTokenエンドポイント上

---ユーザ情報を使用してClaimsIdentityを生成する。
 ClaimsIdentity identity = await userManager.CreateIdentityAsync(
                user, DefaultAuthenticationTypes.ExternalBearer);

---以下の方法でTokenを発行する。~
「Resource Owner Password Credentialsグラント種別」~
「Client Credentialsグラント種別」の両方でAccess Tokenを生成する。
 context.Validated(identity);

-ClaimsIdentityにCustomの情報を格納する場合、以下の様にClaimを追加する。
 identity.AddClaim(new Claim("urn:oauth:scope", scope));

**参考(サービス / ミドルウェア毎の仕様の違い) [#m5bdf7c8]
「[[技術文書中での Shall / Should / May]]」があるため、~
サービス / ミドルウェア毎に仕様は異なってくる。以下が参考になる。

-OAuth2.0対応サービスのstate, redirect_uriパラメータの扱い色々 - BangBlog~
http://bang.hateblo.jp/entry/2012/10/09/002003

やはり、サービスによって扱いがマチマチなのは、~
redirect_uriパラメタとstateパラメタであるもよう。

**Bearer Tokenを暗号化・復号化する秘密鍵 [#h3e8e7b7]
-認可サーバ(Authorization Server)とリソースサーバ(Resource Server)が同じマシン上に無い場合、~
Bearer Tokenを暗号化・復号化する秘密鍵を双方のマシン間で一致させる必要がある。

-これには、以下のように、machinekeyを両方のweb.configファイルに追加する必要がある。
-これには、以下のように、machinekeyを両方の[[Web.config>#nf687ad7]]ファイルに追加する必要がある。
 <system.web>
     <machineKey decryptionKey="Enter decryption Key here" 
         validation="SHA1" 
         validationKey="Enter validation Key here" />
 </system.web>

machineKeyセクションの生成には、以下のツールが使えそう。
-インストール時に MachineKey を自動生成する NuGet パッケージを作った - しばやん雑記~
http://blog.shibayan.jp/entry/20150703/1435897073
--NuGet Gallery | MachineKeyGenerator 0.4.0~
https://www.nuget.org/packages/MachineKeyGenerator/
---garafu/MachineKeyGenerator:~
https://github.com/garafu/MachineKeyGenerator
>This tool allows you to generate random keys for validation and encryption/decription of the view state.

**[[Bearer TokenをJWTアサーションに変更する方法>JWTとOAuth2.0#k0b22c52]] [#a0f5b8a7]

*[[ASP.NET Identity(Identity 2.0)>ASP.NET Identity]](net45)で通常サポートされないSTS機能 [#wd8dc7cd]

**[[OAuth2拡張>ASP.NET IdentityのOAuth2拡張によるSTS実装]] [#m177beb2]

**[[OpenID Connect>ASP.NET IdentityのOIDCによるSTS実装]] [#m177beb2]

*参考 [#r532a3ca]
-OAuthAuthorizationServerProvider クラス (Microsoft.Owin.Security.OAuth)~
https://msdn.microsoft.com/ja-jp/library/microsoft.owin.security.oauth.oauthauthorizationserverprovider.aspx

**The ASP.NET Site [#ac1aed47]
-OWIN OAuth 2.0 Authorization Server~
https://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server

このコンテンツは以下の様な構成になっている。
-[[Download the sample code.>#a54340f2]]
-[[Create an Authorization Server.>#ub84ef28]]
-[[Creating a Resource Server.>#ld778043]]
-[[Create OAuth 2.0 Clients.>#y247ad21]]

***Download the sample code. [#gf225bcb]
以下から、サンプル・コードをダウンロードできる。

http://code.msdn.microsoft.com/OWIN-OAuth-20-Authorization-ba2b8783/file/114932/1/AuthorizationServer.zip

***Create an Authorization Server. [#g23d081f]
-このAuthorization ServerはOAuthの4つのフローをサポートしている。
--Authorization Code Grant Client
--Implicit Grant Client
--Resource Owner Password Credentials Grant Client
--Client Credentials Grant Client

-サーバーの設定と実装
--OWIN Startup classでの設定

--OAuthAuthorizationServerProviderの実装

---ValidateClientRedirectUri~
(Authorization Code, Implicitグラント種別)
---ValidateClientAuthentication~
(Resource Owner Password Credentials, Client Credentialsグラント種別)
---GrantResourceOwnerCredentials~
(Resource Owner Password Credentialsグラント種別)
---GrantClientCredetails~
(Client Credentialsグラント種別)

--AuthorizeEndpointの実装~
(Authorization Code, Implicitグラント種別)

***Creating a Resource Server. [#z4a66371]
アクセストークンによって保護されたResource ServerのEndpointを作成。

***Create OAuth 2.0 Clients. [#j539efef]
.NETクライアント・アプリからHTTPアクセスする際のライブラリとしては、[[DotNetOpenAuth.OAuth2>https://www.nuget.org/packages/DotNetOpenAuth.OAuth2.Client]]を使用している。

-Authorization Code Grant Client~
WebApplicationとして実装。

-Implicit Grant Client~
JavaScriptで実装。

-Resource Owner Password Credentials Grant Client~
コンソール・アプリケーションで実装。

-Client Credentials Grant Client~
コンソール・アプリケーションで実装。

***関連する情報 [#vb13987d]
-The ASP.NET Forums
--OWIN and Authorization Code Grant Flow - Always Bad Request (Invalid Grant)~
https://forums.asp.net/t/1975505.aspx?OWIN+and+Authorization+Code+Grant+Flow+Always+Bad+Request+Invalid+Grant+

-Stack Overflow
--MVC 5 application - implement OAuth Authorization code flow~
http://stackoverflow.com/questions/25845420/mvc-5-application-implement-oauth-authorization-code-flow
--asp.net - Authorization_code grant flow on Owin.Security.OAuth: returns invalid_grant~
http://stackoverflow.com/questions/24515211/authorization-code-grant-flow-on-owin-security-oauth-returns-invalid-grant

-その他
--AuthServerTests.cs | Source Browser~
http://sourcebrowser.io/Browse/jchannon/katanaproject/tests/FunctionalTests/Facts/Security/AuthServer/AuthServerTests.cs#207

**その他のサイト [#vf52938b]
実装方法の調査で参照にしたサイト。

-ASP.NET WebAPI2でAjaxでOAuth認証するよ(ついでにTypeScriptとReact) - かずきのBlog@hatena~
http://blog.okazuki.jp/entry/2016/01/15/215901
-ASP.NET SPA (JavaScript) の Web API 認証 (ASP.NET Identity) – Tsmatz~
https://blogs.msdn.microsoft.com/tsmatsuz/2014/05/20/asp-net-spa-javascript-web-api-asp-net-identity-html5biz/

-asp.net - How do you consume extra parameters~
in OAuth2 Token request within .net WebApi2 application - Stack Overflow~
http://stackoverflow.com/questions/21243996/how-do-you-consume-extra-parameters-in-oauth2-token-request-within-net-webapi2
-c# - Can't get UserManager from OwinContext in apicontroller - Stack Overflow~
http://stackoverflow.com/questions/24001245/cant-get-usermanager-from-owincontext-in-apicontroller
-Simple OAuth Server: Implementing a Simple OAuth Server~
with Katana OAuth Authorization Server Components (Part 1) - Tugberk Ugurlu's Blog~
http://www.tugberkugurlu.com/archive/simple-oauth-server-implementing-a-simple-oauth-server-with-katana-oauth-authorization-server-components-part-1

----
Tags: [[:.NET開発]], [[:ASP.NET]], [[:ASP.NET MVC]], [[:ASP.NET SPA]], [[[[ASP.NET Web API]]]], [[:ASP.NET Identity]], [[:OAuth]], [[:認証基盤]], [[:セキュリティ]]

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS