ASP.NET Web API 2中基于令牌的身份验证不起作用

时间:2019-02-11 10:40:53

标签: c# authentication asp.net-web-api bearer-token

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
        app.UseCors(CorsOptions.AllowAll);
        var myProvider = new MyAuthorizationServerProvider();
        OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = myProvider
        };
        app.UseOAuthAuthorizationServer(options);
        app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions());
        HttpConfiguration config = new HttpConfiguration();
        WebApiConfig.Register(config);
    }
}

令牌成功生成,但是当我使用此令牌访问无法正常工作的Authorize控制器时。总是响应消息显示“此请求的授权已被拒绝” Here postman send request for generate token

这是我的MyAuthorizationServerProvider类

 public class MyAuthorizationServerProvider: OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }
    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        if(context.UserName== "admin" && context.Password == "admin")
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
            identity.AddClaim(new Claim("username", "admin"));
            identity.AddClaim(new Claim(ClaimTypes.Name, "Admin Ahasanul Banna"));
            context.Validated(identity);
        }
        else if (context.UserName=="user" && context.Password=="user")
        {
            identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
            identity.AddClaim(new Claim("username", "user"));
            identity.AddClaim(new Claim(ClaimTypes.Name, "User Ahasanul Banna"));
            context.Validated(identity);
        }
        else
        {
            context.SetError("Invalid_grant", "Provided username & password is incorrect");
            return;
        }
    }
}

还有我的AuthorizeAttribute类

    public class AuthorizeAttribute :System.Web.Http.AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        if (!HttpContext.Current.User.Identity.IsAuthenticated)
        {
            base.HandleUnauthorizedRequest(actionContext);
        }
        else
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
        }

    }
}

当我使用此令牌服务器响应访问任何“授权”操作时,“此请求的授权已被拒绝”。消息Here Postman send request

    [Authorize]
    [HttpGet]
    [Route("authenticate")]
    public IHttpActionResult GetForAuthenticate()
    {
        var identity = (ClaimsIdentity)User.Identity;
        return Ok("Hello" + identity.Name);
    }
    [Authorize(Roles ="admin")]
    [HttpGet]
    [Route("authorize")]
    public IHttpActionResult GetForAdmin()
    {
        var identity = (ClaimsIdentity)User.Identity;
        var roles = identity.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value);

        return Ok("Hello" + identity.Name +" Role: " +string.Join(",",roles.ToList()));
    }

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

检查此代码

public void Configuration(IAppBuilder app)
{
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
    app.UseCors(CorsOptions.AllowAll);
    var myProvider = new MyAuthorizationServerProvider();
    OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = myProvider
    };
    app.UseOAuthAuthorizationServer(options);
    app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions());
    HttpConfiguration config = new HttpConfiguration();
    WebApiConfig.Register(config);
}

在这里,您使用具有配置选项的授权服务器(确定):

app.UseOAuthAuthorizationServer(options);

然后不使用选项覆盖它(不确定)

app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions());

只需删除第二个app.UseOAuthAuthorizationServer,然后重试即可。

您也忘记添加

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());