Skip to content

Commit

Permalink
fixed #231
Browse files Browse the repository at this point in the history
fixed MVC of VB.
  • Loading branch information
daisukenishino committed Aug 17, 2017
1 parent f32aafe commit cbbaab9
Show file tree
Hide file tree
Showing 7 changed files with 170 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,51 @@

Imports MVC_Sample.Models.ViewModels

Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Threading.Tasks

Imports Microsoft.Owin.Security.DataHandler.Encoder

Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq

Imports Touryo.Infrastructure.Business.Presentation
Imports Touryo.Infrastructure.Business.Util
Imports Touryo.Infrastructure.Framework.Util
Imports Touryo.Infrastructure.Public.Util
Imports Touryo.Infrastructure.Public.Util.JWT

Namespace Controllers
''' <summary>HomeController</summary>
<Authorize>
Public Class HomeController
Inherits MyBaseMVController

''' <summary>Nonce</summary>
Public ReadOnly Property Nonce() As String
Get
If Session("nonce") Is Nothing Then
Session("nonce") = GetPassword.Base64UrlSecret(10)
Return DirectCast(Session("nonce"), String)
Else
Return DirectCast(Session("nonce"), String)
End If
End Get
End Property

''' <summary>State</summary>
Public ReadOnly Property State() As String
Get
If Session("state") Is Nothing Then
Session("state") = GetPassword.Base64UrlSecret(10)
Return DirectCast(Session("state"), String)
Else
Return DirectCast(Session("state"), String)
End If
End Get
End Property

''' <summary>
''' GET: Home
''' </summary>
Expand Down Expand Up @@ -60,28 +96,41 @@ Namespace Controllers
<AllowAnonymous>
<ValidateAntiForgeryToken>
Public Function Login(model As LoginViewModel) As ActionResult
If Not String.IsNullOrEmpty(model.UserName) Then
' 認証か完了した場合、認証チケットを生成し、元のページにRedirectする。
' 第2引数は、「クライアントがCookieを永続化(ファイルとして保存)するかどうか。」
' を設定する引数であるが、セキュリティを考慮して、falseの設定を勧める。
FormsAuthentication.RedirectFromLoginPage(model.UserName, False)

' 認証情報を保存する。
Dim ui As New MyUserInfo(model.UserName, Request.UserHostAddress)
UserInfoHandle.SetUserInformation(ui)

'基盤に任せるのでリダイレクトしない。
'return this.Redirect(ReturnUrl);
Return New EmptyResult()
Else
' ユーザー認証 失敗
Me.ModelState.AddModelError(String.Empty, "指定されたユーザー名またはパスワードが正しくありません。")
If Not Request.Form.AllKeys.Any(Function(x) x = "external") Then
' 通常ログイン
If ModelState.IsValid Then
If Not String.IsNullOrEmpty(model.UserName) Then
' 認証か完了した場合、認証チケットを生成し、元のページにRedirectする。
' 第2引数は、「クライアントがCookieを永続化(ファイルとして保存)するかどうか。」
' を設定する引数であるが、セキュリティを考慮して、falseの設定を勧める。
FormsAuthentication.RedirectFromLoginPage(model.UserName, False)

' 認証情報を保存する。
Dim ui As New MyUserInfo(model.UserName, Request.UserHostAddress)
UserInfoHandle.SetUserInformation(ui)

' Session消去
Me.FxSessionAbandon()
'基盤に任せるのでリダイレクトしない。
'return this.Redirect(ReturnUrl);
Return New EmptyResult()
Else
' ユーザー認証 失敗
Me.ModelState.AddModelError(String.Empty, "指定されたユーザー名またはパスワードが正しくありません。")

' Session消去
Me.FxSessionAbandon()
End If
Else
' Session消去
Me.FxSessionAbandon()
End If

' ポストバック的な
Return Me.View(model)
Else
' 外部ログイン
Return Redirect(String.Format(
"http://localhost:63359/MultiPurposeAuthSite/Account/OAuthAuthorize?client_id=f53469c17c5a432f86ce563b7805ab89&response_type=code&scope=profile%20email%20phone%20address%20userid%20auth%20openid&state={0}&nonce={1}",
Me.State, Me.Nonce))
End If
End Function

Expand All @@ -103,5 +152,83 @@ Namespace Controllers
FormsAuthentication.SignOut()
Return Me.Redirect(Url.Action("Index", "Home"))
End Function

''' <summary>OAuthAuthorizationCodeGrantClient</summary>
''' <param name="code">string</param>
''' <param name="state">string</param>
''' <returns>ActionResultを非同期的に返す</returns>
<HttpGet>
<AllowAnonymous>
Public Async Function OAuthAuthorizationCodeGrantClient(code As String, state As String) As Task(Of ActionResult)
If state = Me.State Then
' CSRF(XSRF)対策のstateの検証は重要
Dim httpClient As New HttpClient()

Dim httpRequestMessage As HttpRequestMessage = Nothing
Dim httpResponseMessage As HttpResponseMessage = Nothing

' HttpRequestMessage (Method & RequestUri)
httpRequestMessage = New HttpRequestMessage() With {
.Method = HttpMethod.Post,
.RequestUri = New Uri("http://localhost:63359/MultiPurposeAuthSite/OAuthBearerToken")
}

' HttpRequestMessage (Headers & Content)
httpRequestMessage.Headers.Authorization =
New AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(
String.Format("{0}:{1}", "f53469c17c5a432f86ce563b7805ab89", "cKdwJb6mRKVIJpGxEWjIC94zquQltw_ECfO-55p21YM"))))

httpRequestMessage.Content = New FormUrlEncodedContent(New Dictionary(Of String, String)() From {
{"grant_type", "authorization_code"},
{"code", code},
{"redirect_uri", System.Web.HttpUtility.HtmlEncode("http://localhost:58496/MVC_Sample/Home/OAuthAuthorizationCodeGrantClient")}
})

' HttpResponseMessage
httpResponseMessage = Await httpClient.SendAsync(httpRequestMessage)
Dim response As String = Await httpResponseMessage.Content.ReadAsStringAsync()

' 汎用認証サイトはOIDCをサポートしたのでid_tokenを取得し、検証可能。
Dim base64UrlEncoder As New Base64UrlTextEncoder()
Dim dic As Dictionary(Of String, String) = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(response)

' id_tokenの検証コード
Dim id_token As String = dic("id_token")

Dim jwtRS256 As New JWT_RS256("C:\Git1\MultiPurposeAuthSite\root\programs\MultiPurposeAuthSite\CreateClientsIdentity\CreateClientsIdentity_RS256.cer", "test")

If jwtRS256.Verify(id_token) Then
Dim jwtPayload As String = Encoding.UTF8.GetString(base64UrlEncoder.Decode(dic("id_token").Split("."c)(1)))

' id_tokenライクなJWTなので、中からsubなどを取り出すことができる。
Dim jobj As JObject = DirectCast(JsonConvert.DeserializeObject(jwtPayload), JObject)

Dim nonce As String = jobj("nonce").ToString()
Dim iss As String = jobj("iss").ToString()
Dim aud As String = jobj("aud").ToString()
Dim iat As String = jobj("iat").ToString()
Dim exp As String = jobj("exp").ToString()

Dim [sub] As String = jobj("sub").ToString()

If nonce = Me.Nonce AndAlso
iss = "http://jwtssoauth.opentouryo.com" AndAlso
aud = "f53469c17c5a432f86ce563b7805ab89" AndAlso
Long.Parse(exp) >= DateTimeOffset.Now.ToUnixTimeSeconds() Then
' ログインに成功
FormsAuthentication.RedirectFromLoginPage([sub], False)
Dim ui As New MyUserInfo([sub], Request.UserHostAddress)
UserInfoHandle.SetUserInformation(ui)

Return New EmptyResult()
Else
End If
Else
End If
End If

' ログインに失敗
Return RedirectToAction("Login")
End Function
End Class
End Namespace
Original file line number Diff line number Diff line change
Expand Up @@ -203,14 +203,18 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\Frameworks\Infrastructure\Build\Framework.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Owin, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Owin.3.0.1\lib\net45\Microsoft.Owin.dll</HintPath>
<Reference Include="Microsoft.Owin, Version=3.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Owin.3.1.0\lib\net45\Microsoft.Owin.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Owin.Host.SystemWeb, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Owin.Host.SystemWeb.3.0.1\lib\net45\Microsoft.Owin.Host.SystemWeb.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Owin.Security, Version=3.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Owin.Security.3.1.0\lib\net45\Microsoft.Owin.Security.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
<Private>True</Private>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ Namespace Models.ViewModels
''' <summary>
''' UserName
''' </summary>
<Required(AllowEmptyStrings:=False)>
<Display(Name:="User name")>
Public Property UserName() As String
Get
Expand All @@ -54,7 +53,6 @@ Namespace Models.ViewModels
''' <summary>
''' PWDS
''' </summary>
<Required(AllowEmptyStrings:=False)>
<Display(Name:="passwowd")>
Public Property Passwowd() As String
Get
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@
<!-- Head 部の section -->
}

@Html.ValidationSummary()

@using (@Html.BeginForm())
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()

<table>
<tr>
<th>ユーザーID</th>
Expand All @@ -49,7 +49,12 @@
</tr>
<tr>
<td colspan="2" style="text-align:right;">
<input type="submit" value="ログイン" />
<input type="submit" name="normal" value="ログイン" style="width:150px" />
<td>
</tr>
<tr>
<td colspan="2" style="text-align:right;">
<input type="submit" name="external" value="外部ログイン" style="width:150px" />
<td>
</tr>
</table>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,9 @@
<location path="bundles"><system.web><authorization><allow users="*" /></authorization></system.web></location>
<!--エラー画面-->
<location path="Error"><system.web><authorization><allow users="*" /></authorization></system.web></location>

<!--外部ログイン-->
<location path="Home/OAuthAuthorizationCodeGrantClient"><system.web><authorization><allow users="*" /></authorization></system.web></location>

<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
Expand All @@ -203,6 +205,10 @@
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@
<package id="Microsoft.AspNet.WebPages.ja" version="3.2.3" targetFramework="net46" />
<package id="Microsoft.jQuery.Unobtrusive.Ajax" version="3.2.3" targetFramework="net46" />
<package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.2.3" targetFramework="net46" />
<package id="Microsoft.Owin" version="3.0.1" targetFramework="net46" />
<package id="Microsoft.Owin" version="3.1.0" targetFramework="net46" />
<package id="Microsoft.Owin.Host.SystemWeb" version="3.0.1" targetFramework="net46" />
<package id="Microsoft.Owin.Host.SystemWeb.ja" version="3.0.1" targetFramework="net46" />
<package id="Microsoft.Owin.ja" version="3.0.1" targetFramework="net46" />
<package id="Microsoft.Owin.ja" version="3.1.0" targetFramework="net46" />
<package id="Microsoft.Owin.Security" version="3.1.0" targetFramework="net46" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net46" />
<package id="Modernizr" version="2.8.3" targetFramework="net46" />
<package id="Newtonsoft.Json" version="10.0.3" targetFramework="net46" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
Imports System
Imports System.Text
Imports System.Collections.Generic
Imports System.Net.Http
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Web.Security

Imports Microsoft.Owin.Security.DataHandler.Encoder

Expand Down

0 comments on commit cbbaab9

Please sign in to comment.