Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# .Net Core 2.0授权始终返回401_C#_Authentication_Asp.net Core_Asp.net Core 2.0 - Fatal编程技术网

C# .Net Core 2.0授权始终返回401

C# .Net Core 2.0授权始终返回401,c#,authentication,asp.net-core,asp.net-core-2.0,C#,Authentication,Asp.net Core,Asp.net Core 2.0,将[Authorize]添加到控制器后,我总是从它那里得到401。调试时,我看到已到达返回AuthenticateResult.Success,但控制器的代码从未到达。 我做错了什么 下面是我的启动类和自定义身份验证类的代码 公共类启动 { public void配置服务(IServiceCollection服务) { // ... services.AddCors(选项=> { options.AddPolicy(“CorsPolicy”,builder=>builder .AllowAny

[Authorize]
添加到控制器后,我总是从它那里得到401。调试时,我看到已到达
返回AuthenticateResult.Success
,但控制器的代码从未到达。
我做错了什么

下面是我的启动类和自定义身份验证类的代码


公共类启动
{
public void配置服务(IServiceCollection服务)
{
// ...
services.AddCors(选项=>
{
options.AddPolicy(“CorsPolicy”,builder=>builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials());
});
配置(选项=>
{
options.Filters.Add(新的requireHttpAttribute());
});
services.AddAuthentication(选项=>
{
options.DefaultAuthenticateScheme=“自定义方案”;
options.DefaultChallengeScheme=“自定义方案”;
}).AddCustomAuth(o=>{});
services.AddMvc();
}
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
附录UseCors(“公司政策”);
var options=new RewriteOptions().AddRedirectToHttps();
app.UseRewriter(选项);
app.UseAuthentication();
app.UseMvc();
}
}

公共类CustomAuthOptions:AuthenticationSchemeOptions { 公共索赔实体标识{get;set;} 公共自定义选项() { } } 公共静态类CustomAuthExtensions { 公共静态AuthenticationBuilder AddCustomAuth(此AuthenticationBuilder,操作配置选项) { 返回builder.AddScheme(“自定义方案”、“自定义身份验证”、配置选项); } } 内部类CustomAuthHandler:AuthenticationHandler { public CustomAuthHandler(IOptionsMonitor选项、iLogger工厂记录器、UrlEncoder编码器、ISystemClock时钟):基本(选项、记录器、编码器、时钟) { } 受保护的重写异步任务handleAuthenticateAync() { string token=Request.Headers[“Authorization”]; if(string.IsNullOrEmpty(令牌)) 返回AuthenticateResult.Fail(“失败字符串”); //使用外部服务验证令牌并获取用户id int Id=GetUserId(令牌); 返回AuthenticateResult.Success( 新身份验证票证( 新权利要求书( 新索赔实体( 新列表(){new Claim(ClaimTypes.Sid,Id.ToString())}), 计划名称),; } }
该问题是由您在
CustomAuthHandler.HandleAuthenticationAsync()中创建
ClaimsEntity
实例的方式引起的。<代码>主体.IdIsAudioSudio/<代码>的值将是<代码> false < /代码>,这使得<代码> AuthigeAtgult<代码>考虑您的请求未经授权。

详细说明了
IsAuthenticated
设置为false的原因。要修复它,只需使用
ClaimsIdentity
构造函数重载,该重载接受
authenticationType

return AuthenticateResult.Success(
    new AuthenticationTicket(
        new ClaimsPrincipal(
            new ClaimsIdentity(
                new List<Claim>() { new Claim(ClaimTypes.Sid, Id.ToString()) }, Scheme.Name)),
        Scheme.Name));
返回AuthenticateResult.Success(
新身份验证票证(
新权利要求书(
新索赔实体(
新列表(){new Claim(ClaimTypes.Sid,Id.ToString())},Scheme.Name)),
计划名称),;

启用日志记录并查看内部系统正在执行的操作,您可能会在其中看到一些有用的信息感谢您的回答,我正在创建带有
ClaimType.AuthenticationScheme的声明列表,但授权失败,在搜索了很多次后,您的回答刚刚解决了我的问题(我使用的是ASP.net core 2.1)
public class CustomAuthOptions : AuthenticationSchemeOptions
{
    public ClaimsIdentity Identity { get; set; }

    public CustomAuthOptions()
    {

    }
}

public static class CustomAuthExtensions
{
    public static AuthenticationBuilder AddCustomAuth(this AuthenticationBuilder builder, Action<CustomAuthOptions> configureOptions)
    {
        return builder.AddScheme<CustomAuthOptions, CustomAuthHandler>("Custom Scheme", "Custom Auth", configureOptions);
    }
}

internal class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
{
    public CustomAuthHandler(IOptionsMonitor<CustomAuthOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
    {

    }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        string token = Request.Headers["Authorization"];
        if (string.IsNullOrEmpty(token))
            return AuthenticateResult.Fail("Failing string");

        // Using external service to validate token and get user id
        int Id = GetUserId(token);

        return AuthenticateResult.Success(
            new AuthenticationTicket(
                new ClaimsPrincipal(
                    new ClaimsIdentity(
                        new List<Claim>() { new Claim(ClaimTypes.Sid, Id.ToString()) })),
                        Scheme.Name));
    }
}
return AuthenticateResult.Success(
    new AuthenticationTicket(
        new ClaimsPrincipal(
            new ClaimsIdentity(
                new List<Claim>() { new Claim(ClaimTypes.Sid, Id.ToString()) }, Scheme.Name)),
        Scheme.Name));