在.net Core中使用身份验证方案时返回403(禁止)

时间:2018-11-28 12:44:56

标签: authentication

我正在使用Jwt安全令牌和自定义身份验证方案在Web应用程序中进行身份验证。

1)用户登录时我正在生成令牌

2)我创建了身份验证处理程序,在其中验证所有请求的令牌

//Authentication Handler

public class CustomAuthenticationHandler : AuthenticationHandler<CustomAuthenticationOptions>
{
    public CustomAuthenticationHandler(
        IOptionsMonitor<CustomAuthenticationOptions> options,
        ILoggerFactory logger, 
        UrlEncoder encoder, 
        ISystemClock clock)
    : base(options, logger, encoder, clock)
    {

    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        try
        {
            Exception ex;
            var key = Request.Headers[Options.HeaderName].First();

            if (!IsValid(key, out ex))
            {

                return Task.FromResult(AuthenticateResult.Fail(ex.Message));
                //filterContext.Result = new CustomUnauthorizedResult(ex.Message);
            }
            else
            {

                AuthenticationTicket ticket = new AuthenticationTicket(new ClaimsPrincipal(),new AuthenticationProperties(),this.Scheme.Name);
                return Task.FromResult(AuthenticateResult.Success(ticket));
            }
        }
        catch (InvalidOperationException)
        {
            return Task.FromResult(AuthenticateResult.Fail(""));
        }
    }
}

public static class CustomAuthenticationExtensions
{
    public static AuthenticationBuilder AddCustomAuthentication(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<CustomAuthenticationOptions> configureOptions)
    {
        return builder.AddScheme<CustomAuthenticationOptions, CustomAuthenticationHandler>(authenticationScheme, displayName, configureOptions);
    }
}

这是我的startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddMvc().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Person>());
        services.AddTransient<IRepositoryWrapper, RepositoryWrapper>();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        services.AddAuthentication(options=> {
            options.DefaultScheme = "CustomScheme";
            options.DefaultAuthenticateScheme = "CustomScheme";
            options.DefaultChallengeScheme = "CustomScheme";
        }).AddCustomAuthentication("CustomScheme", "CustomScheme", o => { });

    }


    public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddDebug(LogLevel.Information);

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseAuthentication();
        app.UseHttpsRedirection();
        app.UseMvc();

    }
}

在这里我使用了身份验证方案

[Authorize(AuthenticationSchemes ="CustomScheme")]
[ApiController]
[Route("api/controller")]
public class UserController : BaseController
{

    public UserController(IRepositoryWrapper repository) : base(repository)
    {
    }

    [HttpGet]
    public IEnumerable<Users> Get()
    {
        return _repository.Users.FindAll();
    }
}

当我使用有效令牌从邮递员调用api时,会返回403错误。

请帮助解决此问题... !!

2 个答案:

答案 0 :(得分:1)

对于遇到此问题的其他人:

最初的问题似乎是在 AuthenticationHandler 中返回 AuthenticationResult 时,没有将 ClaimsIdentity 传递给 ClaimsPrincipal。另请注意,身份验证类型必须传递给 ClaimsIdentity,否则 IsAuthenticated 将为 false。在 AuthenticationHandler 中做这样的事情应该可以解决这个问题:

else
{
    var claimsPrincipal = new ClaimsPrincipal();
    var claimsIdentity = new ClaimsIdentity("JWT");
    claimsPrincipal.AddIdentity(claimsIdentity);

    var ticket = new AuthenticationTicket(claimsPrincipal, this.Scheme.Name);

    return AuthenticateResult.Success(ticket);
}

答案 1 :(得分:0)

我找到了解决方法。

我使用CustomAuthenticationMiddle而不是AuthenticationHandler

public class CustomAuthenticationMiddleware
{
    private readonly RequestDelegate _next;
    public CustomAuthenticationMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task Invoke(HttpContext context)
    {
            try
            {
                Exception ex;
                var key = context.Request.Headers["Authorization"].First();

                if (!IsValid(key))
                {
                       //logic for authentication
                }
                else
                {

                    await _next.Invoke(context);
                }
            }
            catch (InvalidOperationException)
            {
                context.Response.StatusCode = 401; //Unauthorized
                return;
            }
        }

    private bool IsValid(string key)
    {
        //Code for checking the key is valid or not
    }
}

,我在startup.cs中添加了以下内容

app.UseMiddleware<CustomAuthenticationMiddleware>();