我已经使用JWT实现了基于JWT Nuget令牌的身份验证/授权,并且按预期工作。能够创建令牌并使用如下所示的filter属性来验证令牌
public class JWTAuthentication : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
try
{
if (actionContext.ActionDescriptor.GetCustomAttributes<IgnoreJWTAuthenticationAttribute>().Any())
return;
IEnumerable<string> authHeaderValues;
actionContext.Request.Headers.TryGetValues("Authorization", out authHeaderValues);
if (authHeaderValues == null)
{
actionContext.Response = UnAuthorisedResponse(actionContext, "Authorization header cannot be empty");
return;
}
var bearerToken = authHeaderValues.ElementAt(0);
var token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken;
Thread.CurrentPrincipal = JWTAuthToken.JWTAuth().ValidateToken(token, true);
if (HttpContext.Current != null)
{
HttpContext.Current.User = Thread.CurrentPrincipal;
}
}
catch (Exception ex)
{
actionContext.Response = UnAuthorisedResponse(actionContext, ex.Message);
}
}
public System.Net.Http.HttpResponseMessage UnAuthorisedResponse(HttpActionContext actionContext, string message)
{
return actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, message);
}
}
public class JWTAuthorization : System.Web.Http.Filters.ActionFilterAttribute
{
private string roles;
public JWTAuthorization(string roles)
{
this.roles = roles;
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
var tempRoles = roles.Split(',').ToList();
var userIdentity = (ClaimsIdentity)HttpContext.Current.User.Identity;
var userRoles = Roles(userIdentity);
if (!tempRoles.Intersect(userRoles).Any())
{
actionContext.Response = UnAuthorisedResponse(actionContext, "UnAuthorized Access");
}
}
public System.Net.Http.HttpResponseMessage UnAuthorisedResponse(HttpActionContext actionContext, string message)
{
return actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, message);
}
private List<string> Roles(ClaimsIdentity identity)
{
return identity.Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => c.Value)
.ToList();
}
}
我们正在为具有公共用户数据库的多个应用程序提供API。因此,我们想将身份验证API(例如创建令牌,验证令牌)与业务应用程序API分开。但是我们不确定该怎么做?
也许我们可以在服务器上创建令牌,并使用相同的密钥在托管业务API的服务器上验证令牌。但是这里还是必须在所有业务应用程序API上实现验证逻辑。
请帮助我们将身份验证/授权与业务API分开。在业务应用程序API上,我们如何确保它是经过身份验证的调用并允许访问资源?