Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.31 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Claims;
  5. using System.Security.Principal;
  6. using System.Threading.Tasks;
  7. using IdentityModel;
  8. using IdentityServer4.Events;
  9. using IdentityServer4.Extensions;
  10. using IdentityServer4.Services;
  11. using IdentityServer4.Stores;
  12. using IdentityServer4.Test;
  13. using Microsoft.AspNetCore.Authentication;
  14. using Microsoft.AspNetCore.Http;
  15. using Microsoft.AspNetCore.Mvc;
  16. using MindsUnited.Authority.Api.Models;
  17. using MindsUnited.Authority.Api.Services;
  18.  
  19. namespace MindsUnited.Authority.Api.Controllers
  20. {
  21.     [SecurityHeaders]
  22.     public class AccountController : Controller
  23.     {
  24.         private readonly TestUserStore _users;
  25.         private readonly IIdentityServerInteractionService _interaction;
  26.         private readonly IEventService _events;
  27.         private readonly AccountService _account;
  28.  
  29.         public AccountController(
  30.             IIdentityServerInteractionService interaction,
  31.             IClientStore clientStore,
  32.             IHttpContextAccessor httpContextAccessor,
  33.             IAuthenticationSchemeProvider schemeProvider,
  34.             IEventService events,
  35.             TestUserStore users = null)
  36.         {
  37.             _users = users ?? new TestUserStore(TestUsers.Users);
  38.             _interaction = interaction;
  39.             _events = events;
  40.             _account = new AccountService(interaction, httpContextAccessor, schemeProvider, clientStore);
  41.         }
  42.  
  43.         [HttpGet]
  44.         public async Task<IActionResult> Login(string returnUrl)
  45.         {
  46.             var vm = await _account.BuildLoginViewModelAsync(returnUrl);
  47.  
  48.             var prov = vm.VisibleExternalProviders.First();
  49.  
  50.             var props = new AuthenticationProperties()
  51.             {
  52.                 RedirectUri = Url.Action("ExternalLoginCallback"),
  53.                 Items =
  54.                 {
  55.                     { "returnUrl", returnUrl }
  56.                 }
  57.             };
  58.  
  59.             if (AccountOptions.WindowsAuthenticationSchemeName == prov.AuthenticationScheme)
  60.             {
  61.                 var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName);
  62.                 if (result?.Principal is WindowsPrincipal wp)
  63.                 {
  64.                     props.Items.Add("scheme", AccountOptions.WindowsAuthenticationSchemeName);
  65.  
  66.                     var id = new ClaimsIdentity(prov.AuthenticationScheme);
  67.                     id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name));
  68.                     id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name));
  69.  
  70.                     foreach (Claim wpClaim in wp.Claims)
  71.                     {
  72.                         id.AddClaim(new Claim(wpClaim.Type, wpClaim.Value));
  73.                     }
  74.  
  75.                     if (AccountOptions.IncludeWindowsGroups)
  76.                     {
  77.                         var wi = wp.Identity as WindowsIdentity;
  78.                         var groups = wi?.Groups?.Translate(typeof(NTAccount));
  79.                         if (groups != null)
  80.                         {
  81.                             var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value));
  82.                             id.AddClaims(roles);
  83.                         }
  84.                     }
  85.  
  86.                     await HttpContext.SignInAsync(
  87.                         IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme,
  88.                         new ClaimsPrincipal(id),
  89.                         props);
  90.                     return Redirect(props.RedirectUri);
  91.                 }
  92.  
  93.                 return Challenge(AccountOptions.WindowsAuthenticationSchemeName);
  94.             }
  95.  
  96.             props.Items.Add("scheme", prov.AuthenticationScheme);
  97.             return Challenge(props, prov.AuthenticationScheme);
  98.         }
  99.  
  100.         [HttpGet]
  101.         public async Task<IActionResult> ExternalLoginCallback()
  102.         {
  103.             var result = await HttpContext.AuthenticateAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme);
  104.             if (result?.Succeeded != true)
  105.             {
  106.                 throw new Exception("External authentication error");
  107.             }
  108.  
  109.             var externalUser = result.Principal;
  110.             var claims = externalUser.Claims.ToList();
  111.  
  112.             var userIdClaim = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject);
  113.             if (userIdClaim == null)
  114.             {
  115.                 userIdClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
  116.             }
  117.             if (userIdClaim == null)
  118.             {
  119.                 throw new Exception("Unknown userid");
  120.             }
  121.  
  122.             claims.Remove(userIdClaim);
  123.             var provider = result.Properties.Items["scheme"];
  124.             var userId = userIdClaim.Value;
  125.  
  126.             var user = _users.FindByExternalProvider(provider, userId);
  127.             if (user == null)
  128.             {
  129.                 user = _users.AutoProvisionUser(provider, userId, claims);
  130.             }
  131.  
  132.             user.Claims.Remove(user.Claims
  133.                 .SingleOrDefault(c => c.Type.Equals("name") && c.Issuer.Equals("LOCAL AUTHORITY")));
  134.  
  135.             var additionalClaims = new List<Claim>();
  136.  
  137.             var sid = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId);
  138.             if (sid != null)
  139.             {
  140.                 additionalClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value));
  141.             }
  142.  
  143.             AuthenticationProperties props = null;
  144.             var idToken = result.Properties.GetTokenValue("id_token");
  145.             if (idToken != null)
  146.             {
  147.                 props = new AuthenticationProperties();
  148.                 props.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = idToken } });
  149.             }
  150.  
  151.             await _events.RaiseAsync(new UserLoginSuccessEvent(provider, userId, user.SubjectId, user.Username));
  152.             await HttpContext.SignInAsync(user.SubjectId, user.Username, provider, props, claims.ToArray());
  153.  
  154.             await HttpContext.SignOutAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme);
  155.  
  156.             var returnUrl = result.Properties.Items["returnUrl"];
  157.             if (_interaction.IsValidReturnUrl(returnUrl) || Url.IsLocalUrl(returnUrl))
  158.             {
  159.                 return Redirect(returnUrl);
  160.             }
  161.  
  162.             return Redirect("~/");
  163.         }
  164.  
  165.         [HttpGet]
  166.         public async Task<IActionResult> Logout(string logoutId)
  167.         {
  168.             var model = await _account.BuildLogoutViewModelAsync(logoutId);
  169.             var vm = await _account.BuildLoggedOutViewModelAsync(model.LogoutId);
  170.  
  171.             var user = HttpContext.User;
  172.             if (user?.Identity.IsAuthenticated == true)
  173.             {
  174.                 await HttpContext.SignOutAsync();
  175.  
  176.                 await _events.RaiseAsync(new UserLogoutSuccessEvent(user.GetSubjectId(), user.GetDisplayName()));
  177.             }
  178.  
  179.             if (vm.TriggerExternalSignout)
  180.             {
  181.                 string url = Url.Action("Logout", new { logoutId = vm.LogoutId });
  182.  
  183.                 return SignOut(new AuthenticationProperties { RedirectUri = url }, vm.ExternalAuthenticationScheme);
  184.             }
  185.  
  186.             return Redirect(vm.PostLogoutRedirectUri ?? "~/");
  187.         }
  188.     }
  189. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement