简体   繁体   English

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

[英]Token based authentication in ASP.NET Web API 2 not working

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);
    }
}

Token generate successfully but when I use this token to access Authorize controller that not work properly. 令牌生成成功,但是当我使用此令牌访问无法正常工作的Authorize控制器时。 Always response message show "Authorization has been denied for this request" Here postman send request for generate token 总是响应消息显示“对此请求的授权已被拒绝” 此处邮递员发送生成令牌的请求

This is my MyAuthorizationServerProvider class 这是我的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;
        }
    }
}

And my AuthorizeAttribute class 还有我的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);
        }

    }
}

When I access any Authorize action using this token server response "Authorization has been denied for this request." 当我使用此令牌服务器响应访问任何“授权”操作时,“此请求的授权已被拒绝”。 message 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()));
    }

How to solve this issue? 如何解决这个问题?

Check this code 检查此代码

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);
}

here you use an authorization server with configured options (OK): 在这里,您使用具有配置选项的授权服务器(确定):

app.UseOAuthAuthorizationServer(options);

then override it without options (NOT OK) 然后将其覆盖而没有选项(不确定)

app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions());

Just remove the second app.UseOAuthAuthorizationServer and try again. 只需删除第二个应用程序app.UseOAuthAuthorizationServer然后重试。

Also you forgot to add 你也忘了加

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM