当前位置: 移动技术网 > IT编程>开发语言>.net > 浅谈如何在ASP.NET Core中实现一个基础的身份认证

浅谈如何在ASP.NET Core中实现一个基础的身份认证

2017年12月12日  | 移动技术网IT编程  | 我要评论

七海里佳,银鹭我是传奇,儿科疾病

asp.net终于可以跨平台了,但是不是我们常用的asp.net, 而是叫一个asp.net core的新平台,他可以跨windows, linux, os x等平台来部署你的web应用程序,你可以理解为,这个框架就是asp.net的下一个版本,相对于传统asp.net程序,它还是有一些不同的地方的,比如很多类库在这两个平台之间是不通用的。

今天首先我们在asp.net core中来实现一个基础的身份认证,既登陆功能。

前期准备:

1.推荐使用 vs 2015 update3 作为你的ide,下载地址:

2.你需要安装.net core的运行环境以及开发工具,这里提供vs版:

创建项目:

在vs中新建项目,项目类型选择asp.net core web application (.net core), 输入项目名称为testbasicauthor。

接下来选择 web application, 右侧身份认证选择:no authentication

打开startup.cs

在configureservices方法中加入如下代码:

services.addauthorization(); 

在configure方法中加入如下代码:

app.usecookieauthentication(new cookieauthenticationoptions 
{ 
  authenticationscheme = "cookie", 
  loginpath = new pathstring("/account/login"), 
  accessdeniedpath = new pathstring("/account/forbidden"), 
  automaticauthenticate = true, 
  automaticchallenge = true 
});

完整的代码应该是这样:

public void configureservices(iservicecollection services) 
{ 
  services.addmvc(); 
 
  services.addauthorization(); 
} 
 
public void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory) 
{ 
  app.usecookieauthentication(new cookieauthenticationoptions 
  { 
    authenticationscheme = "cookie", 
    loginpath = new pathstring("/account/login"), 
    accessdeniedpath = new pathstring("/account/forbidden"), 
    automaticauthenticate = true, 
    automaticchallenge = true 
  }); 
 
  app.usemvc(routes => 
  { 
    routes.maproute( 
       name: "default", 
       template: "{controller=home}/{action=index}/{id?}"); 
  }); 
}

你或许会发现贴进去的代码是报错的,这是因为还没有引入对应的包,进入报错的这一行,点击灯泡,加载对应的包就可以了。

在项目下创建一个文件夹命名为model,并向里面添加一个类user.cs

代码应该是这样

public class user
{
  public string username { get; set; }
  public string password { get; set; }
}

创建一个控制器,取名为:accountcontroller.cs

在类中贴入如下代码:

[httpget] 
public iactionresult login() 
{ 
  return view(); 
} 
 
[httppost] 
public async task<iactionresult> login(user userfromfore) 
{ 
  var userfromstorage = testuserstorage.userlist 
    .firstordefault(m => m.username == userfromfore.username && m.password == userfromfore.password); 
 
  if (userfromstorage != null) 
  { 
    //you can add all of claimtypes in this collection 
    var claims = new list<claim>() 
    { 
      new claim(claimtypes.name,userfromstorage.username) 
      //,new claim(claimtypes.email,"emailaccount@microsoft.com") 
    }; 
 
    //init the identity instances 
    var userprincipal = new claimsprincipal(new claimsidentity(claims, "supersecurelogin")); 
 
    //signin 
    await httpcontext.authentication.signinasync("cookie", userprincipal, new authenticationproperties 
    { 
      expiresutc = datetime.utcnow.addminutes(20), 
      ispersistent = false, 
      allowrefresh = false 
    }); 
 
    return redirecttoaction("index", "home"); 
  } 
  else 
  { 
    viewbag.errmsg = "username or password is invalid"; 
 
    return view(); 
  } 
} 
 
public async task<iactionresult> logout() 
{ 
  await httpcontext.authentication.signoutasync("cookie"); 
 
  return redirecttoaction("index", "home"); 
}

相同的文件里让我们来添加一个模拟用户存储的类

//for simple, i'm not using the database to store the user data, just using a static class to replace it.
public static class testuserstorage
{
  public static list<user> userlist { get; set; } = new list<user>() {
    new user { username = "user1",password = "112233"}
  };
}

接下来修复好各种引用错误。

完整的代码应该是这样

using system;
using system.collections.generic;
using system.linq;
using system.threading.tasks;
using microsoft.aspnetcore.mvc;
using testbasicauthor.model;
using system.security.claims;
using microsoft.aspnetcore.http.authentication;

// for more information on enabling mvc for empty projects, visit http://go.microsoft.com/fwlink/?linkid=397860

namespace testbasicauthor.controllers
{
  public class accountcontroller : controller
  {
    [httpget]
    public iactionresult login()
    {
      return view();
    }

    [httppost]
    public async task<iactionresult> login(user userfromfore)
    {
      var userfromstorage = testuserstorage.userlist
        .firstordefault(m => m.username == userfromfore.username && m.password == userfromfore.password);

      if (userfromstorage != null)
      {
        //you can add all of claimtypes in this collection 
        var claims = new list<claim>()
        {
          new claim(claimtypes.name,userfromstorage.username) 
          //,new claim(claimtypes.email,"emailaccount@microsoft.com") 
        };

        //init the identity instances 
        var userprincipal = new claimsprincipal(new claimsidentity(claims, "supersecurelogin"));

        //signin 
        await httpcontext.authentication.signinasync("cookie", userprincipal, new authenticationproperties
        {
          expiresutc = datetime.utcnow.addminutes(20),
          ispersistent = false,
          allowrefresh = false
        });

        return redirecttoaction("index", "home");
      }
      else
      {
        viewbag.errmsg = "username or password is invalid";

        return view();
      }
    }

    public async task<iactionresult> logout()
    {
      await httpcontext.authentication.signoutasync("cookie");

      return redirecttoaction("index", "home");
    }
  }

  //for simple, i'm not using the database to store the user data, just using a static class to replace it.
  public static class testuserstorage
  {
    public static list<user> userlist { get; set; } = new list<user>() {
    new user { username = "user1",password = "112233"}
  };
  }
}

在views文件夹中创建一个account文件夹,在account文件夹中创建一个名位index.cshtml的view文件。

贴入如下代码:

@model testbasicauthor.model.user

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
</head>
<body>
  @using (html.beginform())
  {
    <table>
      <tr>
        <td></td>
        <td>@viewbag.errmsg</td>
      </tr>
      <tr>
        <td>username</td>
        <td>@html.textboxfor(m => m.username)</td>
      </tr>
      <tr>
        <td>password</td>
        <td>@html.passwordfor(m => m.password)</td>
      </tr>
      <tr>
        <td></td>
        <td><button>login</button></td>
      </tr>
    </table>
  }
</body>
</html>

打开homecontroller.cs

添加一个action, authpage.

[authorize]
[httpget]
public iactionresult authpage()
{
  return view();
}

在views/home下添加一个视图,名为authpage.cshtml

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
</head>
<body>
  <h1>auth page</h1>

  <p>if you are not authorized, you can't visit this page.</p>
</body>
</html>

到此,一个基础的身份认证就完成了,核心登陆方法如下:

await httpcontext.authentication.signinasync("cookie", userprincipal, new authenticationproperties
{
  expiresutc = datetime.utcnow.addminutes(20),
  ispersistent = false,
  allowrefresh = false
});

启用验证如下:

public void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory)
{
  app.usecookieauthentication(new cookieauthenticationoptions
  {
    authenticationscheme = "cookie",
    loginpath = new pathstring("/account/login"),
    accessdeniedpath = new pathstring("/account/forbidden"),
    automaticauthenticate = true,
    automaticchallenge = true
  });
}

在某个controller或action添加[author],即可配置位需要登陆验证的页面。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网