在MyWebAPI.Entities中添加相应类
LoginRequest实体
public class LoginRequest
{
public string UserId { get; set; }
public string Password { get; set; }
}
AuthInfo实体类
public class AuthInfo
{
public string UserId { get; set; }
public DateTime Expires { get; set; }
}
HttpResul实体类
public class HttpResult
{
public bool Success { get; set; }
public dynamic Data { get; set; }
public string Message { get; set; }
}
4.3添加SystemController,并添加Login登录方法
具体代码如下:
[RoutePrefix(“api/System”)]
public class SystemController : ApiController
{
[HttpPost, Route(“Login”)]
public HttpResult Login([FromBody] LoginRequest loginRequest)
{
if (loginRequest == null) return new HttpResult() { Success = false, Message = “登录信息为空!” };
#region 通过数据库判断登录信息是否正确(这里简化判断)
if (loginRequest.UserId != "admin" || loginRequest.Password != "admin")
{
return new HttpResult() { Success = false, Message = "用户名和密码不正确!" };
}
#endregion
AuthInfo authInfo = new AuthInfo()
{
UserId = loginRequest.UserId,
Expires = DateTime.Now.AddDays(1)
};
const string secretKey = "matanzhang";//口令加密秘钥(应该写到配置文件中)
byte[] key = Encoding.UTF8.GetBytes(secretKey);
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//加密方式
IJsonSerializer serializer = new JsonNetSerializer();//序列化Json
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//base64加解密
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);//JWT编码
var token = encoder.Encode(authInfo, key);//生成令牌
return new HttpResult() { Success = true, Data = token,Message = "登录成功!"};
}
}
4.4添加API过滤器ApiAuthorizeAttribute
具体代码如下:
public class ApiAuthorizeAttribute: AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
try
{
var authHeader = from t in actionContext.Request.Headers where t.Key == “auth” select t.Value.FirstOrDefault();
var enumerable = authHeader as string[] ?? authHeader.ToArray();
string token = enumerable.FirstOrDefault();
if (string.IsNullOrEmpty(enumerable.FirstOrDefault())) return false;
const string secretKey = “matanzhang”;//口令加密秘钥(应该写到配置文件中)
byte[] key = Encoding.UTF8.GetBytes(secretKey);
IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
//解密
var authInfo = decoder.DecodeToObject(token, key, verify: true);
if (authInfo != null)
{
//判断口令过期时间
if (authInfo.Expires < DateTime.Now)
{
return false;
}
actionContext.RequestContext.RouteData.Values.Add(“auth”, authInfo);
return true;
}
}
catch (Exception e)
{
}
return false;
}
/// <summary>
/// 处理授权失败的请求
/// </summary>
/// <param name="actionContext"></param>
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
var erModel = new HttpResult()
{
Success = false,
Message = "身份认证不正确!"
};
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, erModel, "application/json");
}
}
4.5在StudentController中添加过滤属性ApiAuthorize
具体如下:
[RoutePrefix(“api/Student”),ApiAuthorize]
public class StudentController : ApiController
{
private static readonly List StudentList = new List()
{
new Student() {Id = “001”, Name = “张三”, Sex = “男”, Age = 19, Dept = “软件学院”},
new Student() {Id = “002”, Name = “李丽”, Sex = “女”, Age = 19, Dept = “资环学院”}
};
[HttpGet]
public IEnumerable<Student> Get()
{
return StudentList;
}
[HttpGet, Route("GetByDept/{dept}")]
public IEnumerable<Student> GetByDept(string dept)
{
List<Student> tempList = StudentList.Where(p => p.Dept == dept).ToList();
return tempList;
}
[HttpGet]
public Student Get(string id)
{
List<Student> tempList = StudentList.Where(p => p.Id == id).ToList();
return tempList.Count == 1 ? tempList.First() : null;
}
[HttpPost]
public bool Post([FromBody] Student student)
{
if (student == null) return false;
if (StudentList.Where(p => p.Id == student.Id).ToList().Count > 0) return false;
StudentList.Add(student);
return true;
}
[HttpPut]
public bool Put(string id, [FromBody] Student student)
{
if (student == null) return false;
List<Student> tempList = StudentList.Where(p => p.Id == id).ToList();
if (tempList.Count == 0) return false;
Student originStudent = tempList[0];
originStudent.Name = student.Name;
originStudent.Sex = student.Sex;
originStudent.Age = student.Age;
originStudent.Dept = student.Dept;
return true;
}
[HttpDelete]
public bool Delete(string id)
{
List<Student> tempList = StudentList.Where(p => p.Id == id).ToList();
if (tempList.Count == 0) return false;
StudentList.Remove(tempList[0]);
return true;
}
}
深圳网站优化www.zg886.cn