【问题标题】:asp.net OAuth token error 401: unauthorizedasp.net OAuth 令牌错误 401:未经授权
【发布时间】:2023-03-03 14:07:01
【问题描述】:

我正在使用 ASP.NET Web API (C#)。我尝试实现基于令牌的身份验证。这是我的 Startup.Auth 类

    public static Startup()
    {
        PublicClientId = "self";

        UserManagerFactory = () => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),

            AccessTokenExpireTimeSpan = TimeSpan.FromHours(2),
            AllowInsecureHttp = true
        };

     }

    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public static Func<UserManager<ApplicationUser>> UserManagerFactory { get; set; }

    public static string PublicClientId { get; private set; }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);
    /* login with third party login providers......*/
    }

我还有另一种发行代币的方法

    public async Task<IHttpActionResult> Login(LoginModel model)
    /* some stuff here...*/
    if (hasRegistered)
            {
                identity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);
                IEnumerable<Claim> claims = externalLogin.GetClaims();
                identity.AddClaims(claims);
                Authentication.SignIn(identity);
            }

        AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
        var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;
        ticket.Properties.IssuedUtc = currentUtc;
        ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromHours(2));
        var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);


        // Create the response building a JSON object that mimics exactly the one issued by the default /Token endpoint
        JObject token = new JObject(
            new JProperty("userName", user.UserName),
            new JProperty("id", user.Id),
            new JProperty("access_token", accessToken),
            new JProperty("token_type", "bearer"),
            new JProperty("expires_in", TimeSpan.FromHours(2).TotalSeconds.ToString()),
            new JProperty(".issued", currentUtc.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'")),
            new JProperty(".expires", currentUtc.Add(TimeSpan.FromHours(2)).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"))
        );
        return Ok(token);
    }

这两种方法都有效。但是,如果我将 [Authorize] 放入控制器并使用使用第二种方法(登录)发布的令牌,我总是会收到“此请求的授权已被拒绝”错误。为什么会这样?我究竟做错了什么?

【问题讨论】:

    标签: asp.net asp.net-web-api access-token unauthorized


    【解决方案1】:

    您似乎在身份验证后成功取回了令牌。要访问资源(具有授权属性的 apicontroller),您需要在 Authorization 标头中传递不记名令牌(以“Bearer”为前缀)。示例:'Bearer [Tokenstring]'。

    您可以通过在您喜欢的浏览器上下载一个 restclient(rest 控制台、邮递员等)工具来测试这一点。尝试正常的 GET 请求并将“Bearer [token]”放在授权标头字段中。我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-11-16
      • 2016-05-17
      • 1970-01-01
      • 1970-01-01
      • 2012-04-08
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多