一.新建.net webapi程序
二.nuget包搜索jwt,点击安装
三.在model文件夹下建立三个主要类:
public class AuthInfo
{
/// <summary>
/// 用户名
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 角色
/// </summary>
public List<string> Roles { get; set; }
/// <summary>
/// 是否管理员
/// </summary>
public bool IsAdmin { get; set; }
/// <summary>
/// 口令过期时间
/// </summary>
public DateTime? ExpiryDateTime { get; set; }
}
public class LoginRequest
{
/// <summary>
/// 用户名
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 密码
/// </summary>
public string Password { get; set; }
}
public class TokenInfo
{
/// <summary>
/// 是否成功
/// </summary>
public bool Success { get; set; }
/// <summary>
/// 令牌
/// </summary>
public string Token { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public string Message { get; set; }
}
四.在Controllers文件夹下创建TokenController.cs文件,主要是登陆时生成口令
[RoutePrefix("api/Token")]
public class TokenController : ApiController
{
/// <summary>
/// 登录
/// </summary>
/// <param name="loginRequest"></param>
/// <returns></returns>
[HttpPost]
[Route("Login")]
public TokenInfo Login([FromBody] LoginRequest loginRequest)
{
TokenInfo tokenInfo = new TokenInfo() { Success = false,Message = "用户信息为空!"};
if (loginRequest != null)
{
string userName = loginRequest.UserName;
string passWord = loginRequest.Password;
bool isAdmin = userName == "admin" ? true : false;
AuthInfo authInfo = new AuthInfo() { UserName = userName, Roles = new List<string> { "admin","commonrole"},IsAdmin = isAdmin, ExpiryDateTime = DateTime.Now.AddHours(2) };
const string secretKey = "Hello World";
try
{
byte[] key = Encoding.UTF8.GetBytes(secretKey);
IJwtAlgorithm jwtAlgorithm = new HMACSHA256Algorithm();
IJsonSerializer jsonSerializer = new JsonNetSerializer();
IBase64UrlEncoder base64UrlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encode = new JwtEncoder(jwtAlgorithm, jsonSerializer, base64UrlEncoder);
var token = encode.Encode(authInfo, key); //生成的令牌
tokenInfo.Success = true;
tokenInfo.Token = token;
tokenInfo.Message = "ok";
}
catch (Exception ex)
{
tokenInfo.Message = ex.Message;
}
}
return tokenInfo;
}
}
五.在项目中添加AuthAttributes文件夹,并且在文件夹在创建ApiAuthorizeAttribute.cs文件,用于创建身份拦截器
/// <summary>
/// 身份认证拦截器
/// </summary>
public class ApiAuthorizeAttribute:AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var authHeader = from t in actionContext.Request.Headers where t.Key == "auth" select t.Value.FirstOrDefault();
if (authHeader != null)
{
const string secreKey = "Hello World";
string token = authHeader.FirstOrDefault();
if (!string.IsNullOrEmpty(token))
{
byte[] key = Encoding.UTF8.GetBytes(secreKey);
try
{
IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtAlgorithm jwtAlgorithm = new HMACSHA256Algorithm();
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, jwtAlgorithm);
var json = decoder.DecodeToObject<AuthInfo>(token, key, verify: true);
if (json != null)
{
if (json.ExpiryDateTime < DateTime.Now)
{
return false;
}
actionContext.RequestContext.RouteData.Values.Add("auth", json);
return true;
}
}
catch (Exception ex)
{
return false;
}
}
}
return false;
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
var erModel = new
{
Success = "false",
ErrorCode = "401"
};
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, erModel, "application/json");
}
}
六.创建UserInfoController.cs 用于获取数据,测试身份验证功能是否成功
[RoutePrefix("api/UserInfo")]
[ApiAuthorize]
public class UserInfoController : ApiController
{
[HttpGet]
[Route("GetUserInfo")]
public string GetUserInfo()
{
var userInfo = new
{
UserName = "test",
Tel = "123456789",
Address = "testddd"
};
return JsonConvert.SerializeObject(userInfo);
}
}
最后F5运行程序,功能测试,打开PostMan
1.首先不进行登录(不获取token看能否获取到数据)
结果:返回未授权信息
2.进行登录在获取
获取到token,然后再进行接口访问
同样,如果输入错误token也会获取不到数据
成功获取到数据信息,致此以全部完成!
转载自:https://blog.csdn.net/liwan09/article/details/83820651