如何在ASp.net Core中使用/实现OAuth2和Owin?

时间:2017-02-02 09:47:18

标签: asp.net-core asp.net-core-mvc

您好我是整个网络开发的初学者,我有一个创建API的任务,无论是好还是坏,我都选择Asp.Core来做。

api将移动客户端与CRM系统连接,并且有一个AD系统(Not azure,也不是Windows AD),它被称为NetIQ。对API的任何请求必须来自Net IQ认证的用户,然后API才会向客户端发出令牌。

无论如何我想要有一种认证机制,我被告知OWIN可以处理OAUTh2的东西。

我有我需要的确切代码,但它与MVC 5相同。

有人可以帮我将这个东西迁移到MVC核心吗?

我搜索了很长时间,找不到我想要的东西。也许是因为我仍然是网络领域的生物。

我要迁移的代码是

Startup.cs

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }
}

Startup.Auth.cs

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

        public static string PublicClientId { get; private set; }

        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/token"),
                Provider = new ApplicationOAuthProvider(),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(15),
                AllowInsecureHttp = true
            };
            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);
        }
    } 

ApplicationOAuthProvider.cs

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    private static string aadInstance = "https://login.microsoftonline.com/{0}";
    private static string tenant = ConfigurationManager.AppSettings["AzureAD.Tenant"];
    private static string clientId = ConfigurationManager.AppSettings["AzureAD.ClientId"];
    private static string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
    private static AuthenticationContext authContext = null;


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

        authContext = new AuthenticationContext(authority, new TokenCache());
        var creds = new UserPasswordCredential(context.UserName, context.Password);
        AuthenticationResult result;
        try
        {
            result = await authContext.AcquireTokenAsync(clientId, clientId, creds);
        }
        catch (Exception ex)
        {
            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"));
        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

        context.Validated(identity);

    }
}

所以有人在ASP核心中如何做到这一点?因为整个创业公司让我感到困惑,说实话。

0 个答案:

没有答案