为了让 MVC 了解有关您的 JWT 的任何信息,您基本上必须告诉它 :-)。首先,从 nuget 安装 Jwt 包:
Install-Package Microsoft.Owin.Security.Jwt
然后打开您的 Startup.cs 文件并添加一个新函数,该函数将告诉 MVC 如何使用 JWT。在基础上,您的 Startup 将类似于:
using System.Configuration;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler.Encoder;
using Microsoft.Owin.Security.Jwt;
using Owin;
[assembly: OwinStartupAttribute(typeof(TOMS.Frontend.Startup))]
namespace TOMS.Frontend
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
ConfigureOAuthTokenConsumption(app);
}
private void ConfigureOAuthTokenConsumption(IAppBuilder app)
{
var issuer = ConfigurationManager.AppSettings["Issuer"];
var audienceId = ConfigurationManager.AppSettings["AudienceId"];
var audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["AudienceSecret"]);
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audienceId },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
}
});
}
}
}
您会注意到我在我的 Web.config 文件中放置了颁发者、受众 ID 和受众秘密。 (这些值应该与您的资源服务器上的值匹配)。此外,您可能希望确保运行更新的 System.IdentityModel.Tokens.Jwt:
Update-package System.IdentityModel.Tokens.Jwt
通过这些设置,您可以使用 [Authorize] 属性装饰您的控制器动作并玩球。
玩球当然意味着将您的请求从您的 javascript 触发到受保护的控制器操作:
//assuming you placed the token in a sessionStorage variable called tokenKey when it came back from your Authorization Server
var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
headers.Authorization = 'Bearer ' + token;
}
$.ajax({
type: 'GET',
url: 'CONTROLLER/ACTION',
headers: headers
}).done(function (data) {
self.result(data);
}).fail(showError);
更新
顺便说一句,如果您希望在 web.config 文件中添加值以便像我上面那样检索它们;只需在 AppSettings 下添加它们:
<configuration>
<appSettings>
<add key="Issuer" value="YOUR_ISSUER" />
<add key="AudienceId" value="YOUR_AUDIENCEID" />
<add key="AudienceSecret" value="YOUR_AUDIENCESECRET" />
</appSettings>
</configuration>
...当然,用你自己的替换“值”