public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { if (InstanceContext.UseHMACAuthentication == false) { return(Task.FromResult(0)); } var req = context.Request; log.Debug("Checking HMAC authentication. "); if (req.Headers.Authorization != null && authenticationScheme.Equals(req.Headers.Authorization.Scheme, StringComparison.OrdinalIgnoreCase)) { var rawAuthzHeader = req.Headers.Authorization.Parameter; var autherizationHeaderArray = GetAutherizationHeaderValues(rawAuthzHeader); if (autherizationHeaderArray != null) { var APPId = autherizationHeaderArray[0]; var incomingBase64Signature = autherizationHeaderArray[1]; var nonce = autherizationHeaderArray[2]; var requestTimeStamp = autherizationHeaderArray[3]; log.Debug("AppId: " + APPId); log.Debug("incomingBase64Signature: " + incomingBase64Signature); log.Debug("nonce: " + nonce); log.Debug("requestTimeStamp: " + requestTimeStamp); var isValid = isValidRequest(req, APPId, incomingBase64Signature, nonce, requestTimeStamp); if (isValid.Result) { var currentPrincipal = new GenericPrincipal(new GenericIdentity(APPId), null); context.Principal = currentPrincipal; log.Debug("Successfully authenticated as " + APPId); } else { log.Debug("Unauthorized"); context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request); } } else { context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request); } } else { log.Debug("Missing or invalid authentication headers"); if (req.Headers.Authorization == null) { log.Debug("Authentication header is null"); } else { log.Debug("Authentication header schema: " + req.Headers.Authorization.Scheme); } context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request); } return(Task.FromResult(0)); }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { }
/// <summary> /// Authenticate a request asynchronously. /// </summary> /// <param name="httpAuthenticationContext"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task AuthenticateAsync(HttpAuthenticationContext httpAuthenticationContext, CancellationToken cancellationToken) { // Account has been authenticated before token is parsed. // Skip the authentication. var principal = httpAuthenticationContext.Principal; if ((principal != null) && (principal.Identity != null) && principal.Identity.IsAuthenticated) { return(Task.FromResult(0)); } // Search the authorization in the header. var authorization = httpAuthenticationContext.Request.Headers.Authorization; // Bearer token is detected. if (authorization == null) { return(Task.FromResult(0)); } // Scheme is not bearer. if (!"Bearer".Equals(authorization.Scheme, StringComparison.InvariantCultureIgnoreCase)) { return(Task.FromResult(0)); } // Token parameter is not defined. var token = authorization.Parameter; if (string.IsNullOrWhiteSpace(token)) { return(Task.FromResult(0)); } try { // Search authentication provider from request sent from client. var bearerAuthenticationProvider = FindProviderFromRequest(httpAuthenticationContext).Result; if (bearerAuthenticationProvider == null) { return(Task.FromResult(0)); } // Decode the token and set to claim. The object should be in dictionary. var claimPairs = JsonWebToken.DecodeToObject <Dictionary <string, string> >(token, bearerAuthenticationProvider.Key); var claimIdentity = new ClaimsIdentity(null, bearerAuthenticationProvider.IdentityName); foreach (var key in claimPairs.Keys) { claimIdentity.AddClaim(new Claim(key, claimPairs[key])); } // Authenticate the request. httpAuthenticationContext.Principal = new ClaimsPrincipal(claimIdentity); } catch (Exception exception) { // Suppress error. Log.Error(exception.Message, exception); } return(Task.FromResult(0)); }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { await Task.Factory.StartNew(() => { HttpRequestMessage request = context.Request; AuthenticationHeaderValue authorization = request.Headers.Authorization; //return true; if (authorization == null) { context.ErrorResult = new AuthenticationFailureResult("Missing authorization header", request); return; } if (authorization.Scheme != "tk") { if (authorization.Scheme != "Basic") { context.ErrorResult = new AuthenticationFailureResult("Authorization scheme not supported", request); return; } } if (authorization.Scheme == "tk") { // По токену шукаємо користувача, перевіряємо його валідність, і формуємо GenericPrincipal string token = GetTokenFromBase64String(authorization.Parameter); if (token != string.Empty) { using (WDB w = new WDB()) { DataModels.VUsers user = w.User.GetUserByToken(token); if (user != null) { var identity = new GenericIdentity(user.Login, "Basic"); context.Principal = new GenericPrincipal(identity, GetRoleNamesByLogin(user.Login)); return; } else { return; } } } } if (authorization.Scheme == "Basic") { Tuple <string, string> userNameAndPasword = ExtractUserNameAndPassword(authorization.Parameter); if (userNameAndPasword == null) { context.ErrorResult = new AuthenticationFailureResult("Invalid credentials", request); } else { string login = userNameAndPasword.Item1; string password = userNameAndPasword.Item2; if (IsAuthenticated(login, password)) { var identity = new GenericIdentity(login, "Basic"); //if you need authorization as well, then fetch the roles and add it here context.Principal = new GenericPrincipal(identity, GetRoleNamesByLogin(login)); } else { context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request); } } } }); }
public async Task Authenticate(HttpAuthenticationContext context, CancellationToken cancellationToken) { // 1. Look for credentials in the request. HttpRequestMessage request = context.Request; AuthenticationHeaderValue authorization = request.Headers.Authorization; // 2. If there are no credentials, do nothing. if (authorization == null) { context.ErrorResult = new AuthenticationFailureResult("Missing credentials", request); return; } // 3. If there are credentials but the filter does not recognize the // authentication scheme, do nothing. if (!authorization.Scheme.EqualsIgnoreCase(AuthenticationScheme)) { return; } // 4. If there are credentials that the filter understands, try to validate them. // 5. If the credentials are bad, set the error result. if (string.IsNullOrEmpty(authorization.Parameter)) { context.ErrorResult = new AuthenticationFailureResult("Missing parameter", request); return; } // Validate the token and get the corresponding API key details var apiClientDetails = await OAuthTokenValidator.GetClientDetailsForTokenAsync(authorization.Parameter); if (!apiClientDetails.IsTokenValid) { context.ErrorResult = new AuthenticationFailureResult("Invalid token", request); return; } if (_expectedUseSandboxValue.Value.HasValue && apiClientDetails.IsSandboxClient != _expectedUseSandboxValue.Value.Value) { var message = apiClientDetails.IsSandboxClient ? "Sandbox credentials used in call to Production API" : "Production credentials used in call to Sandbox API"; context.ErrorResult = new AuthenticationFailureResult(message, request); return; } // Store API key details into context ApiKeyContextProvider.SetApiKeyContext( new ApiKeyContext( apiClientDetails.ApiKey, apiClientDetails.ClaimSetName, apiClientDetails.EducationOrganizationIds, apiClientDetails.NamespacePrefixes, apiClientDetails.Profiles, apiClientDetails.StudentIdentificationSystemDescriptor, apiClientDetails.CreatorOwnershipTokenId, apiClientDetails.OwnershipTokenIds)); var claimsIdentity = ClaimsIdentityProvider.GetClaimsIdentity( apiClientDetails.EducationOrganizationIds, apiClientDetails.ClaimSetName, apiClientDetails.NamespacePrefixes, apiClientDetails.Profiles.ToList()); context.Principal = new ClaimsPrincipal(claimsIdentity); }
/// <inheritdoc /> public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { return(_innerFilter.AuthenticateAsync(context, cancellationToken)); }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { ExceptionTestsUtility.CheckForThrow(_throwAt, "AuthenticationAuthenticate"); return(Task.FromResult <object>(null)); }
protected virtual void Success(HttpAuthenticationContext context, string terminalId, string userId) { return; }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { return(Task.FromResult(0)); }
//private static ManagersProvider AnonymousManagersProvider = new ManagersProvider(); Task IAuthenticationFilter.AuthenticateAsync(HttpAuthenticationContext context, System.Threading.CancellationToken cancellationToken) { var task = Task.FromResult(0); //var routeData = context.ActionContext.ControllerContext.RequestContext.RouteData; //AccessToken data = null; //string msg_signature = HttpContext.Current.Request.QueryString["msg_signature"]; //string timestamp = HttpContext.Current.Request.QueryString["timestamp"]; //string nonce = HttpContext.Current.Request.QueryString["nonce"]; //// Override the authentication if POST from WeChat to server of enterprise //if ((!string.IsNullOrEmpty(msg_signature)) && !string.IsNullOrEmpty(timestamp) && !string.IsNullOrEmpty(nonce) && HttpContext.Current.Request.HttpMethod == "POST") //{ // var bytes = new byte[HttpContext.Current.Request.InputStream.Length]; // HttpContext.Current.Request.InputStream.Read(bytes, 0, bytes.Length); // HttpContext.Current.Request.InputStream.Position = 0; // string requestInput = Encoding.UTF8.GetString(bytes); // string token = ConfigurationManager.AppSettings["WeChatToken"]; // string encodingAESKey = ConfigurationManager.AppSettings["WeChatEncodingAESKey"]; // string corpId = ConfigurationManager.AppSettings["WeChatCorpId"]; // string result = string.Empty; // WeChatCallbackMessageCrypt encrypt = new WeChatCallbackMessageCrypt(token, encodingAESKey, corpId); // int veryfyResult = encrypt.DecryptMsg(msg_signature, timestamp, nonce, requestInput, ref result); // if (string.IsNullOrEmpty(result)) // { // LogHelper.LogInformation("AuthenticateAsync: result is null!"); // } // if (veryfyResult != (int)WeChatCallbackMessageCryptErrorCode.WeChatCallbackMessageCrypt_OK) // { // LogHelper.LogInformation("AuthenticateAsync: ErrorCode: " + veryfyResult.ToString()); // } // XElement element = XElement.Parse(result); // string userWeChatId = element.Element("FromUserName").Value.Trim(); // string eventKey = element.Element("EventKey").Value.Trim(); // if (!AnonymousManagersProvider.UserManager.LoginFromWeChat(corpId, userWeChatId, eventKey).Status) // { // context.ErrorResult = new UnauthorizedWithTextActionResult(new List<AuthenticationHeaderValue> { }, context.Request) { Message = "非法访问" }; // return task; // } // var user = AnonymousManagersProvider.UserManager.GetByWeChatId(userWeChatId); // var identity = new CustomizeIdentity(user.LoginName); // identity.CorporationId = 0; // identity.CommodityList = new CommodityManager(new UserInfo() { CorporationId = 0, UserId = user.WFUserId, Username = user.LoginName }).List().Select(p => p.WFCommodityId).ToList(); // var userManager = new UserManager(new UserInfo() { UserId = user.WFUserId, Username = user.LoginName }); // var accountEnityList = userManager.GetUserAccountEntity(); // var accountEntityIdList = accountEnityList == null ? null : accountEnityList.Select(r => r.WFAccountEntityId).ToList(); // identity.AccountList = accountEntityIdList; // identity.UserType = user.UserType.Value; // identity.UserId = user.WFUserId; // context.Principal = new CustomizePrincile(identity, null); // return task; //} //var qs = context.ActionContext.Request.GetQueryNameValuePairs(); //if (!qs.Any(m => "access_token".Equals(m.Key, StringComparison.InvariantCultureIgnoreCase))) //{ // context.ErrorResult = new UnauthorizedWithTextActionResult(new List<AuthenticationHeaderValue> { }, context.Request) { Message = "非法访问" }; // return task; //} //if (AccessToken.TryParse(qs.First(m => "access_token".Equals(m.Key, StringComparison.InvariantCultureIgnoreCase)).Value, out data)) //{ // if (!data.IsValid()) // { // context.ErrorResult = new UnauthorizedWithTextActionResult(new List<AuthenticationHeaderValue> { }, context.Request) { Message = "登录信息已过期,请重新登录" }; // return task; // } // JavaScriptSerializer jss = new JavaScriptSerializer(); // var userId = int.Parse(data.UserId); // var identity = new CustomizeIdentity(AnonymousManagersProvider.UserManager.GetById(userId).LoginName); // identity.CorporationId = Convert.ToInt32(data.CorporationId); // if (!string.IsNullOrWhiteSpace(data.CommodityList)) identity.CommodityList = (ICollection<int>)jss.Deserialize(data.CommodityList, typeof(IEnumerable<int>)); // identity.AccountList = string.IsNullOrWhiteSpace(data.AccountList) ? null : (List<int>)jss.Deserialize(data.AccountList, typeof(IEnumerable<int>)); // identity.UserType = int.Parse(data.UserType); // identity.UserId = int.Parse(data.UserId); // context.Principal = new CustomizePrincile(identity, null); //} //else //{ // context.ErrorResult = new UnauthorizedWithTextActionResult(new List<AuthenticationHeaderValue> { }, context.Request) { Message = "未授权访问" }; //} return(task); }
public static Token GetToken(this HttpAuthenticationContext context) { return(context.Request.GetToken()); }
public virtual Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { return(Task.FromResult <object>(null)); }
public override Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { context.ErrorResult = new AuthenticationErrorResult(context.ActionContext); return(Task.FromResult <object>(null)); }
public override Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { TryThrowHttpResponseException(context.ActionContext); throw new ArgumentException("authentication"); }
public Task AuthenticateAsync(HttpAuthenticationContext context, System.Threading.CancellationToken cancellationToken) { if (!IsHmacEnabled) { var claims = new List <Claim>() { new Claim(ClaimTypes.Name, "0") }; context.Principal = new ClaimsPrincipal( new[] { new ClaimsIdentity(claims, SignatureProvider.SignatureScheme) }); return(Task.FromResult(0)); } var request = context.Request; var authorization = request.Headers.Authorization; if (authorization == null || authorization.Scheme != SignatureProvider.SignatureScheme) { return(Task.FromResult(0)); } if (string.IsNullOrWhiteSpace(authorization.Parameter)) { context.ErrorResult = new AuthenticationFailureResult("Authorization token missing from header", request); return(Task.FromResult(0)); } if (!request.Headers.Contains(SignatureProvider.UserIDHeader)) { context.ErrorResult = new AuthenticationFailureResult(string.Format("User ID header {0} missing", SignatureProvider.UserIDHeader), request); return(Task.FromResult(0)); } var userId = request.Headers.GetValues(SignatureProvider.UserIDHeader).FirstOrDefault(); if (string.IsNullOrEmpty(userId)) { context.ErrorResult = new AuthenticationFailureResult(string.Format("User ID missing from header value {0}", SignatureProvider.UserIDHeader), request); return(Task.FromResult(0)); } var key = SecretProvider.GetSignatureSecretKey(userId); if (string.IsNullOrEmpty(key)) { context.ErrorResult = new AuthenticationFailureResult("Unknown User ID", request); return(Task.FromResult(0)); } var uri = request.RequestUri.ToString().ToLowerInvariant(); var stripProtocol = SecretProvider.GetProtocolStripList().Any(site => uri.Contains(site)); var success = SignatureProvider.HasValidSignature(request, userId, key, TimeOutPeriod, stripProtocol); //success = true; if (!success) { var sig = SignatureProvider.CreateSignature(request, key, stripProtocol); var diagnostic = string.Format("Diagnostic info follows. Signature: {0}, attached sig: {1}, method: {2}, URI: {3}, content: {4}, Request time stamp:{5}, Server time stamp:{6}, User: {7}, Auth: {8}", sig, request.Headers.Authorization.Parameter, request.Method, request.RequestUri, request.Content != null ? request.Content.ReadAsStringAsync().Result : "", request.Headers.Date == null ? "" : request.Headers.Date.Value.ToUniversalTime().ToString("r"), DateTime.Now.ToUniversalTime().ToString("r"), request.Headers.GetValues(SignatureProvider.UserIDHeader).FirstOrDefault(), request.Headers.Authorization.Scheme); context.ErrorResult = new AuthenticationFailureResult("Invalid or expired signature. " + diagnostic, request); } else { var claims = new List <Claim>() { new Claim(ClaimTypes.Name, userId) }; context.Principal = new ClaimsPrincipal( new[] { new ClaimsIdentity(claims, SignatureProvider.SignatureScheme) }); } //Place user id in context for later use context.ActionContext.Request.Properties.Add(UserIdField, userId); return(Task.FromResult(0)); }
/// <summary>ユーザ情報を取得する</summary> /// <param name="authenticationContext">HttpAuthenticationContext</param> private async Task GetUserInfoAsync(HttpAuthenticationContext authenticationContext) { // カスタム認証処理 -------------------------------------------- // Authorization: Bearer ヘッダから // JWTアサーションを処理し、認証、UserInfoを生成するなど。 // ------------------------------------------------------------- List <Claim> claims = null; if (authenticationContext.Request.Headers.Authorization != null) { if (authenticationContext.Request.Headers.Authorization.Scheme.ToLower() == "bearer") { string access_token = authenticationContext.Request.Headers.Authorization.Parameter; string sub = ""; List <string> roles = null; List <string> scopes = null; JObject jobj = null; if (AccessToken.Verify(access_token, out sub, out roles, out scopes, out jobj)) { // ActionFilterAttributeとApiController間の情報共有はcontext.Principalを使用する。 // ★ 必要であれば、他の業務共通引継ぎ情報などをロードする。 claims = new List <Claim>() { new Claim(ClaimTypes.Name, sub), new Claim(ClaimTypes.Role, string.Join(",", roles)), new Claim(OAuth2AndOIDCConst.Claim_Scopes, string.Join(",", scopes)), new Claim(OAuth2AndOIDCConst.Claim_Audience, (string)jobj[OAuth2AndOIDCConst.aud]), new Claim("IpAddress", MyBaseAsyncApiController.GetClientIpAddress(authenticationContext.Request)) }; // The request message contains valid credential. authenticationContext.Principal = new ClaimsPrincipal(new List <ClaimsIdentity> { new ClaimsIdentity(claims, "Token") }); return; } else { // JWTの内容検証に失敗 } } else { // Authorization HeaderがBearerでない。 } } else { // Authorization Headerが存在しない。 } #region 未認証状態の場合の扱い // The request message contains invalid credential. //context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request); // 未認証状態のclaimsを作成格納 claims = new List <Claim>() { new Claim(ClaimTypes.Name, "未認証"), new Claim(ClaimTypes.Role, ""), new Claim(OAuth2AndOIDCConst.Claim_Scopes, ""), new Claim(OAuth2AndOIDCConst.Claim_Audience, ""), new Claim("IpAddress", MyBaseAsyncApiController.GetClientIpAddress(authenticationContext.Request)) }; authenticationContext.Principal = new ClaimsPrincipal(new List <ClaimsIdentity> { new ClaimsIdentity(claims, "Token") }); return; #endregion }
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { throw new NotImplementedException(); }
/// <summary> /// プロセスが承認を要求したときに呼び出します。 /// https://msdn.microsoft.com/ja-jp/library/dn314618.aspx /// https://msdn.microsoft.com/ja-jp/magazine/dn781361.aspx /// </summary> /// <param name="authenticationContext">HttpAuthenticationContext</param> /// <param name="cancellationToken">CancellationToken</param> public async Task AuthenticateAsync(HttpAuthenticationContext authenticationContext, CancellationToken cancellationToken) { // 認証ユーザ情報をメンバにロードする await this.GetUserInfoAsync(authenticationContext); }
private T GetService <T>(HttpAuthenticationContext context) { return((T)context.ActionContext.ControllerContext.Configuration.DependencyResolver.GetService(typeof(T))); }
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { // implement authentication code, setup something - setup Principal Helper.Write("AuthenticationFilter", context.ActionContext.RequestContext.Principal); }