首页 > 解决方案 > 在现有的 oauth2 实施中包含 Azure AD

问题描述

我们有一个带有 Oauth2 令牌生成和验证的 webApi。这是我在 Startup.Auth 文件上的代码:

public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    static Startup()
    {
        try
        {
            double AccessTokenExpireTimeSpan_SecurityValidation_Days = Convert.ToDouble(ConfigurationManager.AppSettings["AccessTokenExpireTimeSpan_SecurityValidation_Days"]);

            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/token"),
                Provider = new OAuthAppProvider(),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(AccessTokenExpireTimeSpan_SecurityValidation_Days),
                AllowInsecureHttp = true
            };
        }
        catch (Exception ex)
        {
            Tracking.InsertLog("Error generate manager for token", "Error generate manager for token - " + ex.Message);
        }
        
    }

并覆盖配置:

public void ConfigureAuth(IAppBuilder app)
    {
        try
        {
            app.UseOAuthBearerTokens(OAuthOptions);
        }
        catch (Exception ex)
        {
            Tracking.InsertLog("Error API Controller", "Error ConfigureAuth API - " + ex.Message);
        }

      
    }

我有我的拦截器类,我可以在其中验证我们是否可以生成新令牌:

public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        return Task.Factory.StartNew(() =>
        {
            var username = context.UserName;
            var password = context.Password;

            var userService = new UserRepository();

            APIAuth_User user = userService.GetUserByCredentials(username, password);
            if (user != null)
            {
                var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name, user.Username),
                    new Claim("UserID", user.Id)
                };
                ClaimsIdentity oAutIdentity = new ClaimsIdentity(claims, Startup.OAuthOptions.AuthenticationType);
                context.Validated(new AuthenticationTicket(oAutIdentity, new AuthenticationProperties() { }));
            }
            else
            {
                //AuthProviderLogger.WriteMessage(LogLevel.Error, "Exception", "Error validando el request" + " User:" + context.OwinContext.Request.User, context);
                Tracking.InsertLog("Error validating token", "Error validating token");
                context.SetError("invalid_grant", "Error");
            }
        });
    }

这个过程运行良好,没有问题,现在 webApp 需要允许使用 azure AD 进行身份验证,我知道 azure Active Directory 可以对请求进行身份验证和授权。如何将此 Azure AD 身份验证和授权过程加入我所拥有的?或者您是否建议仅使用 AZURE AD 进行身份验证并将令牌保留在我的应用程序中?

标签: asp.netazureoauth-2.0azure-active-directorybearer-token

解决方案


推荐阅读