自己写的认证程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AdminSaltSystem.Models;
using System.Security.Cryptography;
using Microsoft.Owin.Security;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using System.Security.Claims;
namespace AdminSaltSystem.Code
{
public class adminSigninManager
{
private IAuthenticationManager AuthenticationManager { get; }
SaltSystemEntities db = new SaltSystemEntities();
public adminSigninManager(IAuthenticationManager authenticationManager) {
AuthenticationManager = authenticationManager;
}
public SignInStatus Signin(string name, string password, bool RememberMe)
{
if (name == null || password == null) return SignInStatus.Failure;
//检测账户密码是否能够登录
var md5password = GetMD5(password);
var @operator = db.Tbl_Operator.Where(m => m.@operator.Trim() == name.Trim() && m.opassword== md5password);
if (@operator.Count() <= 0) return SignInStatus.Failure;
var op = @operator.FirstOrDefault();
SigninSession(op.ID.ToString(),op.@operator,op.Tbl_RoleSet.RoleName,op.Tbl_RoleSet.Permit_JSON,RememberMe);
return SignInStatus.Success;
}
private void SigninSession(string id,string name,string role,string permissionlist,bool rememberme) {
ClaimsIdentity claimsIdentity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.NameIdentifier, ClaimTypes.Role);
claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, id, "http://www.w3.org/2001/XMLSchema#string"));//如果有@Html.AntiForgeryToken()参与下面的ClaimTypes.NameIdentifier必须有
claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, name, "http://www.w3.org/2001/XMLSchema#string"));//可选 只是如果没有ClaimTypes.Name 就找不到名字
claimsIdentity.AddClaim(new Claim("permissionList", permissionlist, "http://www.w3.org/2001/XMLSchema#string"));////可选 同上
claimsIdentity.AddClaim(new Claim("Role", role, "http://www.w3.org/2001/XMLSchema#string"));////可选 同上
claimsIdentity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Custom Identity", "http://www.w3.org/2001/XMLSchema#string"));//如果有@Html.AntiForgeryToken()参与下面的ClaimTypes.NameIdentifier必须有
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = rememberme }, claimsIdentity);
}
public void SignOut()
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
}
#region 帮助程序
private static string GetMD5(string myString)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString);
byte[] targetData = md5.ComputeHash(fromData);
string byte2String = null;
for (int i = 0; i < targetData.Length; i++)
{
byte2String += targetData[i].ToString("x");
}
return byte2String;
}
#endregion
}
}
调用方法是在 accountcontroller.cs 里
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
//------------------------------------------------------
AdminSaltSystem.Code.adminSigninManager SM = new AdminSaltSystem.Code.adminSigninManager(AuthenticationManager);
var result=SM.Signin(model.username,model.password,model.RememberMe);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal("/auth/index");
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = "/auth/index", RememberMe = model.RememberMe });
case SignInStatus.Failure:
ModelState.AddModelError("", "登录失败。");
return View(model);
default:
ModelState.AddModelError("", "无效的登录尝试。");
return View(model);
}
获取认证信息的方法
using System.Security.Principal;
using System.Security.Claims;
//////////////////////////////
///////////////////////
ClaimsIdentity xxx = new ClaimsIdentity(user.Identity);//user为上下文中中的user类型为IPrincipal
var myclaims = xxx.Claims.Where(m => m.Type == "permissionList").First().Value;
JObject myjobjct = JObject.Parse(myclaims);
var names = (string)myjobjct["name"];
foreach (var x in myjobjct)
{
}
var list = new List<string>();
return list;
}
调用方法只要找到上下文里的user就可以
在网上找到的相关资料用于学习、、、、、、、
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Http.Features.Authentication;
using Microsoft.AspNet.Authentication.Cookies;
using System.Security.Claims;
namespace IdentitySample.Controllers
{
public class AccountController : Controller
{
// Methods
public IActionResult Login(string returnUrl = null)
{
// ViewData
this.ViewData["ReturnUrl"] = returnUrl;
// Return
return View();
}
public async Task<IActionResult> PasswordLogin(string userId, string password, string returnUrl = null)
{
// Login
var existingIdentitySystem = new ExistingIdentitySystem();
if (existingIdentitySystem.PasswordSignIn(userId, password) == false)
{
throw new InvalidOperationException();
}
// ExistingUser
var existingUser = existingIdentitySystem.GetUserById(userId);
if (existingUser == null) throw new InvalidOperationException();
// ApplicationUser
var applicationIdentity = new ClaimsIdentity(IdentityOptions.Current.ApplicationCookieAuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
applicationIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, existingUser.Id));
applicationIdentity.AddClaim(new Claim(ClaimTypes.Name, existingUser.Name));
var applicationUser = new ClaimsPrincipal(applicationIdentity);
// Cookie
await this.HttpContext.Authentication.SignInAsync(IdentityOptions.Current.ApplicationCookieAuthenticationScheme, applicationUser);
await this.HttpContext.Authentication.SignOutAsync(IdentityOptions.Current.ExternalCookieAuthenticationScheme);
// Return
return Redirect(returnUrl);
}
public IActionResult ExternalLogin(string externalProvider, string returnUrl = null)
{
// AuthenticationProperties
var authenticationProperties = new AuthenticationProperties();
authenticationProperties.Items.Add("ExternalProvider", externalProvider);
authenticationProperties.RedirectUri = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
// Return
return new ChallengeResult(externalProvider, authenticationProperties);
}
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null)
{
// AuthenticateContext
var authenticateContext = new AuthenticateContext(IdentityOptions.Current.ExternalCookieAuthenticationScheme);
await this.HttpContext.Authentication.AuthenticateAsync(authenticateContext);
// AuthenticateInfo
string userId = authenticateContext.Principal.FindFirst(ClaimTypes.Email).Value;
string externalProvider = authenticateContext.Properties["ExternalProvider"] as string;
// Login
var existingIdentitySystem = new ExistingIdentitySystem();
if (existingIdentitySystem.ExternalSignIn(userId, externalProvider) == false)
{
throw new InvalidOperationException();
}
// ExistingUser
var existingUser = existingIdentitySystem.GetUserById(userId);
if (existingUser == null) throw new InvalidOperationException();
// ApplicationUser
var applicationIdentity = new ClaimsIdentity(IdentityOptions.Current.ApplicationCookieAuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
applicationIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, existingUser.Id));
applicationIdentity.AddClaim(new Claim(ClaimTypes.Name, existingUser.Name));
var applicationUser = new ClaimsPrincipal(applicationIdentity);
// Cookie
await this.HttpContext.Authentication.SignInAsync(IdentityOptions.Current.ApplicationCookieAuthenticationScheme, applicationUser);
await this.HttpContext.Authentication.SignOutAsync(IdentityOptions.Current.ExternalCookieAuthenticationScheme);
// Return
return Redirect(returnUrl);
}
}
}