Beispiel #1
0
        public async ValueTask <HttpResponseMessage> Authorize(string username, string password)
        {
            var uri = _routePrefix;

            if (username == null || password == null)
            {
                return(null);
            }
            var log = new AuthorizeModel()
            {
                Username = username,
                Password = password
            };
            string json = JsonConvert.SerializeObject(log, Formatting.Indented);
            var    mess = new HttpRequestMessage()
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri(uri, UriKind.Relative),
                Content    = new StringContent(json, UnicodeEncoding.UTF8, "application/json")
            };
            var result = await _client.Http.SendAsync(mess);

            return(result);
        }
Beispiel #2
0
        public AuthorizeModel Login(LogInViewModel logInViewModel)
        {
            var user = _userRepository.GetUserByUserName(logInViewModel.UserName);

            if (user == null)
            {
                throw new Exception("Invalid Credentials!");
            }

            (_, string checkedPassword) = _hashHelper.Hash(logInViewModel.Password, user.Salt);

            if (user.Password != checkedPassword)
            {
                throw new Exception("Invalid Credentials!");
            }

            var model = new AuthorizeModel {
                Id = user.Id, UserName = user.UserName
            };

            model.Token   = _tokenHelper.GenerateToken(user.UserName, user.Id, user.Role);
            model.IsAdmin = user.Role == Role.Admin ? true : false;
            return(model);
        }
Beispiel #3
0
        public async Task <AuthorizeModel> GetCurrentUserAuthorization(Guid userId)
        {
            var allAuthorizePermissions = (await _authorizationService.GetFunctionOperateList()).ToList();
            var allAuthorizeDataRules   = (await _authorizationService.GetDataRuleList()).ToList();
            var user = await _userRepository.GetUserByIdIncludeRoleAndDataRule(userId);

            //如果当前用户类型为管理员或者租户管理员,则直接返回
            if (user.UserType is UserType.AdminUser or UserType.TenantAdminUser)
            {
                var result = new AuthorizeModel
                {
                    AuthorizePermissions = allAuthorizePermissions,
                    AuthorizeDataRules   = allAuthorizeDataRules
                };
                return(result);
            }

            var currentUserRole      = user.Roles.Select(x => x.Id).ToArray();
            var userBasalPermissions = await _permissionRepository.GetUserPermissionLimit(user.Id);

            var roleBasalPermissions = await _permissionRepository.GetRoleListPermissionLimit(currentUserRole);

            var mergeBasalPermissions = userBasalPermissions.Union(roleBasalPermissions).ToList();

            mergeBasalPermissions = PermissionHelper.MergeValidateObjectTypePermission(mergeBasalPermissions);


            var permissionViewModels =
                mergeBasalPermissions
                .Where(p => allAuthorizePermissions.Any(a => a.ServiceId == p.AppliedObjectID))
                .Select(p =>
            {
                var currentServicePermission =
                    allAuthorizePermissions.FirstOrDefault(x => x.ServiceId == p.AppliedObjectID);
                if (currentServicePermission != null)
                {
                    var convertPermissionList = PermissionHelper.ConvertPermissionToString(p);
                    var permissions           = new Dictionary <string, string>();

                    foreach (var keyValue in convertPermissionList)
                    {
                        foreach (var keyValuePair in currentServicePermission.Permissions.Where(keyValuePair =>
                                                                                                keyValuePair.Value == keyValue))
                        {
                            permissions.TryAdd(keyValuePair.Key, keyValue);
                        }
                    }

                    return(new AuthorizePermissionModel()
                    {
                        ServiceName = currentServicePermission?.ServiceName,
                        ServiceId = p.AppliedObjectID,
                        Permissions = permissions
                    });
                }

                return(new AuthorizePermissionModel());
            }).ToList();

            var authorizeDataRuleModels = PermissionHelper.ConvertAuthorizeDataRuleModels(user.RulesList);

            return(new AuthorizeModel()
            {
                AuthorizePermissions = permissionViewModels,
                AuthorizeDataRules = authorizeDataRuleModels
            });
        }
Beispiel #4
0
 public ActionResult SetAuthorize(AuthorizeModel model)
 {
     model.CreateUser = CurrentUser.Id;
     return(Json(new JsonMessage(business.SetAuthorize(model))));
 }
Beispiel #5
0
        public IActionResult Authorize
        (
            [FromBody, Required] AuthorizeModel model
        )
        {
            _ = model ?? throw new NullReferenceException("No valid model was passed");
            _logger.LogInformation("Authorize request received");

            try
            {
                if (model.securityData.login.loginID != _configuration["StubLogin:loginID"] && model.securityData.login.password != _configuration["StubLogin:password"])
                {
                    throw new ArgumentException("login is not valid");
                }
                if (model.accountNumber.Substring(0, 5) != _configuration["StubLogin:routePrefix"])
                {
                    throw new ArgumentOutOfRangeException("account number is not falid");
                }

                Random random = new Random();
                AuthorizeResponseModel authorizeResponseModel = new AuthorizeResponseModel();

                if (random.Next(0, 100) > int.Parse(_configuration["StubLogin:ErrorRatio"]))
                {
                    authorizeResponseModel = new AuthorizeResponseModel()
                    {
                        messageID            = model.messageID,
                        responseCode         = ResponseCode.APPROVED,
                        responseText         = "Success",
                        structuredData       = model.structuredData,
                        transmissionDateTime = DateTime.UtcNow.ToString(Startup.TRANSMISSIONDATEANDTIME),
                        customerData         = new CustomerData()
                        {
                            contactNumber = "0112223344",
                            firstName     = "STUB",
                            idNumber      = "0099887766554",
                            lastName      = "STUB"
                        },
                        dueDate             = DateTime.UtcNow.AddDays(2).ToString(Startup.TRANSMISSIONDATEANDTIME),
                        echoData            = model.echoData,
                        issuerTransactionID = Guid.NewGuid().ToString()
                    };
                }
                else
                {
                    authorizeResponseModel = new AuthorizeResponseModel()
                    {
                        messageID            = model.messageID,
                        responseCode         = ResponseCode.PAYMENT_NOT_ALLOWED,
                        responseText         = "payment not allowed",
                        structuredData       = model.structuredData,
                        transmissionDateTime = DateTime.UtcNow.ToString(Startup.TRANSMISSIONDATEANDTIME),
                        customerData         = new CustomerData()
                        {
                            contactNumber = "0112223344",
                            firstName     = "STUBB",
                            idNumber      = "009988",
                            lastName      = "STUBB"
                        },
                        dueDate             = DateTime.UtcNow.ToString(Startup.TRANSMISSIONDATEANDTIME),
                        echoData            = model.echoData,
                        issuerTransactionID = Guid.NewGuid().ToString()
                    };
                }

                _logger.LogInformation("Authorize request returned");
                return(Ok(authorizeResponseModel));
            }
            catch (ArgumentOutOfRangeException ex)
            {
                _logger.LogError($"Authorize threw an argument excpetion. Message {ex.Message}. Stacktrace {ex.StackTrace}. InnerException {ex.InnerException}");
                return(Ok(new AuthorizeResponseModel()
                {
                    messageID = model.messageID,
                    responseCode = ResponseCode.INVALID_ACCOUNT_NUMBER,
                    responseText = "invalid account number",
                    structuredData = model.structuredData,
                    transmissionDateTime = DateTime.UtcNow.ToString(Startup.TRANSMISSIONDATEANDTIME),
                    customerData = new CustomerData()
                    {
                        contactNumber = "0112223344",
                        firstName = "STUB",
                        idNumber = "0099887766554",
                        lastName = "STUB"
                    },
                    dueDate = DateTime.UtcNow.AddDays(2).ToString(Startup.TRANSMISSIONDATEANDTIME),
                    echoData = model.echoData,
                    issuerTransactionID = Guid.NewGuid().ToString()
                }));
            }
            catch (ArgumentException ex)
            {
                _logger.LogError($"Authorize threw an argument excpetion. Message {ex.Message}. Stacktrace {ex.StackTrace}. InnerException {ex.InnerException}");
                return(Ok(new AuthorizeResponseModel()
                {
                    messageID = model.messageID,
                    responseCode = ResponseCode.INVALID_AUTHENTICATION,
                    responseText = "invalid authentication",
                    structuredData = model.structuredData,
                    transmissionDateTime = DateTime.UtcNow.ToString(Startup.TRANSMISSIONDATEANDTIME),
                    customerData = new CustomerData()
                    {
                        contactNumber = "0112223344",
                        firstName = "STUB",
                        idNumber = "0099887766554",
                        lastName = "STUB"
                    },
                    dueDate = DateTime.UtcNow.AddDays(2).ToString(Startup.TRANSMISSIONDATEANDTIME),
                    echoData = model.echoData,
                    issuerTransactionID = Guid.NewGuid().ToString()
                }));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Authorize threw an excpetion. Message {ex.Message}. Stacktrace {ex.StackTrace}. InnerException {ex.InnerException}");
                return(Ok(new AuthorizeResponseModel()
                {
                    messageID = model.messageID,
                    responseCode = ResponseCode.SYSTEM_MALFUNCTION,
                    responseText = "inner Excpetion",
                    structuredData = model.structuredData,
                    transmissionDateTime = DateTime.UtcNow.ToString(Startup.TRANSMISSIONDATEANDTIME),
                    customerData = new CustomerData()
                    {
                        contactNumber = "0112223344",
                        firstName = "STUB",
                        idNumber = "0099887766554",
                        lastName = "STUB"
                    },
                    dueDate = DateTime.UtcNow.AddDays(2).ToString(Startup.TRANSMISSIONDATEANDTIME),
                    echoData = model.echoData,
                    issuerTransactionID = Guid.NewGuid().ToString()
                }));
            }
        }
Beispiel #6
0
 /// <summary>
 /// Authorize whether entity could be accessed in a store (mapped to this store)
 /// </summary>
 /// <param name="entityName">Type</param>
 /// <param name="entity">Entity</param>
 /// <param name="storeId">Store identifier</param>
 /// <returns>true - authorized; otherwise, false</returns>
 public bool Authorize([FromBody] AuthorizeModel model)
 {
     return(_storeMappingService.Authorize(model.entityName, model.entity, model.storeId));
 }
        public HttpResponseMessage Index(AuthorizeModel azureAdAuthorizeRequest)
        {
            try
            {
                //Input Syntax Validation
                if (azureAdAuthorizeRequest.Id_Token_Hint == null)
                {
                    throw new InvalidDataException("id_token_hint is required.");
                }

                if (azureAdAuthorizeRequest.Response_Type != "id_token")
                {
                    throw new InvalidDataException("Unsupported response type.");
                }

                if (azureAdAuthorizeRequest.Response_Mode != "form_post")
                {
                    throw new InvalidDataException("Unsupported response mode.");
                }

                string requestClientId = azureAdAuthorizeRequest.Client_Id;

                //Validate the client id of the request is allowed
                if (!Settings.Default.AllowedExtensionClientIds.Contains(requestClientId))
                {
                    throw new InvalidDataException("Unauthorized client.");
                }

                if (!Settings.Default.AzureADAllowedRedirectUris.Contains(azureAdAuthorizeRequest.Redirect_Uri))
                {
                    throw new InvalidDataException("Unauthorized redirect uri.");
                }
                //End of input Syntax Validation

                //Validate and parse the original id_token_hint. We need to extract the 'sub' claim and reply it back
                JwtSecurityToken idTokenHint = ValidateIdTokenHint(azureAdAuthorizeRequest.Id_Token_Hint);
                string           originalSub = idTokenHint.Claims.First(c => c.Type == "sub").Value;

                //Analyze the claims requested by Azure AD into the provider
                //In this sample, we will simply echo back exactly what Azure AD Requested.
                //In real examples, the provider would execute some custom logic
                ClaimsRequestParameter requestedControlClaims = JsonConvert.DeserializeObject <ClaimsRequestParameter>(azureAdAuthorizeRequest.Claims);
                if (requestedControlClaims.IdToken == null)
                {
                    throw new InvalidDataException("Unsupported claims request parameter.");
                }

                //In addition to the Sub is required to be returned
                requestedControlClaims.IdToken.Add(
                    "sub", new ClaimsRequestParameter.ClaimProperties()
                {
                    Value = originalSub
                }
                    );

                //We will prepare the output here right away. If user interaction is required, return the proper redirections
                //to views to challenge user.
                NameValueCollection dataToSend = new NameValueCollection();
                dataToSend.Add("state", azureAdAuthorizeRequest.State);
                dataToSend.Add("id_token", GenerateOutputToken(requestedControlClaims, requestClientId));

                Uri    redirectUri = new Uri(azureAdAuthorizeRequest.Redirect_Uri);
                string formPost    = BuildFormPostWithDataToSend(dataToSend, redirectUri);

                var response = Request.CreateResponse(HttpStatusCode.OK);
                response.Content          = new StringContent(formPost, Encoding.UTF8, "text/html");
                response.Headers.Location = redirectUri;
                return(response);
            }
            catch (Exception e)
            {
                return(new HttpResponseMessage()
                {
                    Content = new StringContent(
                        JsonConvert.SerializeObject(e, Formatting.Indented, new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore
                    }),
                        Encoding.UTF8,
                        "application/json")
                });
            }
        }
Beispiel #8
0
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <returns></returns>
        public static bool Add(UserModel model, AuthorizeModel authmodel)
        {
            string sql = @"
insert into user
(UserID
,NickName
,CreateTime
,loginKey
)
values
(@UserID
,@NickName
,@CreateTime
,@loginKey
);

-- 授权
insert into authorize
(UserID
,AuthID
,Data
)
values
(@UserID
,@AuthID
,@Data
);

-- 关注官方的几个吧
insert into user_bar
(UserID
,BarID
,CreateTime
,IsFollow
)
values
(@UserID
,1
,@CreateTime
,1
);

";

            MySqlParameter[] _parameter =
            {
                new MySqlParameter("@UserID",     MySqlDbType.VarChar, 36)
                {
                    Value = model.UserID
                },
                new MySqlParameter("@NickName",   MySqlDbType.VarChar, 36)
                {
                    Value = model.NickName
                },
                new MySqlParameter("@CreateTime", MySqlDbType.VarChar, 36)
                {
                    Value = model.CreateTime
                },
                new MySqlParameter("@loginKey",   MySqlDbType.VarChar, 36)
                {
                    Value = model.LoginKey
                },
                new MySqlParameter("@AuthID",     MySqlDbType.VarChar, 100)
                {
                    Value = authmodel.AuthID
                },
                new MySqlParameter("@Data",       MySqlDbType.LongText)
                {
                    Value = authmodel.Data
                },
            };
            var _rows = DbHelperMySqlForWeiBar.ExecuteSql(sql, _parameter);

            return(_rows > 0);
        }
 public AuthorizeController(IOptions <StateConfigs> configs)
 {
     func = new Functional();
     auth = new AuthorizeModel(configs);
     acc  = new AccountModel(configs);
 }
Beispiel #10
0
        public async Task <string> CreateCodeAndStoreCodeGrant(Client client, ClaimsPrincipal user, AuthorizeModel model)
        {
            if (!AbnfValidationHelper.IsValid(model.CodeChallenge, 43, 128))
            {
                // Code verifier is not valid
                throw new SecurityException("Code challange is not valid");
            }

            var grant = new CodeGrant
            {
                ClientId            = client.ClientId,
                Code                = _randomStringGenerator.GetRandomString(15),
                CodeChallange       = model.CodeChallenge,
                CodeChallangeMethod = model.CodeChallengeMethod,
                Nonce               = model.Nonce,
                RedirectUri         = model.RedirectUri,
                Scope               = model.Scope,
                State               = model.State,
                Expires             = DateTime.UtcNow.AddSeconds(client.AuthorityCodeLifetime),
                Created             = DateTime.UtcNow,
                Resolved            = null,
            };

            SetSubjectId(user, grant);

            await _grantAccessor.SaveCodeGrant(grant);

            return(grant.Code);
        }
Beispiel #11
0
 public Task <string> GetCodeForExistingConsent(Client client, ClaimsPrincipal user, AuthorizeModel model)
 {
     throw new NotImplementedException();
 }
Beispiel #12
0
        public async Task <IActionResult> RequestToken(string grant_type, string code, string redirect_uri,
                                                       string client_id, string client_secret)
        {
            if (grant_type.ToLower() == "authorization_code")
            {
                AuthorizeModel auth = authModels.FirstOrDefault(x => x.Code == code);

                if (auth == null)
                {
                    return(NotFound("Could not find specified code."));
                }

                if (auth.ClientID != client_id)
                {
                    return(NotFound("Client ID does not match."));
                }

                if (auth.Redirect != redirect_uri)
                {
                    return(NotFound("Redirect does not match."));
                }

                OauthApp app = await _context.OauthApps.FirstOrDefaultAsync(x => x.Id == client_id);

                if (app.Secret != client_secret)
                {
                    return(Unauthorized("Failed authorization. This failure has been logged."));
                }

                app.Uses += 1;

                _context.OauthApps.Update(app);
                await _context.SaveChangesAsync();

                string hash = ToHex(SHA256.Create().ComputeHash(Guid.NewGuid().ToByteArray()), false);

                AuthToken token = new AuthToken()
                {
                    Id     = hash,
                    AppId  = client_id,
                    UserId = auth.UserID,
                    Scope  = auth.Scope,
                    Time   = DateTime.UtcNow
                };

                await _context.AuthTokens.AddAsync(token);

                await _context.SaveChangesAsync();

                TokenResponse response = new TokenResponse()
                {
                    access_token = token.Id,
                    expires_in   = 3600,
                    svid         = token.UserId
                };

                return(Json(response));
            }
            else
            {
                return(NotFound("Grant type not implemented!"));
            }
        }