Obtain user email from Mastodon API via OAuth - .net-core

Is it possible to obtain user email through Mastodon Api? I'm working on adding OAuth authentication via Mastodon Api but only seem to get "id" and "display_name" using "/api/v1/accounts/verify_credentials" endpoint. I do not see a property returned for email so currently just using "acct" parameter. I'm using both "read:accounts" and "admin:read:accounts" scopes. This is for an NetCore application.
builder.Services.AddAuthentication()
.AddMicrosoftAccount("Microsoft", "Microsoft", microsoftOptions =>
{
microsoftOptions.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
microsoftOptions.ClientId = _appSettings.Authentication.Microsoft.ClientId;
microsoftOptions.ClientSecret = _appSettings.Authentication.Microsoft.ClientSecret;
})
.AddGoogle("Google", "Google", googleOptions =>
{
googleOptions.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
googleOptions.ClientId = _appSettings.Authentication.Google.ClientId;
googleOptions.ClientSecret = _appSettings.Authentication.Google.ClientSecret;
})
.AddGitHub("GitHub", "GitHub", githubOptions =>
{
githubOptions.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
githubOptions.ClientId = _appSettings.Authentication.GitHub.ClientId;
githubOptions.ClientSecret = _appSettings.Authentication.GitHub.ClientSecret;
})
.AddOAuth("Fosstodon", "Fosstodon", fosstodonOptions =>
{
fosstodonOptions.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
fosstodonOptions.ClientId = _appSettings.Authentication.Fosstodon.ClientId;
fosstodonOptions.ClientSecret = _appSettings.Authentication.Fosstodon.ClientSecret;
fosstodonOptions.CallbackPath = new PathString("/signin-fosstodon");
fosstodonOptions.AuthorizationEndpoint = _appSettings.Authentication.Fosstodon.AuthorizationEndpoint;
fosstodonOptions.TokenEndpoint = _appSettings.Authentication.Fosstodon.TokenEndpoint;
fosstodonOptions.UserInformationEndpoint = _appSettings.Authentication.Fosstodon.UserInformationEndpoint;
fosstodonOptions.SaveTokens = true;
fosstodonOptions.Scope.Add("read:accounts");
fosstodonOptions.Scope.Add("admin:read:accounts");
fosstodonOptions.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
fosstodonOptions.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
fosstodonOptions.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
fosstodonOptions.Events = new OAuthEvents
{
OnCreatingTicket = async context =>
{
var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
response.EnsureSuccessStatusCode();
var user = JObject.Parse(await response.Content.ReadAsStringAsync());
var identifier = user.Value<string>("id")?.Clean();
if (!string.IsNullOrEmpty(identifier))
{
context.Identity?.AddClaim(new Claim(
ClaimTypes.NameIdentifier, identifier,
ClaimValueTypes.String, context.Options.ClaimsIssuer));
}
var userName = user.Value<string>("display_name")?.Clean();
if (!string.IsNullOrEmpty(userName))
{
context.Identity?.AddClaim(new Claim(
ClaimTypes.Name, userName,
ClaimValueTypes.String, context.Options.ClaimsIssuer));
}
var userEmail = user.Value<string>("acct")?.Clean();
if (!string.IsNullOrEmpty(userEmail))
{
context.Identity?.AddClaim(new Claim(
ClaimTypes.Email, userEmail,
ClaimValueTypes.String, context.Options.ClaimsIssuer));
}
}
};
});
Really wanting to know if their is an endpoint that will return current user email address. I have looked through Mastodon Api documentation but not seeing and enpoint for this.

Found that it is not posible to obtain user email through Mastodon Api. Instead decided to handel this situation in the registration process of application authentication flow. Basicly check if a user exists with given email. If so then remove the auto provision user and add external provider information to existing user. Later will submit verify email, to email address provided, to avoid someone from stealing user account through registration.
/// <summary>
/// Handle postback from new registration
/// </summary>
/// <returns>IActionResult</returns>
[AllowAnonymous]
[HttpPost("Registration/New")]
[HttpPost("Registration/New/{id?}")]
[ValidateAntiForgeryToken]
public virtual async Task<IActionResult> New([Bind(RegistrationViewModel.BindProperties)] RegistrationViewModel model, [FromForm(Name = "Button")] string button)
{
// Check if cancled
if (button.Clean() != "submit")
return RedirectToAction("Index", "Home");
// Check email is valid
if (!model.Email.Clean().IsValidEmail())
ModelState.AddModelError(nameof(model.Email), _sharedLocalizer["ErrorMessage.Invalid"]);
if (ModelState.IsValid)
{
// setup results
IdentityResult identityResult = new IdentityResult();
// Check for existing user
ApplicationUser user = await _userManager.FindByEmailAsync(model.Email.Clean());
if (user != null)
{
if (user.Id != model.Id.Clean())
{
ApplicationUser removeUser = await _userManager.FindByIdAsync(model.Id.Clean());
if (removeUser != null)
{
identityResult = await _userManager.DeleteAsync(removeUser);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
}
}
}
else
{
user = await _userManager.FindByIdAsync(model.Id.Clean());
if (user == null)
throw new KeyNotFoundException($"[Key]: {nameof(model.Id)} [Value]: {model.Id}");
}
user.DisplayName = model.DisplayName.Clean();
user.UserName = model.Email.Clean();
user.NormalizedUserName = model.Email.Clean();
user.Email = model.Email.Clean();
user.NormalizedEmail = model.Email.Clean();
identityResult = await _userManager.UpdateAsync(user);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
if (!string.IsNullOrEmpty(model.ProviderUserId.Clean()))
{
var userLogins = await _userManager.GetLoginsAsync(user);
UserLoginInfo? userLogin = userLogins
.Where(x => x.LoginProvider == model.Provider.Clean())
.Where(x => x.ProviderKey == model.ProviderUserId.Clean())
.FirstOrDefault();
if (userLogin == null)
{
identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(model.Provider.Clean(), model.ProviderUserId.Clean(), model.Provider.Clean()));
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
}
}
}
return View(model);
}

Related

Multiple objects to single endpoint with asp.net

I'm building a Restful API with asp.net core. I have an endpoint that are used to authenticate users. I have two kinds of Users where one is an Admin and one is "FilmStudio". I succesfully managed to authenticte the User (Admin) but i also need to be able to authenticate the FilmStudio with username and password. Is there anyway I can do this with a single endpoint?
This is my endpoint form the UsersController:
[AllowAnonymous]
[HttpPost("Authenticate")]
public IActionResult Authenticate([FromBody] UserDto model)
{
var user = _userRepo.Authenticate(model.UserName, model.Password);
if (user !=null)
{
if (user == null)
{
return BadRequest("The username or password is incorrect.");
}
return Ok(new
{
Id = user.UserId,
Username = user.UserName,
Role = user.Role,
Token = user.Token
});
}
else
{
var filmStudioDto = new FilmStudioDto();
var studio = _studioRepo.Authenticate(model.Name, model.Password);
if (studio == null)
{
return BadRequest("The username or password is incorrect.");
}
return Ok(new
{
Id = studio.StudioId,
Username = studio.Name,
City = studio.City,
Role = studio.Role,
Token = studio.Token
});
}
}
}
When im giving the username and password for the admin user it works. However when im trying to enter the username and passwod for FilmStudio I allways get the error messsage that says: "The username or password is incorrect."
[AllowAnonymous]
[HttpPost("Authenticate")]
public IActionResult Authenticate([FromBody] UserDto model)
{
if (model.UserName != null) // Check if UserName is null or not
{
var user = _userRepo.Authenticate(model.UserName, model.Password);
if (user == null)
{
return BadRequest("The username or password is incorrect.");
}
return Ok(new
{
Id = user.UserId,
Username = user.UserName,
Role = user.Role,
Token = user.Token
});
}
else
{
var studio = _studioRepo.Authenticate(model.StudioName, model.StudioPassword);
if (studio == null)
{
return BadRequest("The username or password is incorrect.");
}
return Ok(new
{
Id = studio.StudioId,
Username = studio.Name,
City = studio.City,
Role = studio.Role,
Token = studio.Token
});
}
}
}
you can try to use instead of model.Name model.UserName for studio too
else
{
var studio = _studioRepo.Authenticate(model.UserName, model.Password);
if (studio == null)
return BadRequest("The username or password is incorrect.");
return Ok( new FilmStudioDto
{
Id = studio.StudioId,
Username = studio.Name,
City = studio.City,
Role = studio.Role,
Token = studio.Token
});
}
and IMHO you can fix user part too
if (user !=null)
return Ok(new UserDto
{
Id = user.UserId,
Username = user.UserName,
Role = user.Role,
Token = user.Token
});

Get Claims in a WebApi Control from a JWT Token

This is my first time attempting to use Asp.Net Core Web Api. I have everything working including authentication and jwt token creation and verification. What I am trying to do is extract the user information that is in the token and use some of it when posting data to the database. I create the token like this:
public string NewToken(string ApiKey, ICAN_Context context)
{
var user = context.TblUserLogins.Where(x => x.ApiKey == ApiKey).FirstOrDefault();
int? CompanyId = context.TblEmployeeCompanies.Where(x => x.EmployeeId == user.EmployeeId).Select(x => x.CompanyId).FirstOrDefault();
var identity = new ClaimsIdentity();
identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
identity.AddClaim(new Claim("CompanyId", CompanyId.ToString(), ClaimValueTypes.Integer32));
identity.AddClaim(new Claim("EmployeeCompanyId", user.EmployeeCompanyId.ToString(), ClaimValueTypes.Integer32 ));
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(identity),
Expires = DateTime.UtcNow.AddMinutes(60),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(secretKey), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwtString = tokenHandler.WriteToken(token);
return jwtString;
}
I verify the token using a "filter":
public void OnAuthorization(AuthorizationFilterContext context)
{
var tokenManager = (ITokenManager)context.HttpContext.RequestServices.GetService(typeof(ITokenManager));
var result = true;
if(!context.HttpContext.Request.Headers.ContainsKey("Authorization"))
{
result = false;
}
string token = string.Empty;
if(result)
{
token = context.HttpContext.Request.Headers.First(x=>x.Key == "Authorization").Value;
try
{
var claimPrinciple = tokenManager.VerifyToken(token);
}
catch(Exception ex)
{
result = false;
context.ModelState.AddModelError("Unauthorized", ex.ToString());
}
}
if(!result)
{
context.Result = new UnauthorizedObjectResult(context.ModelState);
}
}
I have no problem retrieving the claims info from the token, my question is how do I get the claims from the token in my controller method?
I want to be able to retrieve its values in my methods something like this:
[HttpPost]
[Route("~/api/entity/department")]
public IActionResult CreateDepartment([FromBody] TblCompanyDepartmentsXlu department)
{
var identity = (ClaimsIdentity)User.Identity;
_context.Departments.Add(department);
_context.SaveChanges();
return Ok("Department created successfully!");
}
I also tried this from StackOverflow:
public static ClaimsPrincipal VerifyToken(string jwtToken)
{
TokenManager tokenManager = new TokenManager();
SecurityToken validatedToken;
TokenValidationParameters validationParameters = new TokenValidationParameters();
validationParameters.ValidateLifetime = true;
validationParameters.IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(tokenManager.secretKey);
validationParameters.ValidateAudience = false;
validationParameters.ValidateIssuer = false;
ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(jwtToken, validationParameters, out validatedToken);
return principal;
}
[HttpGet]
[Route("~/api/entity/GetEmployees")]
public List<TblEmployees> GetEmployees()
{
var identity = HttpContext.User.Identity as ClaimsIdentity;
if (identity != null)
{
IEnumerable<Claim> claims = identity.Claims;
}
var employees = _context.Employees.ToList();
return employees;
}
but identity.Claims is ALWAYS 0.
I am able to retrieve the claims right after verifying the token:
var claimPrinciple = TokenManager.VerifyToken(token);
I am able to retrieve the claims info here
var claims = claimPrinciple.Identities.First().Claims.ToList();
int? CompanyId = Convert.ToInt32(claims.Where(x => x.Type == "CompanyId").FirstOrDefault().Value);
int EmployeeCompanyId = Convert.ToInt32(claims.Where(x => x.Type == "EmployeeCompanyId").FirstOrDefault().Value);
But I am unable to retrieve them in the controller.
//startup.cs dotnet 6.0 :
builder.Services.AddHttpContextAccessor();
.
.
.
//where you want to use the IHttpContextAccessor :
//For example in user repository :
private readonly IHttpContextAccessor _httpContextAccessor;
public UserRepository(IHttpContextAccessor httpContextAccessor) =>
_httpContextAccessor = httpContextAccessor;
public void LogCurrentUser()
{
var username = _httpContextAccessor.HttpContext.User.Identity.Name;
// ...
}
#Klekmek was correct. All I needed to do was use the built-in JWT token functionality (which I didn't know existed). I removed the AuthenticationFilter and added this to my startup:
To the ConfigureServices section:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwt => {
var key = Encoding.ASCII.GetBytes(Configuration["JwtConfig:Secret"]);
jwt.SaveToken = true;
jwt.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateLifetime = true,
ValidateIssuer = false,
ValidateAudience = false
};
});
And the Configure section:
app.UseAuthentication();
After adding that, this worked:
var identity = HttpContext.User.Identity as ClaimsIdentity;

How do I get the user info for whom the jwt token was issued?

I have created a token based authentication in my asp.net core application .When I post with the proper login model , it gives me the token. Now I want to to know how I can Get the info of the user for which this token is generated .
This is the code to create the token. Let me know if I can help with any other information.
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.UserName);
if (user != null)
{
var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
if (result.Succeeded)
{
var claims = new List<Claim>()
{
new Claim(JwtRegisteredClaimNames.Sub,user.Email),
new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName,user.UserName)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:key"]));
var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
_config["Tokens:Issuer"],
_config["Tokens:Audience"],
claims,
expires: DateTime.UtcNow.AddMinutes(20),
signingCredentials: cred );
var results = new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo
};
return Created("", results);
}
}
}
return BadRequest();
You can get user information by ClaimsIdentity like this
var userIdentity = (User.Identity as ClaimsIdentity);
string userName = userIdentity.FindFirst(JwtRegisteredClaimNames.UniqueName).Value;
string email = userIdentity.FindFirst(JwtRegisteredClaimNames.Sub).Value;
string guid = userIdentity.FindFirst(JwtRegisteredClaimNames.Jti).Value;
then change the var claims = new [] to var claims = new List<Claim>()
Or register the IHttpContextAccessor in DI and get it from Constructor to access the HttpContext.User
var claimsIdentity = _contextAccessor.HttpContext.User.Identity as ClaimsIdentity;
var userName = claimsIdentity?.FindFirst(JwtRegisteredClaimNames.UniqueName);
This link maybe helpful for you
After some searching, I have found a solution . You can get the user info from the token
[HttpGet]
public IActionResult GetUser([FromHeader]string token)
{
var stream = token;
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(stream);
var tokenS = handler.ReadToken(stream) as JwtSecurityToken;
var jti = tokenS.Claims.First(claim => claim.Type == "sub").Value;
return Created("", jti);
}

Retrieving email from Facebook Login in ASP.NET MVC throwing null exception

I am developing an ASP.NET MVC application. In my application, I need to provide Faccebook Login service to user. Besides, I need retrieve the user email from Facebook and store in the database.
I am using Visual Studio 2013 and ASP.NET MVC5. My Facebook login method is working fine. But when I retrieve email from Facebook, it is giving me null exception. My externalLoginCallback method is below:
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie);
if (result == null || result.Identity == null)
{
return RedirectToAction("Login");
}
var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier);
if (idClaim == null)
{
return RedirectToAction("Login");
}
var login = new UserLoginInfo(idClaim.Issuer, idClaim.Value);
var name = result.Identity.Name == null ? "" : result.Identity.Name.Replace(" ", "");
//retrieving email from facebook here
var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
var email = emailClaim.Value;//this line is throwing null exception
.
.
.
}
I commented where error throw in my code.
This is how I configured Facebook in Startup.Auth.cs
var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
{
AppId = "x",
AppSecret = "y"
};
facebookAuthenticationOptions.Scope.Add("email");
app.UseFacebookAuthentication(facebookAuthenticationOptions);
I also tried like this:
app.UseFacebookAuthentication(new FacebookAuthenticationOptions
{
AppId = "x",
AppSecret = "y",
Scope = { "email" },
Provider = new FacebookAuthenticationProvider
{
OnAuthenticated = context =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
return Task.FromResult(true);
}
}
});
Both are not working. What is wrong with my code and how can I fix it?
You can try this:
var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
{
AppId = "xxxxxxx",
AppSecret = "xxxxxx",
BackchannelHttpHandler = new FacebookBackChannelHandler(),
UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name,location"
};
and then define this class:
public class FacebookBackChannelHandler : HttpClientHandler
{
protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
if (!request.RequestUri.AbsolutePath.Contains("/oauth"))
{
request.RequestUri = new Uri(request.RequestUri.AbsoluteUri.Replace("?access_token", "&access_token"));
}
var response = await base.SendAsync(request, cancellationToken);
return response;
}
}
finally, you can get email (and first_name,last_name,location) by doing the following in "ExternalLoginCallback" method in account controller:
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("LoginRegister");
}
// GET MAIL AND NAME
var email = loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email).Value;
var name= loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

Redirecting with credentials to another website

I have two websites A and B. On A I have the login option and if the user is authenticated I need to send it to B with same credentials. I have access to the code of both websites. My first approach was trying to log the user on A and figure out how could I make a Post to a action method on a controller on B(this is a recurrent question here in stackoverflow) I found this website and I don't know if it is useful: http://www.codeproject.com/Articles/833007/Redirect-and-POST-in-ASP-NET-MVC. My second approach is putting all the data that I wanted to submit to B in Browser Session, call a Redirect to B and then in a method("GET") try to read all that data and check if I can proceed with the logic on B.
I want to know which is the best approach to make this happen, and also if the later is wrong or not.
I have this code on my website A:
[HttpPost]
public ActionResult Login(LoginModel user)
{
//hardcoding InternalUser
user.AccountType = ((int)AccountTypeEnum.Internal).ToString();
var validator = new LoginModelValidator();
var result = validator.Validate(user);
if (!result.IsValid)
{
return View((LoginModelDecorator) user);
}
var service = new AuthenticationServiceAgent(user.Username, user.Password);
var securityService = new SecurityServiceAgent(service.GeToken());
var state = securityService.ProcessAccount(service.GeToken() != null, user.Username);
if (state == (int)UserAccessEnum.Processed)
{
var type = securityService.GetAccountTypeByUser(user.Username);
//CHeck user type
var accountType = Enum.GetName(typeof(AccountTypeEnum), int.Parse(user.AccountType));
var types = type.Split(',').Select(n => n.Split(':')[0]).ToList();
var containsTheUserType = user.AccountType == "1"
? types.Contains("XXX") || types.Contains(accountType)
: types.Contains(accountType);
if (containsTheUserType)
{
//var cPrincipal = service.GetClaims();
var claims = securityService.GetIdentity().Select(claim => new Claim(claim.ClaimType, claim.Value)).ToList();
if (claims.Count != 0)
{
var cPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Custom"));
type.Split(',')
.ToList()
.ForEach(
ty =>
cPrincipal.Identities.First()
.AddClaim(new Claim("http://claims/custom/accounttype", ty)));
var token = new SessionSecurityToken(cPrincipal)
{
IsReferenceMode = true
};
FederatedAuthentication.WSFederationAuthenticationModule.SetPrincipalAndWriteSessionToken(
token, true);
Session["SEC_TOKEN"] = service.GeToken();
//Do I need to post?: SecurityToken, types and claims
//here is where I am redirecting the user
return Redirect("http://localhost:12345/Account/Login");
}
ModelState.AddModelError("LoginError", "Invalid Username or Password!");
}
ModelState.AddModelError("AccountTypeError", "You don't have access");
}
switch (state)
{
case (int)UserAccessEnum.BlockedAccount:
ModelState.AddModelError("StateError", "Your account is Blocked");
break;
case (int)UserAccessEnum.ChangePassword:
ModelState.AddModelError("StateError", "You need to change your password");
break;
case (int)UserAccessEnum.NoProcessed:
ModelState.AddModelError("StateError", "Error, please contact the system administrator");
break;
}
return View((LoginModelDecorator) user);
}
In my website B:
public ActionResult Login()
{
List<Claim> claims = //I need to get the claims from somewhere SESSION?
var type = //type used in the other Loging method
var securityToken = //securityToken used on the other Login method
if (claims.Count != 0)
{
var cPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Custom"));
type.Split(',')
.ToList()
.ForEach(
ty =>
cPrincipal.Identities.First()
.AddClaim(new Claim("http://claims/custom/accounttype", ty)));
var token = new SessionSecurityToken(cPrincipal)
{
IsReferenceMode = true
};
FederatedAuthentication.WSFederationAuthenticationModule.SetPrincipalAndWriteSessionToken(
token, true);
Session["SEC_TOKEN"] = securityToken;
return RedirectToAction("Index", "Home");
}
return null;
}
Any idea of how to complete the gaps that I have?

Resources