.Net MVC和Angular 6中的Azure AD开放ID连接

时间:2018-10-24 08:05:19

标签: asp.net-mvc-4 azure-active-directory openid-connect azure-authentication angular-oauth2-oidc

我正在制作两个正在通过azure广告进行身份验证的应用程序,这两个应用程序都具有不同的客户端ID,并且在同一租户中,但是在这里我面临的问题是,这两个应用程序都只需单击一下即可登录,但注销行为不同,我必须分别注销两个应用程序

这是我的.Net MVC身份验证代码

public class Startup
{
    string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientId"];

    // RedirectUri is the URL where the user will be redirected to after they sign in.
    string redirectUri = System.Configuration.ConfigurationManager.AppSettings["ida:RedirectUri"];

    // Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
    static string tenant = System.Configuration.ConfigurationManager.AppSettings["ida:Tenant"];

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

    /// <summary>
    /// Configure OWIN to use OpenIdConnect 
    /// </summary>
    /// <param name="app"></param>
    public void Configuration(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
            // Sets the ClientId, authority, RedirectUri as obtained from web.config
            ClientId = clientId,
                Authority = authority,
                RedirectUri = redirectUri,
            // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
            PostLogoutRedirectUri = redirectUri,
                Scope = OpenIdConnectScope.OpenIdProfile,
            // ResponseType is set to request the id_token - which contains basic information about the signed-in user
            ResponseType = OpenIdConnectResponseType.IdToken,
            // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
            // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
            // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter 
            TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = false
                },
            // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
            Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = OnAuthenticationFailed
                }
            }
        );
    }

    /// <summary>
    /// Handle failed authentication requests by redirecting the user to the home page with an error in the query string
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
    {
        context.HandleResponse();
        context.Response.Redirect("/?errormessage=" + context.Exception.Message);
        return Task.FromResult(0);
    }
}

如果我要使用OpenIdConnectAuthenticationDefaults进行登录(如下所示),该怎么办?

app.SetDefaultSignInAsAuthenticationType(OpenIdConnectAuthenticationDefaults.AuthenticationType);

                var options = new OpenIdConnectAuthenticationOptions();
                options.Configuration = new OpenIdConnectConfiguration
                {                   
                    AuthorizationEndpoint = authority + "/authorize,
                    JwksUri = authority + "/.well-known/openid-configuration",
                    TokenEndpoint = authority + "/token",
                    UserInfoEndpoint = authority,
                    Issuer = authority,
                };
                app.UseOpenIdConnectAuthentication(options);

最后这是我的角度验证码

configureAuth() {
this._oauthService.configure(environment.config.oid_auth_config);
this._oauthService.setStorage(sessionStorage);

// // This method just tries to parse the token(s) within the url when
// // the auth-server redirects the user back to the web-app
// // It dosn't send the user the the login page
this._oauthService.tryLogin({
  onTokenReceived: context => {
    //
    // Output just for purpose of demonstration
    // Don't try this at home ... ;-)
    //
    alert('token recieved');
    console.log('logged in');
    console.log(context);
  }
})
  .catch(err => {
    this._sessionService.clearSession();
    location.href = 'http://localhost:54503/';
    console.error(err);
  })
  .then(() => {
    if (!this._oauthService.hasValidAccessToken()) {
      this._oauthService.initImplicitFlow();
    } else {
      this._authService.getFirstUser().subscribe((_user: any) => {
        this._sessionService.createSession(_user);
        this._authService.updateLoginStatus();
        this._router.navigate(['change-viewer']);
      });
    }
    // if (!this._oauthService.hasValidAccessToken()) {
    //   this._oauthService.initImplicitFlow();
    // }
  });

}

请帮助我解决这个问题。

0 个答案:

没有答案