使用asp.net Identity进行授权的Azure AD身份验证
本文关键字:Azure AD 身份验证 授权 asp net Identity 使用 | 更新日期: 2023-09-27 18:03:48
我试着在互联网上寻找,但无法看到我如何才能实现我被要求的。这是我的企业应用程序,它使用Asp.net身份为基于表单的身份验证。我扩展了用户和角色以及组,以便在代码中提供授权。(注意:不使用任何组/角色指令)。
现在我被要求考虑修改代码以适应Azure Active Directory身份验证的可能性。我试着阅读如何注册应用程序,将用户发送到Azure站点进行身份验证,获取令牌等。然而,我被困在"之后怎么办?"我已经通过身份验证的用户如何使用我现有的Asp.net身份模型,其中用户存储在sql数据库中。如何使用此令牌来关联现有用户。
此外,当我更改我的项目以允许Azure AD时,它会删除asp.net。身份包与Azure AD不兼容!!
我甚至尝试手动保持两个包并排,我要指出用户被发送到Azure上进行身份验证,转移回主页,并再次登录Azure AD在永无止境的循环。
总结问题,如何从AAD对用户进行身份验证并继续使用现有的角色和组授权。
编辑:我尝试创建单独的web服务,它将验证用户并发送JWT令牌。如果我直接在浏览器上调用它,那么,当我试图从我的web应用程序调用此服务时,我得到奇怪的错误
Application with identifier 'a2d2---------------' was not found in the directory azurewebsites.net
奇怪的是,这里的目录名称是'azurewebsites.net',而不是我使用的默认目录。
下面是抛出错误
的代码public async Task<ActionResult> Login(string returnUrl)
{
try
{
// get the access token
AuthenticationContext authContext = new AuthenticationContext(authority, new TokenCache());
var clientCredential = new ClientCredential(clientId, password);
//Error on below line
AuthenticationResult result = await authContext.AcquireTokenAsync(resourceId, clientCredential);
// give it to the server to get a JWT
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
......
try this:
var client = new RestClient("https://login.microsoftonline.com/{tenant-
Id}/oauth2/v2.0/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("grant_type", "password");
request.AddParameter("application/x-www-form-urlencoded",
"grant_type=password&client_id={client-Id}&client_secret={client-
secret}&scope={scopeurl}&userName={username}&password={password}",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var json = response.Content;
var JSONObject = JObject.Parse(json);
var token = (string)JSONObject["access_token"];
我有一个类似的问题,所以我创建了一个Office 365自己的安全插件。我在github上分享了代码。它基于codeplex的katana项目。
您可以在https://github.com/chadwjames/wakizashi找到源代码。
你需要在这里注册你的申请。注册应用程序时,将回调uri设置为https://yourdomain/signin-office365
应用程序ID是您的客户端ID,密码是您的客户端秘密。
一旦你注册了它,你就可以修改Startup.Auth.cs,并在ConfigureAuth方法中添加如下内容:
//setup office 365
var office365Options = new Office365AuthenticationOptions
{
ClientId = ConfigurationManager.AppSettings["ada:ClientId"],
ClientSecret = ConfigurationManager.AppSettings["ada:ClientSecret"],
Provider = new Office365AuthenticationProvider
{
OnAuthenticated = async context =>
{
await
Task.Run(
() => context.Identity.AddClaim(new Claim("Office365AccessToken", context.AccessToken)));
}
},
SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
};
office365Options.Scope.Add("offline_access");
app.UseOffice365Authentication(office365Options);
当我有更多的时间,我希望创建一个nuget包。