JSON Web Token(JWT)是一个开放式标准(RFC 7519),它定义了一种紧凑且自包含的方式,用于在各方之间以JSON对象安全传输信息。这些信息可以通过数字签名进行验证和信任。可以使用秘密(使用HMAC算法)或使用RSA的公钥/私钥对对JWT进行签名。
实列讲解
如上图所示引入对应得Nuget包。
在项目中创建 Startup.cs 文件,添加如下代码:
///
/// Startup
///
public class Startup
{
private readonly HttpConfiguration _httpConfig;
///
/// Initializes a new instance of the class.
///
public Startup()
{
_httpConfig = new HttpConfiguration();
}
///
/// Configurations the specified application.
///
/// The application.
public void Configuration(IAppBuilder app)
{
ConfigureOAuthTokenGeneration(app);
ConfigureOAuthTokenConsumption(app);
}
//配置token生成
private void ConfigureOAuthTokenGeneration(IAppBuilder app)
{
var oAuthServerOptions = new OAuthAuthorizationServerOptions
{
//TODO:For Dev enviroment only (on production should be AllowInsecureHttp = false)
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/token"),//获取token请求地址
AccessTokenExpireTimeSpan = TimeSpan.FromDays(5),//token过期时间
Provider = new SimpleOAuthProvider(),//token生成服务
AccessTokenFormat = new SimpleJwtFormat()//token生成Jwt格式
};
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
//配置token使用
private void ConfigureOAuthTokenConsumption(IAppBuilder app)
{
var issuer = ConfigurationManager.AppSettings["oauth:Issuer"];
var audienceIds = ConfigurationManager.AppSettings["oauth:Audiences"];
var audienceSecrets = ConfigurationManager.AppSettings["oauth:Secrets"];
var allowedAudiences = audienceIds.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries);
var base64Keys = audienceSecrets.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries);
var keys = base64Keys.Select(s => TextEncodings.Base64Url.Decode(s)).ToList();
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = allowedAudiences,
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, keys)
},
Provider = new SimpleOAuthBearerAuthenticationProvider("access_token")
});
}
}
SimpleOAuthProvider示例代码:
public class SimpleOAuthProvider : OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId;
string clientSecret;
if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
context.TryGetFormCredentials(out clientId, out clientSecret);
var authDbContext = new ExternalInterfaceBaseDbContext();
ICustomerRepository customerRepository = new CustomerRepository(authDbContext);
if (context.ClientId == null)
{
context.SetError("invalid_client", "The client_id is not set.");
return Task.FromResult
public class SimpleJwtFormat : ISecureDataFormat
{
private const string AudiencePropertyKey = "audience";
private readonly string _issuer;
private readonly string _audienceSecrets;
public SimpleJwtFormat()
{
_issuer = ConfigurationManager.AppSettings["oauth:Issuer"];
_audienceSecrets = ConfigurationManager.AppSettings["oauth:Secrets"];
}
public string Protect(AuthenticationTicket data)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
var properties = data.Properties;
var propertityDictionary = properties.Dictionary;
var audienceId = propertityDictionary.ContainsKey(AudiencePropertyKey)
? propertityDictionary[AudiencePropertyKey]
: null;
if (string.IsNullOrWhiteSpace(audienceId))
throw new InvalidOperationException("AuthenticationTicket.Properties does not include audience.");
if (properties.IssuedUtc == null)
throw new InvalidOperationException("AuthenticationTicket.Properties does not include issued.");
if (properties.ExpiresUtc == null)
throw new InvalidOperationException("AuthenticationTicket.Properties does not include expires.");
var issued = properties.IssuedUtc.Value.UtcDateTime;
var expires = properties.ExpiresUtc.Value.UtcDateTime;
//TODO:
//var authDbContext = new InstrumentDbContext();
//var audienceRepository = new AudienceRepository(authDbContext);
//var audience = audienceRepository.Get(audienceId);
var decodedSecret = TextEncodings.Base64Url.Decode(_audienceSecrets);
var signingCredentials = new HmacSigningCredentials(decodedSecret);
var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued, expires,
signingCredentials);
var handler = new JwtSecurityTokenHandler();
var jwt = handler.WriteToken(token);
return jwt;
}
}
根据授权Id生成Jwt Token返回。
SimpleOAuthBearerAuthenticationProvider 示例代码:
public class SimpleOAuthBearerAuthenticationProvider : OAuthBearerAuthenticationProvider
{
private readonly string _accessTokenName;
public SimpleOAuthBearerAuthenticationProvider(string accessTokenName)
{
_accessTokenName = accessTokenName;
}
public override Task RequestToken(OAuthRequestTokenContext context)
{
var token = context.Request.Query.Get(_accessTokenName);
if (!string.IsNullOrEmpty(token))
context.Token = token;
return Task.FromResult(null);
}
}
配置AccessToken使用。
到这里权限认证代码基本完成,最后就是在控制器或者方法上配置权限控制特性 [Authorize]。
[Authorize]
[RoutePrefix("api/areas")]
public class AreaController : ApiController
这样Web Api Owin + Oauth2.0 + Jwt Token 的权限认证框架就已经搭好了。
FineReport使用中遇到的常见报错及解决办法(一)
这里写点抛砖引玉,希望大家能把自己整理的问题及解决方法晾出来,Mark一下,利人利己。
出现问题先搜一下文档上有没有,再看看度娘有没有,再看看论坛有没有。有报错要看日志。下面简单罗列下常见的问题,大多文档上都有提到的。
1、address pool is full:
含义:地址池满,连接数超过并发数上
原文:http://kindlefireforkid.com/how-to-setup-a-google-account-on-amazon-fire-tablet/
Step 4: Run ADB command from your PC
On the PC, you need install Amazon Fire ADB driver and instal
本文译者:candeladiao,原文:URL filtering for UIWebView on the iPhone说明:译者在做app开发时,因为页面的javascript文件比较大导致加载速度很慢,所以想把javascript文件打包在app里,当UIWebView需要加载该脚本时就从app本地读取,但UIWebView并不支持加载本地资源。最后从下文中找到了解决方法,第一次翻译,难免有