Skip to content

Instantly share code, notes, and snippets.

@cmw2
Created February 15, 2019 20:43
Show Gist options
  • Save cmw2/6a537a4bfa6636f8221a7fc572197988 to your computer and use it in GitHub Desktop.
Save cmw2/6a537a4bfa6636f8221a7fc572197988 to your computer and use it in GitHub Desktop.
OWIN Startup class to use AAD.
using Owin;
namespace WindowsAuthAppToAADDemo
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
using Microsoft.Owin.Extensions;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
using System;
using System.Configuration;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace WindowsAuthAppToAADDemo
{
public partial class Startup
{
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string aadInstance = EnsureTrailingSlash(ConfigurationManager.AppSettings["ida:AADInstance"]);
private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
string authority = aadInstance + tenantId;
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthenticationFailed = (context) =>
{
return System.Threading.Tasks.Task.FromResult(0);
},
SecurityTokenValidated = (context) =>
{
var claims = context.AuthenticationTicket.Identity.Claims;
var groups = from c in claims
where c.Type == "groups"
select c;
foreach (var group in groups)
{
context.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Role, group.Value));
}
return Task.FromResult(0);
}
}
}
);
// This makes any middleware defined above this line run before the Authorization rule is applied in web.config
app.UseStageMarker(PipelineStage.Authenticate);
}
private static string EnsureTrailingSlash(string value)
{
if (value == null)
{
value = string.Empty;
}
if (!value.EndsWith("/", StringComparison.Ordinal))
{
return value + "/";
}
return value;
}
}
}
<appSettings>
<add key="ida:ClientId" value="tbd" />
<add key="ida:AADInstance" value="https://login.microsoftonline.com/" />
<add key="ida:Domain" value="tbd" />
<add key="ida:TenantId" value="tbd" />
<add key="ida:PostLogoutRedirectUri" value="Your local dev URL from enabling SSL" />
</appSettings>
...
<authentication mode="None" />
...
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
@Sijoykr
Copy link

Sijoykr commented Aug 16, 2019

Can you please let me know how to get Token after authentication.

@sjpmax
Copy link

sjpmax commented Nov 25, 2020

For future people, I put this into my onload to get the authentication window to show up:
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties{ RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}

I got it from https://docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-asp-webapp

@JennieHarden
Copy link

When you say you added this to the onload -where exactly do you mean. Do you mean the Page_Load ?

@sjpmax
Copy link

sjpmax commented Dec 4, 2020

Actually, I put it in a button! I put it there because I'm testing out functionality. but yeah a page_load is what I meant.

@charles-richardson
Copy link

  1. Should both classes be named Startup? Or should the main one be named StartupAuth?

@sjpmax
Copy link

sjpmax commented Feb 24, 2021

Hey Charles, I actually was able to get away with not using StartupAuth at all. This is all the code I used for it. Make sure your Azure portal is configured with the proper variables and permissions. Our project is legacy and in VB, so if you want c# run it through this https://converter.telerik.com/

Startup.vb

Imports System
Imports System.Threading.Tasks
Imports Microsoft.Owin
Imports Owin
Imports Microsoft.IdentityModel.Protocols.OpenIdConnect
Imports Microsoft.IdentityModel.Tokens
Imports Microsoft.Owin.Security
Imports Microsoft.Owin.Security.Cookies
Imports Microsoft.Owin.Security.OpenIdConnect
Imports Microsoft.Owin.Security.Notifications
Imports BusinessLayer

Namespace AppModelv2_WebApp_OpenIDConnect_DotNet
    Public Class Startup
        Private clientId As String = System.Configuration.ConfigurationManager.AppSettings("ClientId")
        Private redirectUri As String = AppConfigLogic.GetAppConfigValueByKey("ADLoginRedirectURI")
        Shared tenant As String = System.Configuration.ConfigurationManager.AppSettings("Tenant")
        Private authority As String = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings("Authority"), tenant)

        Public Sub Configuration(ByVal app As IAppBuilder)
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
            app.UseCookieAuthentication(New CookieAuthenticationOptions With {
                .CookieName = "someCookie",
                .ExpireTimeSpan = TimeSpan.FromMinutes(5)
            })
            app.UseOpenIdConnectAuthentication(New OpenIdConnectAuthenticationOptions With {
                .ClientId = clientId,
                .Authority = authority,
                .RedirectUri = redirectUri,
                .PostLogoutRedirectUri = redirectUri,
                .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
End Namespace

AssemblyInfo.vb

(other assembly info before this)
<Assembly: OwinStartup(GetType(AppModelv2_WebApp_OpenIDConnect_DotNet.Startup))>

Login.vb in the button onclick

    Protected Sub adAuth_Click(sender As Object, e As EventArgs)
        HttpContextExtensions.GetOwinContext(Context).Authentication.Challenge(New AuthenticationProperties With {
                   .RedirectUri = "/"
               }, OpenIdConnectAuthenticationDefaults.AuthenticationType)

    End Sub

@charles-richardson
Copy link

Great, thanks! Much appreciated.

@ansh1february
Copy link

Hey ! Can you please tell me what exactly it is that you mean by authority in app settings in the following statement-

Private authority As String = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings("Authority"), tenant)

Thanks

@sjpmax
Copy link

sjpmax commented Apr 23, 2021

Did a quick google because i don't remember this stuff lol.
https://stackoverflow.com/questions/56021816/azure-active-directory-authentication-single-tenant

    // Authority is the URL for authority, composed by Azure Active Directory endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com)
    string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);

Being a good programmer equates to being a good googler IMO

@kkilton
Copy link

kkilton commented Aug 29, 2023

I had to add this to my web.config appsettings which was omitted from the instructions
<add key="owin:appStartup" value="AAD_POC_WebForms.Startup" />

@sam-mdenn
Copy link

Is there a way to get this with work with a Web Site, instead of a Web Application Project?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment