protected override async Task <HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (!CanHandleAuthentication(request)) { return(await base.SendAsync(request, cancellationToken)); } string UserId = ""; string UserRole = ""; string UserName = ""; UserId = GetItemFromHeader(request, "UserId"); UserRole = GetItemFromHeader(request, "UserRole"); UserName = GetItemFromHeader(request, "UserName"); string token = jwtAuthenticationService.CreateToken(UserId, UserRole, UserName, Issuer, Audience); var response = await base.SendAsync(request, cancellationToken); //新token由UserName和token构成,方便验证时取得用户所对应密钥。 string newToken = UserName + ":" + token; response = jwtAuthenticationService.WriteTokenToResponse(response, newToken); response.StatusCode = HttpStatusCode.OK; return(response); }
protected override async Task <HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (!CanHandleAuthentication(request)) { return(await base.SendAsync(request, cancellationToken)); } string[] items = GetItem(request.Headers.Authorization); ClaimsPrincipal cprincipal = HttpContext.Current.User as ClaimsPrincipal; string rolesString = cprincipal.Claims.FirstOrDefault(p => p.Type == "Roles").Value; string userID = cprincipal.Claims.FirstOrDefault(p => p.Type == ClaimTypes.NameIdentifier).Value; string[] roles = rolesString.Split(RoleSeparator); string newToken; if (roles.Contains(items[UserRoleIndex])) { newToken = jwtSecurityService.CreateToken(userID, items[UserRoleIndex], items[UsernameIndex], Issuer, Audience); } else { return(CreateChangeErrorResponse()); } var response = new HttpResponseMessage(); newToken = items[UsernameIndex] + ":" + newToken; jwtSecurityService.WriteTokenToResponse(response, newToken); return(response); }