新的依賴注入,所以這可能是一件簡單的事情,但我已經嘗試過,無法弄清楚,我正在使用簡單注入器。依賴注入(使用SimpleInjector)和OAuthAuthorizationServerProvider
我有一個WebApi,使用SimpleInjector完美罰款,現在我想實現安全使用OAuth。
要做到這一點,我開始學習本教程,這是非常有益的,但犯規利用扶養注射
http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
我有我的Global.asax文件看起來像這樣,設置扶養注射液(工作完美)
protected void Application_Start()
{
SimpleInjectorConfig.Register();
GlobalConfiguration.Configure(WebApiConfig.Register);
}
我創建了一個Startup.Auth.cs文件來配置的OAuth
public class Startup
{
public void Configuration(IAppBuilder app)
{
var OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new MyAuthorizationServerProvider() // here is the problem
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
現在,正如我上面評論,MyAuthorizationServerProvider是問題。它需要我通常注入的IUserService參數。我不想清空構造函數,因爲我的IUserService還會注入一個存儲庫。這裏是文件
public class ApiAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
private IUserService _service;
public ApiAuthorizationServerProvider (IUserService service)
{
_service = service;
}
public override async Task ValidateClientAuthentication(
OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(
OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",
new[] { "*" });
IUserService service = Startup.Container.GetInstance<IUserService>();
User user = _service.Query(e => e.Email.Equals(context.UserName) &&
e.Password.Equals(context.Password)).FirstOrDefault();
if (user == null)
{
context.SetError("invalid_grant",
"The user name or password is incorrect.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
}
我怎麼能得到這與依賴注入工作?這一定會發生很多,必須能夠做一些事情來處理它。我相信它很簡單,但我仍然在學習。
希望這有助於https://simpleinjector.codeplex。 com/discussion/564822 – DSR 2014-09-23 14:25:32
您是否找到其他解決方案? – moyomeh 2016-02-22 17:15:59
我使用來自github的OpenIddict,只將角色名稱存儲爲索賠。權限未被存儲,因爲如果更新了某些內容,則更改將立即在服務器上進行。我只需要檢查一次請求的權限,所以這對我來說很好atm – Gillardo 2016-02-22 20:12:57