private void ConfigureOAuth(IAppBuilder app, OAuthAuthorizationServerProvider authorizationServerProvider) { var oAuthServerOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = authorizationServerProvider }; app.UseOAuthAuthorizationServer(oAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); }
public void Configuration(IAppBuilder app) { var oauthProvider = new OAuthAuthorizationServerProvider { OnGrantResourceOwnerCredentials = async context => { var isValid = true; if (isValid) { var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType); claimsIdentity.AddClaim(new Claim("user", context.UserName)); context.Validated(claimsIdentity); return; } context.Rejected(); }, OnValidateClientAuthentication = async context => { string clientId; string clientSecret; if (context.TryGetBasicCredentials(out clientId, out clientSecret)) { if (clientId == "a" && clientSecret == "a") context.Validated(); } } }; var oauthOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), Provider = oauthProvider, AuthorizationCodeExpireTimeSpan = TimeSpan.FromMinutes(1), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1440), SystemClock = new SystemClock() }; app.UseOAuthAuthorizationServer(oauthOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); }
public void Configuration(IAppBuilder app) { app.UseCors(CorsOptions.AllowAll); var myProvider = new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerProvider(); OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60), Provider = myProvider, RefreshTokenProvider = new RefreshTokenProvider() }; app.UseOAuthAuthorizationServer(options); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); HttpConfiguration config = new HttpConfiguration(); WebApiConfig.Register(config); }
public void Configuration(IAppBuilder app) { var oauthProvider = new OAuthAuthorizationServerProvider { OnGrantResourceOwnerCredentials = async context => { if (context.UserName == "filip" && context.Password == "xxx") { var claimsIdentity = new ClaimsIdentity(context.Options.AuthenticationType); claimsIdentity.AddClaim(new Claim("user", context.UserName)); context.Validated(claimsIdentity); return; } context.Rejected(); }, OnValidateClientAuthentication = async context => { string clientId; string clientSecret; if (context.TryGetBasicCredentials(out clientId, out clientSecret)) { if (clientId == "filipClient" && clientSecret == "secretKey") { context.Validated(); } } } }; var oauthOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/accesstoken"), Provider = oauthProvider }; app.UseOAuthAuthorizationServer(oauthOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); var config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); app.UseWebApi(config); }
/// <summary> /// Web API配置。 /// </summary> /// <param name="app">应用程序启动对象</param> public void Configuration(IAppBuilder app) { app.MapSignalR(); app.UseAutofacMiddleware(AutofacConfig.Container); // 自定义OAuth验证提供者实现。 var oauthProvider = new OAuthAuthorizationServerProvider { // Web API用户访问权限认证处理。 OnGrantResourceOwnerCredentials = context => { using (var container = AutofacConfig.Container.BeginLifetimeScope()) { var userService = container.Resolve<IUserService>(); if (userService != null) { if (context != null) { var account = userService.ValidateAccount(context.UserName, context.Password); if (!account.IsSuccess) { context.SetError("未知错误", account.ErrorMessage); } else { if (account.Data == null) { context.SetError("无效账号", "登录账号或者密码错误!"); } else if (account.Data.Status == 2) { context.SetError("无效账号", "您的账户已经被管理员禁用!"); } else { var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, $"{account.Data.Id},{account.Data.Account},{account.Data.Account}")); identity.AddClaim(new Claim("sub", account.Data.Id.ToString())); identity.AddClaim(new Claim("role", "user")); context.Validated(identity); context.Request.Context.Authentication.SignIn(identity); } } } } return Task.FromResult(0); } }, // 验证客户端访问权限。 OnValidateClientAuthentication = context => { context.Validated(); return Task.FromResult(0); } }; var oauthServerOptions = new OAuthAuthorizationServerOptions { Provider = oauthProvider, AllowInsecureHttp = true, SystemClock = new SystemClock(), TokenEndpointPath = new PathString("/api/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(365), // 默认Token过期时间为365天 AuthorizationCodeExpireTimeSpan = TimeSpan.FromDays(365) }; app.UseOAuthAuthorizationServer(oauthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); var config = new HttpConfiguration { DependencyResolver = new AutofacWebApiDependencyResolver(AutofacConfig.Container) }; // Web Api配置。 WebApiConfig.Register(config); app.UseWebApi(config); app.UseAutofacWebApi(config); app.UseCors(CorsOptions.AllowAll); }
private void LookupClient(OAuthAuthorizationServerProvider provider, string knownClientId, string knownClientSecret, string knownRedirectUri) { provider.OnValidateClientRedirectUri = ctx => { LastLookupClientId = ctx.ClientId; if (string.Equals(ctx.ClientId, knownClientId, StringComparison.Ordinal)) { ctx.Validated(knownRedirectUri); } return Task.FromResult(0); }; provider.OnValidateClientAuthentication = ctx => { string clientId; string clientSecret; if (ctx.TryGetBasicCredentials(out clientId, out clientSecret) || ctx.TryGetFormCredentials(out clientId, out clientSecret)) { LastLookupClientId = clientId; if (string.Equals(clientId, knownClientId, StringComparison.Ordinal) && string.Equals(clientSecret, knownClientSecret, StringComparison.Ordinal)) { ctx.Validated(clientId); } } return Task.FromResult(0); }; }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") }); // Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); #region ServerOAuth app.UseOAuthBearerAuthentication(new Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationOptions () { AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active, AuthenticationType = "Emad", Realm = "EHM" //anything }); var options = new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions(); options.TokenEndpointPath = new PathString("/account/token"); options.AuthorizeEndpointPath = new PathString("/account/auth"); options.AllowInsecureHttp = true; //Don't do that!! always be on secure scheme, this is set to "true" for demo purposes var provider = new OAuthAuthorizationServerProvider(); provider.OnValidateClientRedirectUri = (context) => { return Task.Run(() => { //Caution: this is not to validate that the uri is valid syntax wise, this is to validate it business wise. If this uri is not //valid syntax wise this entry will not be hit in the first place, and your authentication process will not work! context.Validated(); }); }; provider.OnValidateAuthorizeRequest = (context) => { return Task.Run(() => { //Authorization validation here //Somewhere in the request you should create the identity and sign in with it, I put it here, it could be a page on your app? context.OwinContext.Authentication.SignIn(new System.Security.Claims.ClaimsIdentity("Bearer")); context.Validated(); }); }; provider.OnAuthorizeEndpoint = (context) => { return Task.Run(() => { //This is the last chance to alter the request, you can either end it here using RequestCompleted and start resonding, //or you can let it go through to the subsequent middleware, //except that you have to make sure the response returns a 200, otherwise the whole thing will not work context.RequestCompleted(); var str = context.Options.AccessTokenFormat; }); }; provider.OnValidateClientAuthentication = (context) => { return Task.Run(() => { //Client validation here context.Validated(); }); }; options.Provider = provider; AuthenticationTokenProvider authTokenProvider = new AuthenticationTokenProvider(); authTokenProvider.OnCreate = (context) => { //create a dummy token context.SetToken("MyTokenblablabla"); }; //This is called when a client is requesting with Authorization header and passing the token, like this "Authorization: Bearer jdksjkld" authTokenProvider.OnReceive = (context) => { //create dummy identity regardless of the validty of the token :) var claimsIdentity = new System.Security.Claims.ClaimsIdentity("Bearer"); claimsIdentity.AddClaim(new Claim("something", "Ahmad")); //This claim type "something" is used for protection from anti-forgery... //Check the Global.asax for "AntiForgeryConfig.UniqueClaimTypeIdentifier = "something";" //you can avoid setting this, but you have to use the default claims type. check http://bartwullems.blogspot.com.au/2013/09/aspnet-mvc-4-error-when-using-anti.html context.SetTicket(new Microsoft.Owin.Security.AuthenticationTicket(claimsIdentity, new Microsoft.Owin.Security.AuthenticationProperties { ExpiresUtc = new System.DateTimeOffset(2015, 3, 1, 1, 1, 1, new System.TimeSpan()), } )); }; options.AuthorizationCodeProvider = authTokenProvider; options.RefreshTokenProvider = authTokenProvider; options.AccessTokenProvider = authTokenProvider; app.UseOAuthBearerTokens(options); #endregion //app.UseGoogleAuthentication(); }