将承载令牌身份验证添加到MVC 4项目中的WebAPI控制器

时间:2019-04-10 15:26:49

标签: asp.net-mvc asp.net-mvc-4 authentication asp.net-web-api bearer-token

我已成功将webapi控制器添加到和MVC4项目中。我可以调用它并返回数据。然后,我向控制器添加了[Authorize]属性以保护它。

它与Cookie身份验证一起使用,但不与承载令牌身份验证一起使用。奇怪的是,MVC控制器可以同时使用。这是我的创业公司所拥有的,我都注册了。

using (IDependencyScope scope = GlobalConfiguration.Configuration.DependencyResolver.BeginScope())
            {
                app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    CookieName = "mycookie.myname",
                    CookieHttpOnly = false
                });

                IOpenIdSettingProvider openIdSettingProvider = scope.GetService<IOpenIdSettingProvider>();

                OpenIdConnectAuthenticationDefinition openIdConnectAuthenticationDefinition = openIdSettingProvider.Resolve().FirstOrDefault();

                app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
                {
                    AllowedAudiences = new List<string>
                    {
                        openIdConnectAuthenticationDefinition.Audience
                    },
                    AuthenticationMode = AuthenticationMode.Active,
                    IssuerSecurityTokenProviders = new List<IIssuerSecurityTokenProvider>
                    {
                        new StaticSecurityTokenProvider(openIdConnectAuthenticationDefinition.Issuer, openIdConnectAuthenticationDefinition.SigningTokens)
                    }
                });

                IConfigurationSource configurationSource = scope.GetService<IConfigurationSource>();

                app.UseOpenIdConnectAuthentication(
                    new OpenIdConnectAuthenticationOptions
                    {
                        ClientId = configurationSource.GetSetting("ClientId"),
                        Authority = configurationSource.GetSetting("BaseAuthorityUri"),
                        Notifications = new OpenIdConnectAuthenticationNotifications
                        {
                            RedirectToIdentityProvider = context =>
                            {
                                context.ProtocolMessage.Prompt = "login";
                                context.ProtocolMessage.RedirectUri = context.Request.Uri.ToString();
                                return Task.CompletedTask;
                            }
                        }
                    });
            }
        }

0 个答案:

没有答案