ASP.NET核心Web API身份验证

ht4b089n  于 2022-12-20  发布在  .NET
关注(0)|答案(9)|浏览(236)

我正纠结于如何在我的网络服务中设置身份验证。这个服务是用ASP.NET核心网络API构建的。
我的所有客户端(WPF应用程序)都应该使用相同的凭据来调用Web服务操作。
经过一番研究,我提出了基本身份验证--在HTTP请求的头中发送用户名和密码。但是经过几个小时的研究,我认为基本身份验证不是ASP.NET核心中的正确做法。
我找到的大多数资源都是使用OAuth或其他一些中间件来实现身份验证的,但这对于我的场景以及使用ASP .NETCore的Identity部分来说似乎太大了。
那么,实现我的目标的正确方法是什么--在ASP .NETCoreWeb服务中使用用户名和密码进行简单的身份验证?

brtdzjyr

brtdzjyr1#

现在,在我被指出正确的方向后,我的完整解决方案如下:
这是在每个传入请求上执行的中间件类,用于检查请求是否具有正确的身份证明。如果没有身份证明或身份证明错误,服务将立即以 401 Unauthorized 错误进行响应。

public class AuthenticationMiddleware
{
    private readonly RequestDelegate _next;

    public AuthenticationMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        string authHeader = context.Request.Headers["Authorization"];
        if (authHeader != null && authHeader.StartsWith("Basic"))
        {
            //Extract credentials
            string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
            Encoding encoding = Encoding.GetEncoding("iso-8859-1");
            string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));

            int seperatorIndex = usernamePassword.IndexOf(':');

            var username = usernamePassword.Substring(0, seperatorIndex);
            var password = usernamePassword.Substring(seperatorIndex + 1);

            if(username == "test" && password == "test" )
            {
                await _next.Invoke(context);
            }
            else
            {
                context.Response.StatusCode = 401; //Unauthorized
                return;
            }
        }
        else
        {
            // no authorization header
            context.Response.StatusCode = 401; //Unauthorized
            return;
        }
    }
}

需要在服务Startup类的Configure方法中调用中间件扩展

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseMiddleware<AuthenticationMiddleware>();

    app.UseMvc();
}

就是这样!:)
关于.Net Core中的中间件和身份验证的一个非常好的资源可以在这里找到:https://www.exceptionnotfound.net/writing-custom-middleware-in-asp-net-core-1-0/

v1uwarro

v1uwarro2#

您可以实现一个处理基本身份验证的中间件。

public async Task Invoke(HttpContext context)
{
    var authHeader = context.Request.Headers.Get("Authorization");
    if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
    {
        var token = authHeader.Substring("Basic ".Length).Trim();
        System.Console.WriteLine(token);
        var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
        var credentials = credentialstring.Split(':');
        if(credentials[0] == "admin" && credentials[1] == "admin")
        {
            var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
            var identity = new ClaimsIdentity(claims, "Basic");
            context.User = new ClaimsPrincipal(identity);
        }
    }
    else
    {
        context.Response.StatusCode = 401;
        context.Response.Headers.Set("WWW-Authenticate", "Basic realm=\"dotnetthoughts.net\"");
    }
    await _next(context);
}

这段代码是在www.example.com核心的beta版本中编写asp.net的。希望它能有所帮助。

kulphzqa

kulphzqa3#

例如,要仅对特定控制器使用此选项,请使用以下命令:

app.UseWhen(x => (x.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)), 
            builder =>
            {
                builder.UseMiddleware<AuthenticationMiddleware>();
            });
6tdlim6h

6tdlim6h4#

我认为您可以使用JWT(Json Web令牌)。
首先,您需要安装System.IdentityModel.Tokens.Jwt包:

$ dotnet add package System.IdentityModel.Tokens.Jwt

您需要添加一个控制器来生成令牌和进行身份验证,如下所示:

public class TokenController : Controller
{
    [Route("/token")]

    [HttpPost]
    public IActionResult Create(string username, string password)
    {
        if (IsValidUserAndPasswordCombination(username, password))
            return new ObjectResult(GenerateToken(username));
        return BadRequest();
    }

    private bool IsValidUserAndPasswordCombination(string username, string password)
    {
        return !string.IsNullOrEmpty(username) && username == password;
    }

    private string GenerateToken(string username)
    {
        var claims = new Claim[]
        {
            new Claim(ClaimTypes.Name, username),
            new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
            new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(1)).ToUnixTimeSeconds().ToString()),
        };

        var token = new JwtSecurityToken(
            new JwtHeader(new SigningCredentials(
                new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret Key You Devise")),
                                         SecurityAlgorithms.HmacSha256)),
            new JwtPayload(claims));

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}

之后,更新Startup.cs类,如下所示:

namespace WebAPISecurity
{   
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.AddMvc();

        services.AddAuthentication(options => {
            options.DefaultAuthenticateScheme = "JwtBearer";
            options.DefaultChallengeScheme = "JwtBearer";
        })
        .AddJwtBearer("JwtBearer", jwtBearerOptions =>
        {
            jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret Key You Devise")),
                ValidateIssuer = false,
                //ValidIssuer = "The name of the issuer",
                ValidateAudience = false,
                //ValidAudience = "The name of the audience",
                ValidateLifetime = true, //validate the expiration and not before values in the token
                ClockSkew = TimeSpan.FromMinutes(5) //5 minute tolerance for the expiration date
            };
        });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseAuthentication();

        app.UseMvc();
    }
}

就是这样,现在剩下的就是把[Authorize]属性放在你想要的控制器或动作上。
这里是一个完整的直接教程的链接。
http://www.blinkingcaret.com/2017/09/06/secure-web-api-in-asp-net-core/

mefy6pfw

mefy6pfw5#

我已经实现了BasicAuthenticationHandler用于基本身份验证,因此您可以将其与标准属性AuthorizeAllowAnonymous一起使用。

public class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOptions>
{
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var authHeader = (string)this.Request.Headers["Authorization"];

        if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
        {
            //Extract credentials
            string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
            Encoding encoding = Encoding.GetEncoding("iso-8859-1");
            string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));

            int seperatorIndex = usernamePassword.IndexOf(':', StringComparison.OrdinalIgnoreCase);

            var username = usernamePassword.Substring(0, seperatorIndex);
            var password = usernamePassword.Substring(seperatorIndex + 1);

            //you also can use this.Context.Authentication here
            if (username == "test" && password == "test")
            {
                var user = new GenericPrincipal(new GenericIdentity("User"), null);
                var ticket = new AuthenticationTicket(user, new AuthenticationProperties(), Options.AuthenticationScheme);
                return Task.FromResult(AuthenticateResult.Success(ticket));
            }
            else
            {
                return Task.FromResult(AuthenticateResult.Fail("No valid user."));
            }
        }

        this.Response.Headers["WWW-Authenticate"]= "Basic realm=\"yourawesomesite.net\"";
        return Task.FromResult(AuthenticateResult.Fail("No credentials."));
    }
}

public class BasicAuthenticationMiddleware : AuthenticationMiddleware<BasicAuthenticationOptions>
{
    public BasicAuthenticationMiddleware(
       RequestDelegate next,
       IOptions<BasicAuthenticationOptions> options,
       ILoggerFactory loggerFactory,
       UrlEncoder encoder)
       : base(next, options, loggerFactory, encoder)
    {
    }

    protected override AuthenticationHandler<BasicAuthenticationOptions> CreateHandler()
    {
        return new BasicAuthenticationHandler();
    }
}

public class BasicAuthenticationOptions : AuthenticationOptions
{
    public BasicAuthenticationOptions()
    {
        AuthenticationScheme = "Basic";
        AutomaticAuthenticate = true;
    }
}

在Startup. cs-app.UseMiddleware<BasicAuthenticationMiddleware>();注册。使用此代码,您可以限制任何具有标准属性Autorize的控制器:

[Authorize(ActiveAuthenticationSchemes = "Basic")]
[Route("api/[controller]")]
public class ValuesController : Controller

如果在应用程序级别应用授权过滤器,则使用属性AllowAnonymous

8gsdolmq

8gsdolmq6#

正如之前的文章所言,其中一种方法是实现一个自定义的基本身份验证中间件。我在这个博客中找到了最好的工作代码:Basic Auth with custom middleware
我提到了同一个博客,但不得不做2个适应:
1.在启动文件-〉配置函数中添加中间件时,务必先添加自定义中间件,再添加app.UseMvc()。
1.从appsettings.json文件阅读用户名、密码时,在启动文件中添加静态只读属性。然后从appsettings.json读取。最后,从项目中的任何位置读取值。示例:

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

  public IConfiguration Configuration { get; }
  public static string UserNameFromAppSettings { get; private set; }
  public static string PasswordFromAppSettings { get; private set; }

  //set username and password from appsettings.json
  UserNameFromAppSettings = Configuration.GetSection("BasicAuth").GetSection("UserName").Value;
  PasswordFromAppSettings = Configuration.GetSection("BasicAuth").GetSection("Password").Value;
}
mm9b1k5b

mm9b1k5b7#

您可以使用ActionFilterAttribute

public class BasicAuthAttribute : ActionFilterAttribute
{
    public string BasicRealm { get; set; }
    protected NetworkCredential Nc { get; set; }

    public BasicAuthAttribute(string user,string pass)
    {
        this.Nc = new NetworkCredential(user,pass);
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var req = filterContext.HttpContext.Request;
        var auth = req.Headers["Authorization"].ToString();
        if (!String.IsNullOrEmpty(auth))
        {
            var cred = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(auth.Substring(6)))
                .Split(':');
            var user = new {Name = cred[0], Pass = cred[1]};
            if (user.Name == Nc.UserName && user.Pass == Nc.Password) return;
        }

        filterContext.HttpContext.Response.Headers.Add("WWW-Authenticate",
            String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Ryadel"));
        filterContext.Result = new UnauthorizedResult();
    }
}

并将该属性添加到控制器
[BasicAuth("USR", "MyPassword")]

jslywgbw

jslywgbw8#

在这个公开的Github repo https://github.com/boskjoett/BasicAuthWebApi中,你可以看到一个简单的API示例,它的端点受到基本身份验证的保护。

dzjeubhm

dzjeubhm9#

ASP.NET核心2.0(带Angular )

https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login
确保使用身份验证筛选器的类型

[授权(验证方案= JwtBearer默认值.验证方案)]

相关问题