基于Web.Api的基本令牌认证和授权
本文关键字:令牌 认证和 授权 Web Api 基于 | 更新日期: 2023-09-27 18:05:44
所以我有一个MVC应用程序调用WebApi方法。
我对MVC App的授权是这样完成的
public class CustomAuthorizeAttribute : AuthorizeAttribute {
private RolesEnum _role;
public CustomAuthorizeAttribute() {
_role = RolesEnum.User;
}
public CustomAuthorizeAttribute(RolesEnum role) {
_role = role;
}
protected override bool AuthorizeCore(HttpContextBase httpContext) {
User currentUser = (User)httpContext.Session["CurrentUser"];
if (currentUser == null) {
return false;
}
if (currentUser.Role == RolesEnum.User && _role == RolesEnum.Admin) {
return false;
}
return true;
}
通过调用WebApi方法完成认证
[HttpPost]
public ActionResult Login(string username, string password)
{
User acc = new User();
acc.Username = username;
acc.Password = password;
acc = accBL.Login(acc);
if (acc != null) {
Session.Add("CurrentUser", acc);
return RedirectToAction("Index", "Project", null);
} else {
return View();
}
}
登录方法如下所示
public User LogIn(User acc) {
try {
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync("api/Account/Login", acc).Result;
if (response.IsSuccessStatusCode) {
return response.Content.ReadAsAsync<User>().Result;
} else {
return null;
}
} catch {
return null;
}
}
WebApi方法是这样的
[Route("api/Account/Login")]
[HttpPost]
public IHttpActionResult Login(User userModel) {
User user = db.Users.Where(p => p.Username == userModel.Username && p.Password == userModel.Password).FirstOrDefault();
if (user != null) {
return Ok(user);
} else {
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
}
如何在MVC应用程序和WebApi服务之间建立连接?我的授权和身份验证工作在MVC部分,但我的WebApi服务可以调用没有任何授权/身份验证。根据我的例子,我如何保护我的WebApi ?我已经用MVC和WebApi工作了大约3周,很多事情对我来说都不是很清楚。
我应该只是创建一个GUID在公共IHttpActionResult登录(用户userModel),并检查它每次我的方法被调用?我如何将此GUID传递到MVC应用程序和从MVC到WebApi?
您可以做的是创建某种令牌(例如:JWT)在WebAPI Login()
方法中,并返回Ok()
响应(对MVC应用程序)。调用您的API端点的用户必须将此令牌发回(例如:在自定义的"Token"头中)。您可以在API端点中使用的自定义WebAPI授权属性中验证令牌。
。
<登录端点/strong>
[Route("api/Account/Login")]
[HttpPost]
public object Login(User userModel) {
User user = ...;
string token = CreateTokenForUser(user);
if (user != null) {
// return user and token back
return new {User = user, Token = token};
} else {
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
}
自定义认证过滤器
public class UserAuthAttribute : ActionFilterAttribute, IAuthenticationFilter
{
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
string token = null;
IEnumerable<string> tokenHeader;
if (context.Request.Headers.TryGetValues("Token", out tokenHeader))
token = tokenHeader.FirstOrDefault();
if (token != null && IsTokenValid(token)
{
// user has been authenticated i.e. send us a token we sent back earlier
}
else
{
// set ErrorResult - this will result in sending a 401 Unauthorized
context.ErrorResult = new AuthenticationFailureResult(Invalid token", context.Request);
}
}
}
其他只允许认证用户访问的端点
[Route("api/Values")]
[HttpGet]
[UserAuth]
public object GetValues() {
// only requests with a valid token will be able to call this because of the [UserAuth] attribute
}