【问题标题】:OAuth bearer token validation by Authorize Attribute通过授权属性验证 OAuth 不记名令牌
【发布时间】:2016-12-04 06:24:37
【问题描述】:

我坚持使用 OAuth 令牌授权。我已经配置了 OAuth,并且我有自己的 OAuth 服务器提供程序。

配置代码:

    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AuthorizeEndpointPath = new PathString("/authorize"),
        AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
        Provider = new SimpleAuthorizationServerProvider()
    };

    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

服务器提供商:

 public class SimpleAuthorizationServerProvider : 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[] { "*" });

            using (AuthRepository _repo = new AuthRepository())
            {
                IdentityUser user = await _repo.FindUser(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);            
        }
    }

当我发送:grand_type=password, username=MyUserName, password=MyPassword 到 OAuth 令牌端点 "localhost/token" 时,它很好地创建了我的 OAuth 持有者令牌。但是从这里开始,我不知道如何使用这个生成的令牌,它的存储位置(如何获取它),以及如何使用 ASP.NET MVC 控制器上的[Authorize] 属性进行成功验证。我只是想使用我生成的令牌,当我从一个视图转到另一个视图时,它具有[Authorize] 属性,并成功通过它。我怎样才能做到这一点?

【问题讨论】:

  • 你可以为你生成的刷新令牌创建一个cookie,这可以跨多个视图访问,记住你的访问令牌有效期只有1小时,你需要每小时生成一个新的访问令牌

标签: asp.net asp.net-mvc oauth asp.net-mvc-5 bearer-token


【解决方案1】:

在“SimpleAuthorizationServerProvider”类中添加新的覆盖函数。

public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
            {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }

            return Task.FromResult<object>(null);
        }

然后就可以在json对象中获取token了。

【讨论】:

    【解决方案2】:

    实施以下工作流程:

    【讨论】:

      猜你喜欢
      • 2018-02-07
      • 2015-11-06
      • 1970-01-01
      • 2014-12-16
      • 2017-07-25
      • 2015-11-04
      • 2018-11-08
      • 2022-10-07
      • 2018-09-22
      相关资源
      最近更新 更多