Пример #1
0
        public IActionResult Index()
        {
            AuthorizeViewModel myModel = new AuthorizeViewModel();

            myModel.DSThongTin = GetInfo();
            return(View(myModel));
        }
Пример #2
0
        public async Task <IActionResult> Authorize(AuthorizeAddressModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View("AuthError"));
            }
            var app  = (await _apiService.AppInfoAsync(model.AppId)).App;
            var url  = new Uri(model.RedirectUri);
            var user = await GetCurrentUserAsync();

            // Wrong domain
            if (url.Host != app.AppDomain && app.DebugMode == false)
            {
                ModelState.AddModelError(string.Empty, "Redirect uri did not work in the valid domain!");
                _logger.LogInformation($"A request with appId {model.AppId} is access wrong domain.");
                return(View("AuthError"));
            }
            // Signed in. App is not in force input password mode. User did not specify force input.
            else if (user != null && app.ForceInputPassword != true && model.ForceConfirm != true)
            {
                await _authLogger.LogAuthRecord(user.Id, HttpContext, true, app.AppId);

                return(await _authManager.FinishAuth(user, model, app.ForceConfirmation, app.TrustedApp));
            }
            // Not signed in but we don't want his info
            else if (model.TryAutho == true)
            {
                return(Redirect($"{url.Scheme}://{url.Host}:{url.Port}/?{AuthValues.DirectShowString.Key}={AuthValues.DirectShowString.Value}"));
            }
            var viewModel = new AuthorizeViewModel(model.RedirectUri, model.State, model.AppId, app.AppName, app.IconPath, _allowRegistering, _allowPasswordSignIn);

            return(View(viewModel));
        }
 public Authorize()
 {
     viewModel   = new AuthorizeViewModel();
     DataContext = viewModel;
     InitializeComponent();
     MainFrame.Content = new AuthPage(ref viewModel);
 }
Пример #4
0
        public async Task <IActionResult> Authorize(AuthorizeViewModel model)
        {
            var capp = await APIService.AppInfoAsync(model.AppId);

            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, isPersistent : model.RememberMe, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    return(await FinishAuth(model, capp.ForceConfirmation));
                }
                else if (result.RequiresTwoFactor)
                {
                    throw new NotImplementedException();
                }
                else if (result.IsLockedOut)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                }
            }
            model.Recover(capp.AppName, capp.AppImageUrl);
            return(View(model));
        }
        /// <summary>
        /// Provides the user with a consent screen where the user can decide whether to give the
        /// application access or not.
        /// </summary>
        /// <exception cref="ArgumentNullException">
        /// Thrown when one or more required arguments are null.
        /// </exception>
        /// <param name="model">The consent screen viewmodel.</param>
        /// <returns>An action result</returns>
        public virtual async Task <ActionResult> Index(AuthorizeViewModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model), "The request is invalid");
            }

            if (!this.Authentication.User.Identity.IsAuthenticated)
            {
                this.log.Debug($"User is not authenticated, redirecting to login screen");

                this.Authentication.Challenge(DefaultAuthenticationTypes.ApplicationCookie);

                return(new HttpUnauthorizedResult());
            }

            this.log.Debug($"User is already authenticated, redirecting to {this.Request.Url}");

            // Remove trailing slash if present
            if (this.Request.Url != null && this.Request.Url.AbsolutePath.EndsWith("/"))
            {
                var returnUrl = $"{this.Request.Url.Scheme}://{this.Request.Url.Authority}{this.Request.Url.AbsolutePath.TrimEnd('/')}{this.Request.Url.Query}";

                return(this.Redirect(returnUrl));
            }

            return(this.View(model));
        }
Пример #6
0
        public IActionResult ViewUser()
        {
            AuthorizeViewModel myModel = new AuthorizeViewModel();

            myModel.DSThongTin = GetUser();
            return(View(myModel));
        }
Пример #7
0
        public async Task <IActionResult> Authorize(AuthorizeViewModel model)
        {
            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, isPersistent : model.RememberMe, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    var cuser = await GetCurrentUserAsync(model.Email);

                    var pack = await cuser.GeneratePack(_dbContext, model.AppId);

                    var url = AddCode(model.ToRedirect, pack.Code, model.State);
                    return(Redirect(url));
                }
                else if (result.RequiresTwoFactor)
                {
                    throw new NotImplementedException();
                }
                else if (result.IsLockedOut)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(View(model));
                }
            }
            return(View(model));
        }
Пример #8
0
 public AuthorizeView(AuthorizeViewModel viewModel)
 {
     InitializeComponent();
     ViewModel   = viewModel;
     DataContext = ViewModel;
     Load();
 }
Пример #9
0
        public async Task <IActionResult> Index()
        {
            var user = await _userManager.GetUserAsync(HttpContext.User);

            var userId = user?.Id;
            var mail   = user?.Email;

            if (userId == null && mail == null)
            {
                return(RedirectToAction("Login", "Account", new { returnUrl = Request.Path + Request.QueryString }));
            }

            OpenIdConnectRequest request = HttpContext.GetOpenIdConnectRequest();
            OAuthClient          client  = await _context.ClientApplications.Where(x => x.ClientId == request.ClientId).FirstOrDefaultAsync();

            if (client == null)
            {
                return(NotFound());
            }

            AuthorizeViewModel vm = new AuthorizeViewModel()
            {
                ClientId            = client.ClientId,
                ClientDescription   = client.ClientDescription,
                ClientName          = client.ClientName,
                RedirectUri         = request.RedirectUri,
                ResponseType        = request.ResponseType,
                Scopes              = string.IsNullOrWhiteSpace(request.Scope) ? new string[0] : request.Scope.Split(' '),
                State               = request.State,
                CodeChallenge       = request.CodeChallenge,
                CodeChallengeMethod = request.CodeChallengeMethod
            };

            return(View(vm));
        }
        public async Task <IActionResult> AuthorizeStatus(AuthorizeViewModel model)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", model.State);

                var response = await httpClient.GetAsync(HiddenSoundOptions.ApiUri + "/Api/Authorization/Info?authorizationCode=" + WebUtility.UrlEncode(model.AuthorizationCode));

                var jsonString = await response.Content.ReadAsStringAsync();

                var responseModel = JsonConvert.DeserializeObject <AuthorizationInfoResponse>(jsonString);

                model.Status = responseModel.Status;
            }

            if (model.Status == AuthorizationStatus.Approved)
            {
                return(RedirectToAction("CartRedirectApproved"));
            }
            else if (model.Status == AuthorizationStatus.Declined)
            {
                return(RedirectToAction("CartRedirectDeclined"));
            }

            return(PartialView("_AuthorizeStatus", model));
        }
Пример #11
0
        public async Task <ActionResult> Authorize(GetAuthorizeRequest request, CancellationToken ct)
        {
            var client = await _ioAuthClientsService.GetByClientIdAsync(request.client_id, ct);

            if (!client.IsValid())
            {
                return(BadRequest("Client not found"));
            }

            if (!client.IsMatchRedirectUri(request))
            {
                return(BadRequest("Invalid redirect uri"));
            }

            if (!client.IsScopesInclude(request.scope))
            {
                return(BadRequest("Invalid scopes"));
            }

            var model = new AuthorizeViewModel(
                request.client_id,
                request.response_type,
                request.scope,
                request.redirect_uri,
                request.state,
                request.IsInvalidCredentials);

            return(View("~/OAuth/Views/Authorize.cshtml", model));
        }
        public async Task <ActionResult> LocalLogin(AuthorizeViewModel authorizeViewModel)
        {
            var authenticatedUser = await this.GetAuthenticatedUser(Constants.CookieName);

            if (authenticatedUser != null &&
                authenticatedUser.Identity != null &&
                authenticatedUser.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "User"));
            }

            if (authorizeViewModel == null)
            {
                throw new ArgumentNullException(nameof(authorizeViewModel));
            }

            if (!ModelState.IsValid)
            {
                await TranslateView(DefaultLanguage);

                return(View("Index", authorizeViewModel));
            }

            try
            {
                var resourceOwner = await _authenticateActions.LocalUserAuthentication(authorizeViewModel.ToParameter());

                var claims = resourceOwner.Claims;
                claims.Add(new Claim(ClaimTypes.AuthenticationInstant,
                                     DateTimeOffset.UtcNow.ConvertToUnixTimestamp().ToString(CultureInfo.InvariantCulture),
                                     ClaimValueTypes.Integer));
                var subject = claims.First(c => c.Type == Core.Jwt.Constants.StandardResourceOwnerClaimNames.Subject).Value;
                var authenticationManager = this.GetAuthenticationManager();
                if (resourceOwner.TwoFactorAuthentication == Core.Models.TwoFactorAuthentications.NONE)
                {
                    await SetLocalCookie(authenticationManager, claims);

                    _simpleIdentityServerEventSource.AuthenticateResourceOwner(subject);
                    return(RedirectToAction("Index", "User"));
                }

                // 2.1 Store temporary information in cookie
                await SetTwoFactorCookie(authenticationManager, claims);

                // 2.2. Send confirmation code
                var code = await _authenticateActions.GenerateAndSendCode(subject);

                _simpleIdentityServerEventSource.GetConfirmationCode(code);
                return(RedirectToAction("SendCode"));
            }
            catch (Exception exception)
            {
                _simpleIdentityServerEventSource.Failure(exception.Message);
                await TranslateView("en");

                ModelState.AddModelError("invalid_credentials", exception.Message);
                return(View("Index", authorizeViewModel));
            }
        }
Пример #13
0
        public async Task <dynamic> Authorize(AuthorizeViewModel model)
        {
            var modelJson     = JsonSerializer.Serialize(model, jsonSerializerOptions);
            var stringContent = new StringContent(modelJson, Encoding.UTF8, "application/json");
            var client        = _clientFactory.CreateClient("MedByte");
            var response      = await client.PostAsync("account/register", stringContent);

            return(response);
        }
        public async Task <IActionResult> LocalLogin(LocalAuthenticationViewModel localAuthenticationViewModel)
        {
            var authenticatedUser = await SetUser();

            if (authenticatedUser != null &&
                authenticatedUser.Identity != null &&
                authenticatedUser.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "User", new { area = "UserManagement" }));
            }

            if (localAuthenticationViewModel == null)
            {
                throw new ArgumentNullException(nameof(localAuthenticationViewModel));
            }

            if (ModelState.IsValid)
            {
                ResourceOwner resourceOwner = null;
                try
                {
                    resourceOwner = await _smsAuthenticationOperation.Execute(localAuthenticationViewModel.PhoneNumber);
                }
                catch (Exception ex)
                {
                    _simpleIdentityServerEventSource.Failure(ex.Message);
                    ModelState.AddModelError("message_error", ex.Message);
                }

                if (resourceOwner != null)
                {
                    var claims = resourceOwner.Claims;
                    claims.Add(new Claim(ClaimTypes.AuthenticationInstant,
                                         DateTimeOffset.UtcNow.ConvertToUnixTimestamp().ToString(CultureInfo.InvariantCulture),
                                         ClaimValueTypes.Integer));
                    await SetPasswordLessCookie(claims);

                    try
                    {
                        return(RedirectToAction("ConfirmCode"));
                    }
                    catch (Exception ex)
                    {
                        _simpleIdentityServerEventSource.Failure(ex.Message);
                        ModelState.AddModelError("message_error", "TWILIO account is not valid");
                    }
                }
            }

            var viewModel = new AuthorizeViewModel();

            await SetIdProviders(viewModel);
            await TranslateView(DefaultLanguage);

            return(View("Index", viewModel));
        }
        public virtual Task SignIn(AuthorizeViewModel model)
        {
            var oauthIdentity = new SentinelIdentity(OAuthDefaults.AuthenticationType, this.Authentication.User.Identity);

            this.Authentication.SignOut(OAuthDefaults.AuthenticationType);
            this.Authentication.SignIn(new AuthenticationProperties()
            {
                RedirectUri = model.RedirectUri
            }, oauthIdentity.ToClaimsIdentity());

            return(Task.FromResult <object>(null));
        }
        private async Task <IActionResult> DisplayError(string errorMessage)
        {
            _simpleIdentityServerEventSource.Failure(errorMessage);
            await TranslateView(DefaultLanguage).ConfigureAwait(false);

            ModelState.AddModelError("invalid_credentials", errorMessage);
            var viewModel = new AuthorizeViewModel();

            await SetIdProviders(viewModel);

            return(View("Index", viewModel));
        }
        public static LocalAuthenticationParameter ToParameter(this AuthorizeViewModel viewModel)
        {
            if (viewModel == null)
            {
                throw new ArgumentNullException(nameof(viewModel));
            }

            return(new LocalAuthenticationParameter
            {
                UserName = viewModel.UserName,
                Password = viewModel.Password
            });
        }
Пример #18
0
        public async Task <IActionResult> Index()
        {
            var authenticatedUser = await SetUser().ConfigureAwait(false);

            if (authenticatedUser?.Identity == null || !authenticatedUser.Identity.IsAuthenticated)
            {
                var viewModel = new AuthorizeViewModel();
                await SetIdProviders(viewModel).ConfigureAwait(false);

                return(Ok(viewModel));
            }

            return(RedirectToAction("Index", "User", new { area = "pwd" }));
        }
Пример #19
0
        public async Task <IActionResult> Authorize(AuthorizeViewModel model)
        {
            App app;

            try
            {
                app = (await _apiService.AppInfoAsync(model.AppId)).App;
            }
            catch (AiurUnexceptedResponse)
            {
                return(NotFound());
            }
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var mail = await _dbContext
                       .UserEmails
                       .Include(t => t.Owner)
                       .SingleOrDefaultAsync(t => t.EmailAddress == model.Email.ToLower());

            if (mail == null)
            {
                ModelState.AddModelError(string.Empty, "Unknown user email.");
                model.Recover(app.AppName, app.AppIconAddress);
                return(View(model));
            }
            var user   = mail.Owner;
            var result = await _signInManager.PasswordSignInAsync(user, model.Password, isPersistent : true, lockoutOnFailure : true);

            if (result.Succeeded)
            {
                return(await FinishAuth(model, app.ForceConfirmation));
            }
            else if (result.RequiresTwoFactor)
            {
                throw new NotImplementedException();
            }
            else if (result.IsLockedOut)
            {
                ModelState.AddModelError(string.Empty, "The account is locked for too many attempts.");
            }
            else
            {
                ModelState.AddModelError(string.Empty, "The password does not match our records.");
            }
            model.Recover(app.AppName, app.AppIconAddress);
            return(View(model));
        }
Пример #20
0
        public async Task <IActionResult> Authorize(AuthorizeViewModel model)
        {
            if (!_allowPasswordSignIn)
            {
                return(Unauthorized());
            }
            var app = (await _apiService.AppInfoAsync(model.AppId)).App;

            if (!ModelState.IsValid)
            {
                model.Recover(app.AppName, app.IconPath, _allowRegistering, _allowPasswordSignIn);
                return(View(model));
            }
            var mail = await _dbContext
                       .UserEmails
                       .Include(t => t.Owner)
                       .SingleOrDefaultAsync(t => t.EmailAddress == model.Email.ToLower());

            if (mail == null)
            {
                ModelState.AddModelError(string.Empty, "Unknown user email.");
                model.Recover(app.AppName, app.IconPath, _allowRegistering, _allowPasswordSignIn);
                return(View(model));
            }
            var user   = mail.Owner;
            var result = await _signInManager.PasswordSignInAsync(user, model.Password, isPersistent : true, lockoutOnFailure : true);

            await _authLogger.LogAuthRecord(user.Id, HttpContext, result.Succeeded || result.RequiresTwoFactor, app.AppId);

            if (result.Succeeded)
            {
                return(await _authManager.FinishAuth(user, model, app.ForceConfirmation, app.TrustedApp));
            }
            if (result.RequiresTwoFactor)
            {
                return(Redirect(new AiurUrl($"/oauth/{nameof(SecondAuth)}", new FinishAuthInfo
                {
                    AppId = model.AppId,
                    RedirectUri = model.RedirectUri,
                    State = model.State
                }).ToString()));
            }
            ModelState.AddModelError(string.Empty,
                                     result.IsLockedOut
                    ? "The account is locked for too many attempts."
                    : "The password does not match our records.");
            model.Recover(app.AppName, app.IconPath, _allowRegistering, _allowPasswordSignIn);
            return(View(model));
        }
Пример #21
0
        protected async Task SetIdProviders(AuthorizeViewModel authorizeViewModel)
        {
            var schemes     = (await _authenticationSchemeProvider.GetAllSchemesAsync().ConfigureAwait(false)).Where(p => !string.IsNullOrWhiteSpace(p.DisplayName));
            var idProviders = new List <IdProviderViewModel>();

            foreach (var scheme in schemes)
            {
                idProviders.Add(new IdProviderViewModel
                {
                    AuthenticationScheme = scheme.Name,
                    DisplayName          = scheme.DisplayName
                });
            }

            authorizeViewModel.IdProviders = idProviders;
        }
Пример #22
0
        public async Task <IActionResult> Index()
        {
            var authenticatedUser = await SetUser();

            if (authenticatedUser == null || authenticatedUser.Identity == null || !authenticatedUser.Identity.IsAuthenticated)
            {
                await TranslateView(DefaultLanguage);

                var viewModel = new AuthorizeViewModel();
                await SetIdProviders(viewModel);

                return(View(viewModel));
            }

            return(RedirectToAction("Index", "User", new { area = "UserManagement" }));
        }
Пример #23
0
        /*[HttpPost("api/register")]
         * public IActionResult Register([FromBody] User model)
         * {
         *  if (!ModelState.IsValid)
         *      return BadRequest(ModelState);
         *  model.Password = CryptServices.Encript(model.Password, model.Login.ToLower());
         *  //var roleId = ;
         *  //model.UserRoles = role.Id;
         *  ur.Add(model);
         *  return Ok(model);
         *
         *  ViewBag.Message = "Такой пользователь уже есть";
         *  return BadRequest(model);
         * }*/

        public async Task <ApplicationUser> GetUserAsync(AuthorizeViewModel model)
        {
            //name find by dpiscriminator
            ApplicationUser user = await userManger.FindByNameAsync(model.Login);

            if (user == null)
            {
                return(null);
            }
            var hasUser = user.Login == model.Login && user.Password == model.Password;

            if (!hasUser)
            {
                return(null);
            }
            return(user);
        }
Пример #24
0
        public async Task <IActionResult> Index()
        {
            var authenticatedUser = await SetUser().ConfigureAwait(false);

            var hasReturnUrl = Request.Query.TryGetValue("ReturnUrl", out var returnUrl);

            if (authenticatedUser?.Identity == null || !authenticatedUser.Identity.IsAuthenticated)
            {
                var viewModel = new AuthorizeViewModel {
                    ReturnUrl = returnUrl
                };
                await SetIdProviders(viewModel).ConfigureAwait(false);

                return(Ok(viewModel));
            }

            return(hasReturnUrl ? Redirect(returnUrl) : RedirectToAction("Index", "User"));
        }
Пример #25
0
        private async Task <AuthorizeViewModel> FillFromRequest(OpenIdConnectRequest OIDCRequest)
        {
            string      clientId = OIDCRequest.ClientId;
            OAuthClient client   = await _context.ClientApplications.FindAsync(clientId);

            if (client == null)
            {
                return(null);
            }
            else
            {
                // Get the Scopes for this application from the query - disallow duplicates
                ICollection <OAuthScope> scopes = new HashSet <OAuthScope>();
                if (!String.IsNullOrWhiteSpace(OIDCRequest.Scope))
                {
                    foreach (string s in OIDCRequest.Scope.Split(' '))
                    {
                        if (OAuthScope.NameInScopes(s))
                        {
                            OAuthScope scope = OAuthScope.GetScope(s);
                            if (!scopes.Contains(scope))
                            {
                                scopes.Add(scope);
                            }
                        }
                        else
                        {
                            return(null);
                        }
                    }
                }

                AuthorizeViewModel avm = new AuthorizeViewModel()
                {
                    ClientId     = OIDCRequest.ClientId,
                    ResponseType = OIDCRequest.ResponseType,
                    State        = OIDCRequest.State,
                    Scopes       = String.IsNullOrWhiteSpace(OIDCRequest.Scope) ? new string[0] : OIDCRequest.Scope.Split(' '),
                    RedirectUri  = OIDCRequest.RedirectUri
                };

                return(avm);
            }
        }
Пример #26
0
        public async Task <IActionResult> Accept()
        {
            ApplicationUser au = await _userManager.GetUserAsync(HttpContext.User);

            if (au == null)
            {
                return(LocalRedirect("/error"));
            }
            OpenIdConnectRequest request = HttpContext.GetOpenIdConnectRequest();
            AuthorizeViewModel   avm     = await FillFromRequest(request);

            if (avm == null)
            {
                return(LocalRedirect("/error"));
            }
            AuthenticationTicket ticket = TicketCounter.MakeClaimsForInteractive(au, avm);

            Microsoft.AspNetCore.Mvc.SignInResult sr = SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
            return(sr);
        }
        public async Task <IActionResult> Authorize(string state)
        {
            var model = new AuthorizeViewModel();

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", state);

                var response = await httpClient.PostAsync(HiddenSoundOptions.ApiUri + "/Api/Authorization/Create", new StringContent(""));

                var jsonString = await response.Content.ReadAsStringAsync();

                var responseModel = JsonConvert.DeserializeObject <AuthorizationCreateResponse>(jsonString);

                model.QRCode            = responseModel.Base64QR;
                model.AuthorizationCode = responseModel.AuthorizationCode;
                model.State             = state;
            }

            return(View(model));
        }
Пример #28
0
        public async Task <IActionResult> Authorize(AuthorizeAddressModel model)
        {
            App app;

            try
            {
                app = (await _apiService.AppInfoAsync(model.appid)).App;
            }
            catch (AiurUnexceptedResponse)
            {
                return(NotFound());
            }
            if (!ModelState.IsValid)
            {
                return(View("AuthError"));
            }
            var url  = new Uri(model.redirect_uri);
            var user = await GetCurrentUserAsync();

            // Wrong domain
            if (url.Host != app.AppDomain && app.DebugMode == false)
            {
                ModelState.AddModelError(string.Empty, "Redirect uri did not work in the valid domain!");
                _logger.LogInformation($"A request with appId {model.appid} is access wrong domian.");
                return(View("AuthError"));
            }
            // Signed in. App is not in force input password mode. User did not specify force input.
            else if (user != null && app.ForceInputPassword != true && model.forceConfirm != true)
            {
                return(await FinishAuth(model.Convert(user.Email), app.ForceConfirmation));
            }
            // Not signed in but we don't want his info
            else if (model.tryAutho == true)
            {
                return(Redirect($"{url.Scheme}://{url.Host}:{url.Port}/?{Values.DirectShowString.Key}={Values.DirectShowString.Value}"));
            }
            var viewModel = new AuthorizeViewModel(model.redirect_uri, model.state, model.appid, model.scope, model.response_type, app.AppName, app.AppIconAddress);

            return(View(viewModel));
        }
Пример #29
0
        public async Task <IActionResult> Token([FromBody] AuthorizeViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await userManger.FindByNameAsync(model.Login);

            //context.Users.FirstOrDefault(x => x.Login == model.Login);

            if (user == null)
            {
                return(NotFound());
            }
            if (user.Login != model.Login && user.Password != model.Password) //потом добавить CryptService и доделать сравнение пароля
            {
                return(BadRequest());
            }

            var identity = await GetIdentity(user);

            var encodeJwt = tokenServices.GenerateAccessToken(identity.Claims);

            var newToken = tokenServices.GenerateRefreshToken();

            var responce = new
            {
                access_token = encodeJwt,
                refreshToken = newToken,
                user_name    = identity.Name,
                role         = identity.GetUserRole(),
                admin        = identity.IsAdmin(),
                id           = identity.getUserId <string>()
            };

            //ReplaseRefreshToken(responce.id, newToken);

            return(Ok(responce));
        }
Пример #30
0
        public ActionResult Authorize(AuthorizeViewModel model, bool isGrant)
        {
            if (Response.StatusCode != 200)
            {
                return(View("AuthorizeError"));
            }

            if (ModelState.IsValid)
            {
                var scopes = model.Scope.Split(',');

                if (isGrant)
                {
                    var ticket   = AuthenticationManager.AuthenticateAsync(User.Identity.AuthenticationType).Result;
                    var identity = ticket != null ? ticket.Identity : null;
                    if (identity == null)
                    {
                        return(View("AuthorizeError"));
                    }
                    var oauthIdentity = identity;
                    if (!identity.AuthenticationType.Equals(OAuthDefaults.AuthenticationType, StringComparison.Ordinal))
                    {
                        oauthIdentity = new ClaimsIdentity(identity.Claims, OAuthDefaults.AuthenticationType, identity.NameClaimType, identity.RoleClaimType);
                    }
                    foreach (var scope in scopes)
                    {
                        oauthIdentity.AddClaim(new Claim("urn:oauth:scope", scope, oauthIdentity.AuthenticationType));
                    }
                    AuthenticationManager.SignIn(identity);
                }
                else
                {
                    AuthenticationManager.SignOut();
                    AuthenticationManager.Challenge();
                    return(new HttpUnauthorizedResult());
                }
            }
            return(View());
        }