我坚持这个问题。我在客户端使用angular,在服务器端使用EF和mvc。我想用Authorize属性保护我的Dashboard Controller。所以说清楚,当我拿到我的仪表板控制器[授权]属性并且我注册时......我立即被重定向到登录页面,因为User.Identity为空。我在chrome开发人员工具中注意到它没有发送带有请求的Bearer令牌。
当我从Dashboard控制器中删除authorize属性并且我想使用[Authorize] attribut甚至使用角色保护来激活我的任何受保护API控制器时,一切正常,因为在每个请求中我都会看到我的Bearer令牌被发送并且我的User.Identity已通过凭据完成。
我错过了控制器无法接收Bearer jwt令牌和ApiControllers的东西吗?我被困在它上面超过6小时并且无法弄清楚,为什么当我想要使用受保护的Dashboard控制器时,我的令牌不会被发送,但每当我想使用任何其他控制器和方法时,一切都很好
[CustomAuthorize]
public class DashboardController : Controller
{
// GET: Dashboard
public ActionResult Index()
{
return View();
}
}
我创建了CustomAuthorize类,看看我是否在User.Identity中获得了一些东西,但是一切都是null
public class CustomAuthorize : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectResult("/");
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (this.AuthorizeCore(filterContext.HttpContext))
{
base.OnAuthorization(filterContext);
}
else
{
this.HandleUnauthorizedRequest(filterContext);
}
}
}
这是我的启动方法,我强制控制器验证jwt令牌
private void ConfigureOAuthTokenConsumption(IAppBuilder app)
{
var issuer = "http://localhost:2969";
string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];
byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:AudienceSecret"]);
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audienceId },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
}
});
}
带有路由和拦截器的主角度模块,用于将我的令牌推送到每个请求中
var app = angular.module(moduleName, ["ngRoute", "ngResource", 'ui.bootstrap', "signalR" ])
.config(function ($routeProvider, $compileProvider, $httpProvider) {
'use strict';
$httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
$httpProvider.interceptors.push(['$q', 'currentUser', '$location', function ($q, currentUser) {
return {
'request': function (config) {
//if (currentUser.profile.loggedIn) {
config.headers.Authorization = "Bearer " + currentUser.profile.Token;
//}
return config;
},
'responseError': function (response) {
if (response.status == 401 || response.status == 403) {
window.location = "/";
}
return $q.reject(response);
}
};
}]);
$compileProvider.debugInfoEnabled(true);
$routeProvider
.when("/", {
templateUrl: "app/components/views/index.html"
})
答案 0 :(得分:0)
好的,所以我想出了WebApiConfig类的Register方法,不知怎的那两种方法删除标题内容
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//Delete both of those methods to make JWT authentication accept JWT tokens, at least it was the problem in my case
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
}
}