ren*_*han 5 c# asp.net jwt angularjs asp.net-web-api2
我正在尝试在项目中实现JWT授权.但是,为了成功获取令牌,我必须将client_id从AngularJS前端传递到ASP.NET Web API后端,据我所知它根本不安全.那么有人可以给我一个提示,告诉我在我的情况下应该做些什么.
在JS方面 -
var data = 'grant_type=password&username='
+ loginData.Email + '&password=' + loginData.Password + '&client_id=' + client_id;
$http.post('/oauth2/token', data); //Code omitted
Run Code Online (Sandbox Code Playgroud)
在大多数情况下,我正在使用本指南创建Jwt授权.除了我在一个域上有一个应用程序,所以这是我的Startup.cs的样子 -
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
ConfigureOAuth(app);
ConfigureValidationOAuth(app);
}
private static void ConfigureOAuth(IAppBuilder app)
{
var oAuthServerOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth2/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new CustomOAuthProvider(),
AccessTokenFormat = new CustomJwtFormat(ConfigurationManager.AppSettings["owin:issuer"])
};
app.UseOAuthAuthorizationServer(oAuthServerOptions);
}
private static void ConfigureValidationOAuth(IAppBuilder app)
{
var issuer = ConfigurationManager.AppSettings["owin:issuer"];
var audience = ConfigurationManager.AppSettings["owin:audience"];
var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["owin:secret"]);
//Api controllers with [Authorize] attribute will be validated with Jwt
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] {audience},
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
}
});
}
Run Code Online (Sandbox Code Playgroud)
小智 2
JWT 身份验证和授权应该像这样工作:
服务器检查用户数据并生成 JWT 令牌,该令牌应采用以下格式:(查看JWT.io了解更多信息)
eyJhbGciOiJIUZI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9liiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
JWT 令牌应存储在客户端本地存储中
myApp.factory('jwt-interceptor', ['$q', '$window', function($q, $window) {
return {
request: function(request) {
request.headers['Authorization'] = 'Bearer ' + $window.localStorage.token;
return request;
},
responseError: function(response) {
return $q.reject(response);
}
};
}]).config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('jwt-interceptor');
}]);
服务器应该读取名为 的标头参数Authorization,反编译令牌并检查有效负载:
A。已正确反编译且有效负载完好无损
b. 检查有效负载中的到期时间戳是否大于当前时间戳
C。其他用户权限相关检查(如果需要)
| 归档时间: |
|
| 查看次数: |
570 次 |
| 最近记录: |