Select Git revision
ShibbolethController.cs

Marcel Nellesen authored
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
ShibbolethController.cs 3.52 KiB
using Coscine.STS.Data;
using Coscine.STS.Models;
using Coscine.STS.Utils;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Coscine.ApiCommons.Models;
using Coscine.Database.Model;
namespace Coscine.STS.Controllers
{
[Route("[controller]/[action]")]
public class ShibbolethController : Controller
{
private readonly SignInManager<CoscineUser> _signInManager;
public ShibbolethController(SignInManager<CoscineUser> signInManager)
{
_signInManager = signInManager;
}
[HttpGet]
public async Task<ActionResult> Callback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
throw new ArgumentException($"Error from external provider: {remoteError}");
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return Redirect(UrlGenerator.GetLoginUrl(Request));
}
ExternalAuthenticatorModel externalAuthenticatorModel = new ExternalAuthenticatorModel();
var shibbolethAuthItem = externalAuthenticatorModel.GetWhere((externalAuthenticator) => externalAuthenticator.DisplayName == "Shibboleth");
ExternalIdModel externalIdModel = new ExternalIdModel();
var identifier = info.Principal.FindFirstValue(ShibbolethAttributeMapping.Identifier);
identifier = identifier.Substring(identifier.IndexOf(">") + 1);
identifier = identifier.Substring(0, identifier.IndexOf("<"));
var mapping = externalIdModel.GetAllWhere((map) => map.ExternalId_Column == identifier && map.ExternalAuthenticatorId == shibbolethAuthItem.Id);
User user;
UserPlainModel userPlainModel = new UserPlainModel(Program.Configuration);
if (mapping.Count() > 0)
{
var userId = mapping.First().UserId;
user = userPlainModel.GetById(userId);
}
else
{
user = ShibbolethAttributeMapping.CreateUser(info.Principal);
userPlainModel.Insert(user);
externalIdModel.Insert(new ExternalId
{
ExternalId_Column = identifier,
ExternalAuthenticatorId = shibbolethAuthItem.Id,
UserId = user.Id
});
}
var coscineUser = new CoscineUser()
{
UserName = user.Id.ToString(),
Email = user.EmailAddress
};
var result = await _signInManager.UserManager.CreateAsync(coscineUser);
result = await _signInManager.UserManager.AddLoginAsync(coscineUser, info);
await _signInManager.SignInAsync(coscineUser, isPersistent: false);
return Redirect(UrlGenerator.ExtendReturnUrl(returnUrl, Request));
}
[HttpPost]
public ActionResult Login(string returnUrl)
{
var provider = "Saml2";
var redirectUrl = Program.MainUrl + "/Shibboleth/Callback?returnUrl=" + returnUrl;
redirectUrl = UrlGenerator.ExtendReturnUrl(redirectUrl, Request);
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
}
}