如何在asp.net swagger API中实现基于令牌的身份验证?

时间:2019-06-12 22:10:00

标签: authentication asp.net-web-api swagger owin bearer-token

我有一个swagger API项目并安装了OWIN所需的所有nuget软件包以进行身份​​验证。如何将登录系统集成到swagger ui中?用于验证用户名和密码的api URL链接是什么? 提前感谢

我试图调用[MyAuthProvider]类,该类从控制器继承了[OAuthAuthorizationServerProvider]类,但无法正常工作。

// MyAuthProvider类

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


    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);

        UserRepository repository = new UserRepository();
        var userdata = repository.GetAll().Where(e => e.Username.Contains(context.UserName) && e.Password.Contains(context.Password)).FirstOrDefault();
        if (userdata != null)
        {
            //identity.AddClaim(new Claim(ClaimTypes.Role, userdata.UserRole));
            identity.AddClaim(new Claim(ClaimTypes.Name, userdata.Username));
            context.Validated(identity);
        }
        else
        {
            context.SetError("invalid_grant", "Provided username and password is incorrect");
            context.Rejected();
        }
    }
}

//启动类

public class Startup
{
    public void Configuration(IAppBuilder app)
    {

        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        var myProvider = new MyAuthProvider();
        OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
            Provider = myProvider
        };
        app.UseOAuthAuthorizationServer(options);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());


        HttpConfiguration config = new HttpConfiguration();
        WebApiConfig.Register(config);
    }
}

}

我想从angular制作的客户端调用此api来授权下一步。

0 个答案:

没有答案