asp.net and Identity Server 3 - asp.net

I am trying to authenticate my application with Identity Server Version 3. But, when I do, I get an error. Here is my code:
Startup.Auth.vb:
Partial Public Class Startup
Public Sub ConfigureAuth(app As IAppBuilder)
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
app.UseCookieAuthentication(New CookieAuthenticationOptions())
app.UseOpenIdConnectAuthentication(New OpenIdConnectAuthenticationOptions() With {
.ClientId = clientId,
.Authority = authority,
.RedirectUri = "https://localhost:44321/",
.Scope = OpenIdConnectScope.OpenIdProfile,
.ResponseType = OpenIdConnectResponseType.IdToken,
.TokenValidationParameters = New TokenValidationParameters() With {
.ValidateIssuer = False
},
.Notifications = New OpenIdConnectAuthenticationNotifications() With {
.AuthenticationFailed = AddressOf OnAuthenticationFailed
}
})
End Sub
Private Function OnAuthenticationFailed(ByVal context As AuthenticationFailedNotification(Of OpenIdConnectMessage, OpenIdConnectAuthenticationOptions)) As Task
context.HandleResponse()
context.Response.Redirect("/?errormessage=" & context.Exception.Message)
Return Task.FromResult(0)
End Function
end class
Login Page:
Protected Sub manuanSignIn(ByVal sender As Object, ByVal e As EventArgs) Handles manualLogin.Click
If (Not Request.IsAuthenticated) Then
Dim newAuth As AuthenticationProperties = New AuthenticationProperties()
newAuth.RedirectUri = "/"
HttpContext.Current.GetOwinContext().Authentication.Challenge(newAuth, OpenIdConnectAuthenticationDefaults.AuthenticationType)
End If
End Sub
The Error I get, when I attempt to login, is:
An existing connection was forcibly closed by the remote host
Anyone have ideas on what is causing this and how to fix it?

Adding this fixed the issue:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12

Related

ASP.net IdentiyServer 3 AuthorizationCodeReceived not firing

when a user authenticates with Identity Server 3, AuthorizationCodeReceived never fires. RedirectToIdentityProvider does get fired but thats it. I am trying to call a function that will get the users email or windows ID, and then add a custom claim. But without the AuthorizationCodeReceived method being called, I am not sure how to do that. Anyone have experience with this? Not sure if it matters, but my code is ASP.net windows form (not MVC)
Here is my code:
Public Sub ConfigureAuth(app As IAppBuilder)
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = New Dictionary(Of String, String)
app.UseCookieAuthentication(New CookieAuthenticationOptions() With {
.AuthenticationType = CookieAuthenticationDefaults.AuthenticationType
})
Dim OpenIdAuthOption = New OpenIdConnectAuthenticationOptions() With {
.Authority = "https://myidentityserver.azurewebsites.net/core/",
.ClientId = "adfafasfasdfa",
.RedirectUri = "https://localhost:44321/default.aspx/",
.ResponseType = ("access_token"),
.RequireHttpsMetadata = False,
.SignInAsAuthenticationType = "Cookies",
.Notifications = New OpenIdConnectAuthenticationNotifications() With {
.AuthorizationCodeReceived = Function(ctx)
Dim claimPrincipal As ClaimsPrincipal = ctx.AuthenticationTicket.Identity.Claims
TransformClaims(claimPrincipal)
Return Task.FromResult(0)
End Function,
.RedirectToIdentityProvider = Function(context)
RedirectLogin(context)
Return Task.FromResult(0)
End Function
}
}
app.UseOpenIdConnectAuthentication(OpenIdAuthOption)
End Sub

Translating C# to VB for OWIN Single Sign On

I am trying to use Single Sign On, using the OWIN libraries. The code that I have that works is in MVC C#. I am trying to translate it to Form website in VB. Here is the C# code, that works:
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
Wtrealm = realm,
MetadataAddress = metadata,
Notifications = new WsFederationAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("Home/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
}
}
});
}
And here is the VB.Net code:
Public Sub ConfigureAuth(app As IAppBuilder)
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
app.UseCookieAuthentication(New CookieAuthenticationOptions())
Dim authOption As WsFederationAuthenticationOptions = New WsFederationAuthenticationOptions()
app.UseWsFederationAuthentication(New WsFederationAuthenticationOptions() With {
.Wtrealm = realm,
.MetadataAddress = metadata
})
End Sub
I don't think I got the UseWsFederationAuthentication code properly translated, as I left out the Notifications stuff, as I could not figure out how to translate it. While no error is thrown, it does not properly authenticate. Can anyone tell me if there is an issue with the translation and how to fix it?
I can't really test it. However, try this:
Public Sub ConfigureAuth(app As IAppBuilder)
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
app.UseCookieAuthentication(New CookieAuthenticationOptions())
app.UseWsFederationAuthentication(New WsFederationAuthenticationOptions() With {
.Wtrealm = realm,
.MetadataAddress = metadata,
.Notifications = New WsFederationAuthenticationNotifications() With {
.AuthenticationFailed = Function(context)
context.HandleResponse()
context.Response.Redirect("Home/Error?message=" + context.Exception.Message)
Return Task.FromResult(0)
End Function
}
})
End Sub

401 Unauthorized - Google Drive API

I'm working with the Google APIs for the first time and I'm having problems trying to download files with the File object "downloadUrl" property. I'm currently using the "Service Account" option with the associated service account email and P12 certificate.
However, the URL returned "https://doc-08-68-docs.googleusercontent.com/docs/securesc/bteg36c1tifegg79l2ov17og25612tet/gk7kn52ahe4d0to7d6hte9f0f2hv47e4/1434132000000/11750183130219432819/11750183130219432819/0BziIKv2_NWCxc3RhcnRlcl9maWxl?e=download&gd=true" returns a 401 - Unauthorized response.
Imports System.Collections.Generic
Imports System.Security.Cryptography.X509Certificates
Imports System.IO
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Services
Imports Google.Apis.Auth.OAuth2
Namespace Videos
Partial Class List
Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Const serviceAccountEmail As String = "#developer.gserviceaccount.com"
Dim certificate = New X509Certificate2(
Server.MapPath("~/bin/key.p12"),
"notasecret",
X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable
)
Dim credential = New ServiceAccountCredential(
New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
.Scopes = New String() {DriveService.Scope.Drive}
}.FromCertificate(certificate)
)
Dim service = New DriveService(
New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "LexVid-VideoEncode/1.0"
}
)
UxFiles.DataSource = RetrieveAllFiles(service)
UxFiles.DataBind()
End Sub
Public Shared Function RetrieveAllFiles(service As DriveService) As List(Of Data.File)
Dim result = New List(Of Data.File)()
Dim request As FilesResource.ListRequest = service.Files.List()
Do
Try
Dim files As FileList = request.Execute()
result.AddRange(files.Items)
request.PageToken = files.NextPageToken
Catch e As Exception
request.PageToken = Nothing
End Try
Loop While (Not String.IsNullOrEmpty(request.PageToken))
Return result
End Function
Public Shared Function DownloadFile(ByVal service As DriveService, ByVal file As Data.File) As System.IO.Stream
If (Not String.IsNullOrEmpty(file.DownloadUrl)) Then
Try
Dim x = service.HttpClient.GetByteArrayAsync(file.DownloadUrl)
Dim result As [Byte]() = x.Result
Return New MemoryStream(result)
Catch e As Exception
Return Nothing
End Try
Else
Return Nothing
End If
End Function
Protected Sub UxFiles_ItemDataBound(ByVal sender As Object, ByVal e As ListViewItemEventArgs) Handles UxFiles.ItemDataBound
Dim dataItem = CType(e.Item.DataItem, Data.File)
Dim file = CType(e.Item.FindControl("UxFile"), HyperLink)
file.NavigateUrl = dataItem.DownloadUrl
file.Text = dataItem.Title
End Sub
End Class
End Namespace
I got this resolved through some trial and error. Although I'm building the links manually now, so the request token isn't even necessary anymore. However, I'm posting here in case anyone else is looking to resolve a similar issue.
Imports System.Collections.Generic
Imports System.Security.Cryptography.X509Certificates
Imports System.IO
Imports System.Threading
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Services
Imports Google.Apis.Auth.OAuth2
Namespace Videos
Partial Class List
Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Const serviceAccountEmail As String = "#developer.gserviceaccount.com"
Dim certificate = New X509Certificate2(
Server.MapPath("~/bin/key.p12"),
"notasecret",
X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable
)
Dim credential As ServiceAccountCredential = New ServiceAccountCredential(
New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
.Scopes = New String() {DriveService.Scope.Drive}
}.FromCertificate(certificate)
)
If (credential.RequestAccessTokenAsync(CancellationToken.None).Result) Then
Dim service = New DriveService(
New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "LexVid-VideoEncode/1.0"
}
)
UxFiles.DataSource = RetrieveAllFiles(service)
UxFiles.DataBind()
End If
End Sub
Public Shared Function RetrieveAllFiles(service As DriveService) As List(Of Data.File)
Dim result = New List(Of Data.File)()
Dim request As FilesResource.ListRequest = service.Files.List()
Do
Try
Const folderID As String = "0B5RLR6VRZsR4fkE5QjVFajg2dzZOMXZLYkNZUVdGbEtNODF0XzVBVGdjMW9ISDF5OE9kM0E"
request.Q = String.Format("'{0}' in parents and trashed=false", folderID)
Dim files As FileList = request.Execute()
result.AddRange(files.Items)
request.PageToken = files.NextPageToken
Catch e As Exception
request.PageToken = Nothing
End Try
Loop While (Not String.IsNullOrEmpty(request.PageToken))
Return result
End Function
Protected Sub UxFiles_ItemDataBound(ByVal sender As Object, ByVal e As ListViewItemEventArgs) Handles UxFiles.ItemDataBound
Dim dataItem = CType(e.Item.DataItem, Data.File)
Const folderID As String = "0B5RLR6VRZsR4fkE5QjVFajg2dzZOMXZLYkNZUVdGbEtNODF0XzVBVGdjMW9ISDF5OE9kM0E"
Dim file = CType(e.Item.FindControl("UxFile"), HyperLink)
file.NavigateUrl = String.Format("http://googledrive.com/host/{0}/{1}", folderID, dataItem.Title)
' Large files prompt for virus scan; no bypass available.
' file.NavigateUrl = String.Format("https://drive.google.com/uc?export=download&id={0}", dataItem.Id)
file.Text = dataItem.Title
End Sub
End Class
End Namespace

Using OWIN with VB

I am trying to set up some password policies, I managed to successfully do this in C#, but I need to convert the code into VB. There are two issues that I cannot figure out:
1) app.UseUserManagerFactory does not exist;
It states UseUserManagerFactory is not a member of Owin.IAppBuilder
2) The OnCreate attribute when instantiating the Provider is not being passed correctly
Public Sub ConfigureAuth(app As IAppBuilder)
'Configure the UserManager
app.UseUserManagerFactory(New IdentityFactoryOptions(Of ApplicationUserManager)() With { _
.DataProtectionProvider = app.GetDataProtectionProvider(), _
.Provider = New IdentityFactoryProvider(Of ApplicationUserManager)() With { _
.OnCreate = ApplicationUserManager.Create _
} _
})
Here is the Create function for the sake of completeness:
Public Shared Function Create(options As IdentityFactoryOptions(Of ApplicationUserManager))
Dim manager = New ApplicationUserManager(New ApplicationUserStore(New ApplicationDbContext()))
manager.UserValidator = New UserValidator(Of ApplicationUser)(manager) With {.AllowOnlyAlphanumericUserNames = False, .RequireUniqueEmail = True}
manager.PasswordValidator = New PasswordValidator()
Dim dataProtectionProvider = options.DataProtectionProvider
If (dataProtectionProvider IsNot Nothing) Then
' Do stuff
End If
Return manager
End Function
Any help would be appreciated, my VB skills coupled with the lack of documentation has me scratching my head.

configuration of asp.net mailmessage

Can someone help me pls. I am ready to deploy my web application. I have a contact form that i want users to send me a message. Ive created the smtp when i click on submit, i get the error message cannot be sent.
The application is still on my local machine maybe thats why. But i just want to know if this code is good for my form:
Imports System.Net.Mail
Partial Class contact
Inherits System.Web.UI.Page
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
If txtComments.Text.Length > 300 Then
args.IsValid = False
Else
args.IsValid = True
End If
End Sub
Protected Sub Wizard1_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles Wizard1.FinishButtonClick
SendMail(txtEmail.Text, txtComments.Text)
End Sub
Private Sub SendMail(ByVal from As String, ByVal body As String)
Dim mailServerName As String = "SMTP.relay-hosting.secureserver.net"
Dim message As MailMessage = New MailMessage(from, "collins#collinsegbe.com", "feedback", body)
Dim mailClient As SmtpClient = New SmtpClient
mailClient.Host = mailServerName
mailClient.Send(message)
message.Dispose()
End Sub
End Class
The error is indicated on this line of code: mailClient.Send(message)
I will appreciate help from anyone
protected void Button9_Click(object sender, EventArgs e)
{
{
var fromAddress = new MailAddress("rusty109.stud#gmail.com");
var toAddress = new MailAddress(TextBox13.Text);
const string fromPassword = "commando1";
string subject = TextBox14.Text;
string body = TextBox12.Text;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
}
}
my old code when i wanted to email, you can use the gmail account if you wish, nothing in it... was set up to use this code :)
using System.Net.Mail;
using System.Net;
You need to add the username and password for the SMTP server by setting the SmtpClient's Credential property to an instance of the NetworkCredential class.

Resources