Owin Bearer令牌认证+授权控制器

Col*_*lin 20 c# authentication token owin

我正在尝试使用Bearer令牌和owin进行身份验证.

我可以使用授权类型发出令牌passwordGrantResourceOwnerCredentialsAuthorizationServerProvider.cs中重写.

但我无法使用该Authorize属性访问控制器方法.

这是我的代码:

Startup.cs

public class Startup
{
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    // normal
    public Startup() : this(false) { }

    // testing
    public Startup(bool isDev)
    {
        // add settings
        Settings.Configure(isDev);

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/Token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new AuthorizationServerProvider()
        };
    }

    public void Configuration(IAppBuilder app)
    {
        // Configure the db context, user manager and role manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
        app.CreatePerOwinContext<LoanManager>(BaseManager.Create);

        var config = new HttpConfiguration();
        WebApiConfig.Register(config);
        app.UseWebApi(config);

        // token generation
        app.UseOAuthAuthorizationServer(OAuthOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
        {
            AuthenticationType = "Bearer",
            AuthenticationMode = AuthenticationMode.Active
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

AuthorizationServerProvider.cs

public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);
    }
}
Run Code Online (Sandbox Code Playgroud)

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        // enable CORS for all hosts, headers and methods
        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

        config.Routes.MapHttpRoute(
            name: "optional params",
            routeTemplate: "api/{controller}"
        );

        config.Routes.MapHttpRoute(
            name: "Default",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // stop cookie auth
        config.SuppressDefaultHostAuthentication();
        // add token bearer auth
        config.Filters.Add(new MyAuthenticationFilter());
        //config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthOptions.AuthenticationType));

        config.Filters.Add(new ValidateModelAttribute());

        if (Settings.IsDev == false)
        {
            config.Filters.Add(new AuthorizeAttribute());
        }

        // make properties on model camelCased
        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }
Run Code Online (Sandbox Code Playgroud)

MyAuthenticationFilter.cs用于调试目的的自定义过滤器

public class MyAuthenticationFilter : ActionFilterAttribute, IAuthenticationFilter
{
    public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        if (context.Principal != null && context.Principal.Identity.IsAuthenticated)
        {
        }

        return Task.FromResult(0);
    }

    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        throw new System.NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我AuthenticateAsyncMyAuthenticationFilter.cs中调试,我会在请求中看到标题:

Authorization: Bearer AQAAANCMnd8BFdERjHoAwE_Cl...
Run Code Online (Sandbox Code Playgroud)

但身份声明是空的,context.Principal.Identity.IsAuthenticated是假的.

有任何想法吗?

Sha*_*adi 7

我正在寻找相同的解决方案,我花了一个星期左右的时间,我离开了它.今天我开始再次搜索,我找到了你的问题,我希望能找到答案.

所以我花了一整天的时间除了尝试所有可能的解决方案,将建议相互融合之外,我找到了一些解决方案,但他们是长期的解决方法,这里的长话短说是我发现的.

首先,如果您需要使用自定义第三方身份提供者令牌对Web站点进行身份验证,则需要使用相同的machineKey,或者您需要将它们都放在同一台服务器上.

您需要将machineKey添加到该system.web部分,如下所示:

Web.Config中

<system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <machineKey validationKey="*****" decryptionKey="***" validation="SHA1" decryption="AES" />
</system.web>
Run Code Online (Sandbox Code Playgroud)

这是一个生成新machineKey的链接:

现在您需要移动到Startup.Auth.cs文件,您可以在其中找到Startup.cs分部类,您需要定义OAuthBearerOptions

Startup.Auth.cs

public partial class Startup
{
    public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }
    ...

    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per    request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
        app.UseOAuthBearerAuthentication(OAuthBearerOptions);
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

使用以下内容替换AccountController中的Login操作:

AccountController.cs

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    /*This will depend totally on how you will get access to the identity provider and get your token, this is just a sample of how it would be done*/
    /*Get Access Token Start*/
    HttpClient httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri("https://youridentityproviderbaseurl");
    var postData = new List<KeyValuePair<string, string>>();
    postData.Add(new KeyValuePair<string, string>("UserName", model.Email));
    postData.Add(new KeyValuePair<string, string>("Password", model.Password));
    HttpContent content = new FormUrlEncodedContent(postData);


    HttpResponseMessage response = await httpClient.PostAsync("yourloginapi", content);
    response.EnsureSuccessStatusCode();
    string AccessToken = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync());
    /*Get Access Token End*/

    If(!string.IsNullOrEmpty(AccessToken))
    {
            var ticket = Startup.OAuthBearerOptions.AccessTokenFormat.Unprotect(AccessToken);
            var id = new ClaimsIdentity(ticket.Identity.Claims, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, id);

            return RedirectToLocal(returnUrl);

   }

   ModelState.AddModelError("Error", "Invalid Authentication");
   return View();
}
Run Code Online (Sandbox Code Playgroud)

您需要做的最后一件事是将这行代码放在Global.asax.cs中以避免Anti Forgery异常:

的Global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

        …
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这对你有用.


tea*_*ime 0

我不确定这是否有帮助,但我在使用依赖项注入时遇到了 IsAuthenticated 返回 false 的问题(请参阅此处的SO 问题),它看起来是因为在注入时 Owin 管道尚未设置它。

我通过惰性注入校长克服了这个问题。不管怎样,我整理了一个非常基本的应用程序(在上面链接到)来演示问题,但它可能会帮助您,因为它显示了在属性中设置的主体以及不记名身份验证的使用。