asp.net core中虽然集成了许多常用的身份认证,但很多时候,我们还是需要实现自己的身份认证接口,本文这里就简单的介绍下如何实现自定义身份认证接口。

首先写一个简单的接口。

[authorize]
[httpget]
public object foo()
{
  return datetime.now.tostring();
}

由于有authorize标记,访问函数体前会判断用户是否通过认证,由于这里没有通过认证,会的得到一个500错误。

自定义认证处理类:

实现一个iauthenticationhandler接口即可:

public class myauthhandler : iauthenticationhandler
  {
    public const string schemename = "myauth";

    authenticationscheme _scheme;
    httpcontext     _context;

    /// <summary>
    /// 初始化认证
    /// </summary>
    public task initializeasync(authenticationscheme scheme, httpcontext context)
    {
      _scheme = scheme;
      _context = context;
      return task.completedtask;
    }

    /// <summary>
    /// 认证处理
    /// </summary>
    public task<authenticateresult> authenticateasync()
    {
      var req   = _context.request.query;
      var islogin = req["islogin"].firstordefault();

      if (islogin != "true")
      {
        return task.fromresult(authenticateresult.fail("未登陆"));
      }

      var ticket = getauthticket("test", "test");
      return task.fromresult(authenticateresult.success(ticket));
    }

    authenticationticket getauthticket(string name, string role)
    {
      var claimsidentity = new claimsidentity(new claim[]
      {
        new claim(claimtypes.name, name),
        new claim(claimtypes.role, role),
      }, "my_auth");

      var principal = new claimsprincipal(claimsidentity);
      return new authenticationticket(principal, _scheme.name);
    }

    /// <summary>
    /// 权限不足时的处理
    /// </summary>
    public task forbidasync(authenticationproperties properties)
    {
      _context.response.statuscode = (int)httpstatuscode.forbidden;
      return task.completedtask;
    }

    /// <summary>
    /// 未登录时的处理
    /// </summary>
    public task challengeasync(authenticationproperties properties)
    {
      _context.response.statuscode = (int)httpstatuscode.unauthorized;
      return task.completedtask;
    }
  }

主体函数是authenticateasync,主要进行了如下几步

首先是根据http上下文判断用户是否通过认证,这里我实现的比较简单,判断下querystring中的islogin是否为true,为true则通过验证。如果通过认证,则生成一个claimsprincipal对象,返回认证成功

claimsprincipal对象它是.net core的验证模型。asp.net core 的验证模型是claims-based authentication,网上有一些文章来介绍他introduction to authentication with asp.net core。他们代表的意义如下:

claim是用户信息,例如用户名,角色,邮件。一般常用的是用户名和角色。特别是角色,经常接用于授权信息中。一组claims构成了一个identity,构成了claimsidentity对象,可以把claimsidentity理解为”证件”,驾照是一种证件,护照也是一种证件。理解记录了用户的基本信息。claimsidentity的持有者就是claimsprincipal,一个claimsprincipal可以持有多个claimsidentity,就比如一个人既持有驾照,又持有护照。

认证通过后,也可以通过httpcontext.user属性获取这个对象,从而获取用户名,角色等信息

注册自定义认证处理类:

在startup.cs中进行如下配置:

开启身份验证中间件

app.useauthentication();
app.useauthorization();

配置选项

services.addauthentication(options =>
  {
    options.addscheme<myauthhandler>(myauthhandler.schemename, "default scheme");
    options.defaultauthenticatescheme = myauthhandler.schemename;
    options.defaultchallengescheme  = myauthhandler.schemename;
  });

测试:

上述功能完成后,再进行前面的测试,在url中带上认证信息访问:

可以看到这次能成功访问接口,说明认证信息是生效了的。

到此这篇关于asp.net core中实现自定义身份认证的示例代码的文章就介绍到这了,更多相关asp.net core自定义身份认证内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!