Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to manage user Information by Azure AD in Windows Azure SDK .NET Development

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article shows you how Azure AD manages user information in Windows Azure SDK .NET development. The content is concise and easy to understand. It will definitely make your eyes shine. I hope you can get something through the detailed introduction of this article.

Use Azure AD for authentication

The reason why we started with Azure AD is that basically all of our applications need security management. Azure Active Directory (Azure AD) simplifies the authentication of developers by providing identity as a service, supporting industry standard protocols such as OAuth 2.0 and OpenID Connect, and providing open source libraries for different platforms to help you start coding quickly.

Azure Active Directory (Azure AD) provides an easy way for enterprises to manage identity and access both in the cloud and locally. Your users can use the same work or school account to single sign on to any cloud and local Web application. Your users can use their favorite devices, including iOS, Mac OS X, Android and Windows. Your organization can use integrated multifactor authentication to protect sensitive data and applications locally and in the cloud, thereby securing local and remote access.

And Azure Active Directory (AD) provides core directory and identity management capabilities behind most Microsoft cloud services. These services include, but are not limited to:

Azure

Microsoft Office 365

Microsoft Dynamics CRM Online

Windows Intune

First, you need to understand several concepts when using Azure AD (1) Azure AD directory

When you sign up for the Microsoft cloud service, you will get an Azure AD directory. You can create more directories as needed. For example, you can leave the first directory as a production directory, and then create another directory for testing or transition.

(II) Azure AD tenants

In a cloud-enabled workspace, a tenant can be defined as a client or organization that owns and manages a specific instance of the cloud service. Tenants use the identification platform provided by Microsoft Azure, which is just a dedicated instance of Azure Active Directory (Azure AD) that your organization receives and owns when registering for Microsoft cloud services such as Azure or Office 365. Each Azure AD directory is unique and independent of other Azure AD directories. Just as a corporate office building is a security asset unique to your organization, the Azure AD catalog is designed to be a security asset for your organization only. The Azure AD architecture isolates customer data and identity information and avoids mixed storage. This means that users and administrators of one Azure AD directory cannot accidentally or maliciously access data in another directory.

I now have two Azure AD directories, that is, two Azure AD tenants.

Now, when you register for Azure, a directory will be automatically created and your subscription will be associated with that directory. There is no charge for using Azure AD. Catalogs are free resources. There is also a paid Azure Active Directory Premium level that provides additional features such as corporate branding and self-service password reset. Interestingly, the Azure AD directory can be changed after it has been created, so you don't have to hesitate to name it for the first time.

Second, authentication development

In our case, we identified the user through the Web application.

Azure AD is an identity provider that validates the identity of users and applications that exist in an organization's directory and eventually issues security tokens when those users and applications are successfully authenticated.

Applications that want to outsource authentication to Azure AD must register in Azure AD, and Azure AD will register in the directory and uniquely identify the application.

After the user is authenticated, the application must authenticate the user's security token to ensure that the authentication is successful for the target party.

The request and response flow of the authentication process is determined by the authentication protocol used (such as OAuth 2.0, OpenID Connect, WS-Federation, or SAML 2.0)

In this chapter, we will make a simple introduction to the development of Azure AD, including authentication and login, storage of basic identity information. In order to complete the application development of Azure AD, some work needs to be done in the Azure portal and the development environment.

Azure AD development part

First, we need to introduce the following component libraries

Microsoft.IdentityModel.Clients.ActiveDirectory

Microsoft.IdentityModel.Protocol.Extensions

Microsoft.Owin

Microsoft.Owin.Host.SystemWeb

Microsoft.Owin.Security

Microsoft.Owin.Security.Cookies

Microsoft.Owin.Security.OpenIdConnect

Microsoft.Web.Infrastructure

Microsoft.WindowsAzure.ConfigurationManager.

System.IdentityModel.Tokens.Jwt

Secondly, we need to add the following configuration node to the appSettings section of the Web.config file

Note that since we are using the century interconnected version, the Url of ida:AADInstance and ida:GraphUrl will be fixed as https://login.chinacloudapi.cn/{0} and https://graph.chinacloudapi.cn. Additional configuration values are explained in the Azure AD Portal section.

Then we need to write the AuthenticationHelper class to assist us with the basic processing of authorization. AuthenticationHelper has two parts. The first part is to read the information about Azure AD configured in the appSettings section of the Web.config file through static fields.

Public static readonly string Tenant = CloudConfigurationManager.GetSetting ("ida:Tenant")

Public static readonly string TenantId = CloudConfigurationManager.GetSetting ("ida:TenantId")

Public static readonly string LoginUrl = CloudConfigurationManager.GetSetting ("ida:AADInstance")

Public static readonly string GraphUrl = CloudConfigurationManager.GetSetting ("ida:GraphUrl")

Public static readonly string AppKey = CloudConfigurationManager.GetSetting ("ida:AppKey")

Public static readonly string AuthorityUrl = String.Format (CultureInfo.InvariantCulture, LoginUrl, TenantId)

Public static readonly string AuthString = CloudConfigurationManager.GetSetting ("ida:Auth") + CloudConfigurationManager.GetSetting ("ida:Tenant")

Public static readonly string ClaimsSchemas = "http://schemas.microsoft.com/identity/claims/objectidentifier";

Public static readonly string ClientId = CloudConfigurationManager.GetSetting ("ida:ClientId")

Public static readonly string ClientSecret = CloudConfigurationManager.GetSetting ("ida:ClientSecret")

Public static readonly string PostLogoutRedirectUri = CloudConfigurationManager.GetSetting ("ida:PostLogoutRedirectUri")

You have noticed that the above code does not use our traditional WebConfigurationManager class when reading the configuration, but uses the new CloudConfigurationManager class added by Azure, which is a static class for accessing Microsoft Azure configuration settings, which can be read from the corresponding configuration store of the platform on which the application is running. .net applications running in Microsoft Azure external environments typically store configuration settings in web.config or app.config files. Regardless of the environment in which the code is running, you can use the CloudConfigurationManager class to read the settings from the appropriate configuration file.

Then add a method AcquireTokenAsync to the AuthenticationHelper, which returns the current user credentials and throws an exception if there are no credentials.

Public static string Token

Public static async Task AcquireTokenAsync ()

{

If (Token = = null | | Token.IsEmpty ())

{

Throw new Exception ("Authorization Required.")

}

Return Token

}

Then we add the GetActiveDirectoryClient method to get the client object reference to Azure AD.

Public static ActiveDirectoryClient GetActiveDirectoryClient ()

{

Uri baseServiceUri = new Uri (GraphUrl)

ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient (new Uri (baseServiceUri, TenantId), async () = > await AcquireTokenAsync ())

Return activeDirectoryClient

}

AuthenticationHelper is done here, and we set up a controller AzureActiveDirectoryController that will contain the following methods to use the AuthenticationHelper class.

SignIn

SignOut

SignIn login

The code is very simple. OpenID is used to query the identity in the current context.

Public void SignIn ()

{

If (! Request.IsAuthenticated)

{

HttpContext.GetOwinContext ()

.Authentication .Challenge (new AuthenticationProperties {RedirectUri = "/"}

OpenIdConnectAuthenticationDefaults.AuthenticationType)

}

}

SignOut logout

The same code is simple and clear vm

Public void SignOut ()

{

String userObjectID = ClaimsPrincipal.Current.FindFirst (AuthenticationHelper.ClaimsSchemas) .Value

Var authContext = new AuthenticationContext (AuthenticationHelper.AuthorityUrl, new NaiveSessionCache (userObjectID))

AuthContext.TokenCache.Clear ()

AuthenticationHelper.Token = null

HttpContext.GetOwinContext () .Authentication.SignOut (OpenIdConnectAuthenticationDefaults.AuthenticationType CookieAuthenticationDefaults.AuthenticationType)

}

Well, now that the login and logout code is complete, we can try to download our MVC Web APP execution experience. In the architecture built by MVC itself, we can follow View\ Shared\ _ LoginPartial.cshtml to find the general login and logout View interface, and then modify the code to

@ if (Request.IsAuthenticated)

{

< text>

< ul class="nav navbar-nav navbar-right">

< li class="navbar-text">

Hello, @ User.Identity.Name!

< li>

@ Html.ActionLink ("Sign out", "SignOut", "AzureActiveDirectory")

< /li>

< /ul>

< /text>

}

Else

{

< li>

@ Html.ActionLink ("Sign in", "SignIn", "AzureActiveDirectory", routeValues: null, htmlAttributes: new {id = "loginLink"})

< /ul>

}

The above code completes the login through an if and then the Sign out link appears and the logout status is Sign in link. Then add this _ LoginPartial.cshtml to View\ Shared\ _ LoginPartial.cshtml and we have the login and logout link in the main template. My modifications to _ LoginPartial.cshtml here are as follows

@ Html.ActionLink ("Home Page", "Index", "Home")

@ Html.ActionLink ("about", "About", "Home")

@ Html.ActionLink ("contact details", "Contact", "Home")

@ Html.Partial ("_ LoginPartial")

Now that we have executed the code, the default page we see is

Click on the Sign in link to jump to the Microsoft login interface

After clicking on the account

After entering the correct password, we will jump back to the default home page of our application and obviously find that we have logged in with the correct identity.

The above is how Azure AD manages user information in Windows Azure SDK. Net development. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report