如何从OAuth2中的MVC5获取客户端ID和客户端密钥?

时间:2017-08-07 12:15:31

标签: android asp.net-mvc oauth oauth-2.0

我正在我的MVC 5应用程序中实现OAuth2身份验证,因此我可以在我的Android应用程序中使用它。但我不确定这一切是怎么回事,因为我以前从未使用过Oauth2或任何令牌认证。

到目前为止,我在MVC中实现了以下代码:

OwinContextExtensions.cs

public static class OwinContextExtensions
{
    public static string GetUserId(this IOwinContext ctx)
    {
        var result = "-1";
        var claim = ctx.Authentication.User.Claims.FirstOrDefault(c => c.Type == "UserID");
        if (claim != null)
        {
            result = claim.Value;
        }
        return result;
    }
}

Startup.Auth.cs

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

    static Startup()
    {
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/token"),
            Provider = new OAuthAppProvider(),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(2),
            AllowInsecureHttp = true
        };
    }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseOAuthBearerTokens(OAuthOptions);
    }
}

OAuthAppProvider.cs

public class OAuthAppProvider : OAuthAuthorizationServerProvider
{
    private ProtokolEntities db = new ProtokolEntities();
    public IFormsAuthenticationService FormsService { get; set; }
    public IMembershipService MembershipService { get; set; }


    public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

        return Task.Factory.StartNew(() =>
        {
            var username = context.UserName;
            var password = context.Password;


            var userID = db.aspnet_Users.Where(x => x.UserName == username).SingleOrDefault().UserId.ToString();

            if (MembershipService.ValidateUser(username, password))
            {
                var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name, username),
                    new Claim("UserID", userID)
                };

                ClaimsIdentity oAutIdentity = new ClaimsIdentity(claims, Startup.OAuthOptions.AuthenticationType);
                context.Validated(new AuthenticationTicket(oAutIdentity, new AuthenticationProperties() { }));
            }
            else
            {
                context.SetError("invalid_grant", "Error");
            }
        });
    }

    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        if (context.ClientId == null)
        {
            context.Validated();
        }
        return Task.FromResult<object>(null);
    }
}

Startup.cs.cs

[assembly: OwinStartup(typeof(PageOffice.Startup))]
namespace PageOffice
{

    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();

            ConfigureAuth(app);
        }
    }
}

当我打开Postman并在http://localhost:1076/token上使用POST方法时,我打开Body - &gt;生和写

  

grant_type =密码&安培;密码=输入mypassword&安培;用户名=名为myUsername

之后我得到了这个结果:

{
    "access_token": "QmmWSh4OZPfC8uv-jyzFzZx1KP05T8b09QlPP3Cy-_Zr9qvWtzWpxNTXOhc4U387N6VHNCnIPklgTEk8CISMyXlcsWAz7MxlRN8qI_Ajg8gjEphHUS1SrO0uDRG2XRqtX1gvTVupym_1xtsdjlwj2VXoc6ySvR0ihb2YjuXnSd4CNgKKaMBQLb1w8P1XB13jc4Pc5tump4-Y4dYn3A5hpvtc9fqpgVAUjZFdiJ_HXMiIpgmqdIFim0Ty8oRZolzpm3RSMPRV6ZIpZBqHG1A2kcdWN-52ZkHuL4_7U743vW0",
    "token_type": "bearer",
    "expires_in": 172799
}

如何找到这个&#34; 客户ID &#34;和&#34; 客户端秘密&#34; paremeters? 另外,我真的不明白如何在android中使用这个access_token,this教程的解释是否足够?

感谢阅读并抱歉这么多代码:)

1 个答案:

答案 0 :(得分:0)

有关于OAuth2 for native applications的RFC。它建议使用授权代码授权流程,但没有客户端机密,因为您无法在应用程序二进制文件中保密。

您正在使用的资源所有者密码凭据流(请参阅OAuth2 RFC)应仅在资源所有者完全信任该应用程序的情况下使用,因为应用程序必须知道其密码。

当您在OAuth2提供商处注册应用程序(客户端)时,您将获得或指定客户端ID和密码。

您链接的教程似乎讨论了OAuth版本1,而不是2。