ASP.net IdentiyServer 3 AuthorizationCodeReceived not firing - asp.net

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

Related

Asp.net OpenID Identity Server specifying scope causes error

I have an ASP.Net web form site that I want to authenticate with Identity Server 3. In the Identity Server app, I have a list of Scopes defined (one of which is "email"). But, when I run my code and attempt to authenticate, I get an error. If I remove the Scope property, it runs fine, but does not include the Scope fields I requested (only has generic claims). 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 = "Cookies"
})
Dim OpenIdAuthOption = New OpenIdConnectAuthenticationOptions() With {
.Authority = "https://myidentityserver.azurewebsites.net/core/",
.ClientId = "adfasdfafasdfasfasf",
.RedirectUri = "https://localhost:44321/default.aspx/",
.ResponseType = OpenIdConnectResponseType.IdTokenToken,
.SignInAsAuthenticationType = "Cookies",
.Scope = "email",
.Notifications = New OpenIdConnectAuthenticationNotifications() With {
.SecurityTokenReceived = Function(ctx)
Return Task.FromResult(0)
End Function,
.MessageReceived = Function(ctx)
Return Task.FromResult(0)
End Function,
.SecurityTokenValidated = Function(ctx)
Dim claimPrincipal = ctx.AuthenticationTicket.Identity
TransformClaims(claimPrincipal)
Return Task.FromResult(0)
End Function,
.AuthorizationCodeReceived = Function(ctx)
Return Task.FromResult(0)
End Function,
.RedirectToIdentityProvider = Function(context)
RedirectLogin(context)
Return Task.FromResult(0)
End Function
}
}
app.UseOpenIdConnectAuthentication(OpenIdAuthOption)
End Sub
The error I get is:
"OpenIdConnectMessage.Error was not null, indicating an error. Error:
'invalid_request'. Error_Description (may be empty): ''. Error_Uri
(may be empty): ''."
can anyone explain how I can get the scope values (like "email) from Identity Server?
In the scope of your client configuration add openid as well it is mandatory scope to be there if you use response type (IdTokenToken/CodeIdToken/CodeToken/CodeIdTokenToken)
You code should be like
Dim OpenIdAuthOption = New OpenIdConnectAuthenticationOptions() With {
.Authority = "https://myidentityserver.azurewebsites.net/core/",
.ClientId = "adfasdfafasdfasfasf",
.RedirectUri = "https://localhost:44321/default.aspx/",
.ResponseType = OpenIdConnectResponseType.IdTokenToken,
.SignInAsAuthenticationType = "Cookies",
.Scope = "openid email",
.Notifications = New OpenIdConnectAuthenticationNotifications() With {
.SecurityTokenReceived = Function(ctx)
Return Task.FromResult(0)
End Function,
.MessageReceived = Function(ctx)
Return Task.FromResult(0)
End Function,
.SecurityTokenValidated = Function(ctx)
Dim claimPrincipal = ctx.AuthenticationTicket.Identity
TransformClaims(claimPrincipal)
Return Task.FromResult(0)
End Function,
.AuthorizationCodeReceived = Function(ctx)
Return Task.FromResult(0)
End Function,
.RedirectToIdentityProvider = Function(context)
RedirectLogin(context)
Return Task.FromResult(0)
End Function
}
}

asp.net and Identity Server 3

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

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

AspNet Identity not using custom PasswordValidator code in IdentityConfig

I've been trying to work this problem out for over a week and can't seem to work out why it isn't working. I'm using ASP.NET Web Forms.
I have updated the following on my IdentityConfig.vb file to reduce the password requirement so it doesn't need any uppercase or numeric value:
manager.PasswordValidator = New PasswordValidator() With {
.RequiredLength = 4,
.RequireNonLetterOrDigit = False,
.RequireDigit = False,
.RequireLowercase = False,
.RequireUppercase = False
}
And this is the code I have to create a user
Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
Dim userName As String = TextBox1.Text
Dim manager = Context.GetOwinContext().GetUserManager(Of ApplicationUserManager)()
Dim signInManager = Context.GetOwinContext().Get(Of ApplicationSignInManager)()
Dim user = New ApplicationUser() With {.UserName = userName, .Email = userName}
Dim result = manager.Create(user, TextBox2.Text)
If result.Succeeded Then
signInManager.SignIn(user, isPersistent:=False, rememberBrowser:=False)
Response.Redirect("/member")
Else
Literal1.Text = result.Errors.FirstOrDefault()
End If
End Sub
But for some reason no matter what I try it's using the default password requirement and giving me the following validation messages when trying to create an account.
Passwords must be at least 6 characters. Passwords must have at least one non letter or digit character. Passwords must have at least one lowercase ('a'-'z'). Passwords must have at least one uppercase ('A'-'Z').
I have moved the register page out of the /account section.
Does anybody know what I've done wrong?
Edit 1: Reference to ApplicationUserManager in my IdentityConfig file
Public Class ApplicationUserManager
Inherits UserManager(Of ApplicationUser)
Public Sub New(store As IUserStore(Of ApplicationUser))
MyBase.New(store)
End Sub
Public Shared Function Create(options As IdentityFactoryOptions(Of ApplicationUserManager), context As IOwinContext) As ApplicationUserManager
Dim manager = New ApplicationUserManager(New UserStore(Of ApplicationUser)(context.[Get](Of ApplicationDbContext)()))
' Configure validation logic for usernames
manager.UserValidator = New UserValidator(Of ApplicationUser)(manager) With {
.AllowOnlyAlphanumericUserNames = False,
.RequireUniqueEmail = True
}
' Configure validation logic for passwords
manager.PasswordValidator = New PasswordValidator() With {
.RequiredLength = 4,
.RequireNonLetterOrDigit = False,
.RequireDigit = False,
.RequireLowercase = False,
.RequireUppercase = False
}
' Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user. '
' You can write your own provider and plug in here. '
manager.RegisterTwoFactorProvider("Phone Code", New PhoneNumberTokenProvider(Of ApplicationUser)() With {
.MessageFormat = "Your security code is {0}"
})
manager.RegisterTwoFactorProvider("Email Code", New EmailTokenProvider(Of ApplicationUser)() With {
.Subject = "Security Code",
.BodyFormat = "Your security code is {0}"
})
' Configure user lockout defaults '
manager.UserLockoutEnabledByDefault = True
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5)
manager.MaxFailedAccessAttemptsBeforeLockout = 5
manager.EmailService = New EmailService()
manager.SmsService = New SmsService()
Dim dataProtectionProvider = options.DataProtectionProvider
If dataProtectionProvider IsNot Nothing Then
manager.UserTokenProvider = New DataProtectorTokenProvider(Of ApplicationUser)(dataProtectionProvider.Create("ASP.NET Identity"))
End If
Return manager
End Function
End Class

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.

Resources