Force claim on user - asp.net-mvc

I integrated with and old Active Directive through LDAP, where some users are to be looked up.
If I find the user, it should have access - no additional requirements.
I have a specific page, which I have placed a restriction on, so that only user from MyGroup can see. When I go to the site, I get redirected to my Login-page and get a nice ReturnUrl, but I get a 401 back for the page.
EPiServer refuses to let me in, although I can see I actual get my user.
How can I tell EPiServer, that a given user is allowed access?
I created my own LoginController, which calls a method like this:
public AuthenticationResult SignInAsLdapUser(string username, string password)
{
var principalContext = new PrincipalContext(/*...*/);
isAuthenticated = principalContext.ValidateCredentials(username, password);
if (!isAuthenticated)
return;
var userPrincipal = UserPrincipal.FindByIdentity(principalContext, username);
//Attempt to force additional claims on user
var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
identity.AddClaim(new Claim(ClaimTypes.Role, "MyGroup")); //Group I am trying to add
HttpContext.Current.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.Current.GetOwinContext().Authentication.SignIn(new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.Now.AddMinutes(30),
AllowRefresh = true
}, identity);
return new AuthenticationResult();
}
in my web.config I specified the group MyGroup:
<virtualRoles addClaims="true">
<providers>
...
<add name="CmsEditors" type="EPiServer.Security.MappedRole, EPiServer.Framework" roles="MyGroup, ..." mode="Any"/>
...
</providers>
</virtualRoles>
In my startup.cs I specified the built-in Identity and cookies:
public void Configuration(IAppBuilder app)
{
app.AddCmsAspNetIdentity<ApplicationUser>(); //OWIN from EPiServer
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
AuthenticationMode = AuthenticationMode.Active,
CookieSecure = CookieSecureOption.Always,
LoginPath = new PathString("/Login"),
CookieName = "MyCookie",
ExpireTimeSpan = TimeSpan.FromDays(7),
ReturnUrlParameter = "ReturnUrl",
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator
.OnValidateIdentity<ApplicationUserManager<ApplicationUser>, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => manager.GenerateUserIdentityAsync(user)),
OnApplyRedirect = context => context.Response.Redirect(context.RedirectUri),
OnResponseSignIn = context => context.Response.Redirect(GetReturnUrl()),
}
});
app.UseStageMarker(PipelineStage.Authenticate);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
}

Related

ASP.NET MVC 5 Owin Identity got lost before allowed ExpiresUtc

public void ConfigureAuth(IAppBuilder app)
{
app.UseKentorOwinCookieSaver(PipelineStage.Authenticate);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Login"),
LogoutPath = new PathString("/Logout"),
CookieSecure = CookieSecureOption.SameAsRequest ,
SlidingExpiration = true,
CookieName = ".app",
CookieHttpOnly = true,
CookiePath = "/",
CookieDomain = Domain
});
My sign in method:
private void IdentitySignin(AppUserState appUserState, bool isPersistent = false)
{
var Browser = Request.Browser + Request.Browser.Version;
var claims = new List<Claim>
{
// create required claims
new Claim(ClaimTypes.NameIdentifier, appUserState.UserId),
new Claim(ClaimTypes.Name, appUserState.Name),
new Claim(ClaimTypes.Role, appUserState.RoleName),
new Claim(ClaimTypes.UserData, Browser.GetHashCode().ToString()),
// User State Info
new Claim("userState", appUserState.ToString())
};
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties()
{
AllowRefresh = true,
IsPersistent = isPersistent,
//Dictionary = { { "RememberMe", isPersistent ? "true" : "false" } },
ExpiresUtc = isPersistent ? DateTime.UtcNow.AddHours(3) : DateTime.UtcNow.AddMinutes(20)
}, identity);
}
I'm expecting that cookie should be alive for 3 hours, but it expires after less than 15 minutes.
It works as expected on local, but this happens only when i deploy to IIS.
Should I set asp.net session timeout to be same as expiration timeout?
Should I include any other IIS configuration?
After long research, I found that I have to add the following line to my web.config file
<system.web>
<sessionState mode="StateServer" timeout="1200" cookieless="false" />
</system.web>

Azure AD Auto signing out after signin

So ive gone through as many posts as I can, and I cant seem to sort this out!
My client wants us to allow logging into their ADFS via an MVC platform that I have built, so I am trying to allow them to sign into their Azure AD to sign into the platform.
When I am redirected to my signin page for Azure AD(MS Login), I type in my credentials and then it looks like it is doing a quick redirect loop and then automatically signs me out, I am going crazy!!!
Below is everything I have setup:
On Azure AD:
Created App service and put ApplicationId and TenantId in my Web.config
<add key="ida:ClientId" value="ApplicationID from AzureAD" />
<add key="ida:Tenant" value="TenantId from AzureAD" />
<add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}" />
<add key="ida:RedirectUri" value="https://sitename.azurewebsites.net/Home/Index" />
<add key="ida:PostLogoutRedirectUri" value="https://sitename.azurewebsites.net" />
On Startup.Auth.cs
public partial class Startup
{
// Calling the keys values from Web.config file
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
// Concatenate aadInstance, tenant to form authority value
private string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
// ConfigureAuth method
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
//app.UseCookieAuthentication(new CookieAuthenticationOptions());
//Enable the application to use a cookie to store information for the signed in user
//and to use a cookie to temporarily store information about a user logging in with a third party login provider
//Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = (context) =>
{
context.HandleResponse();
context.OwinContext.Response.Redirect("/Home/Index");
return Task.FromResult(0);
}
}
});
} // end - ConfigureAuth method
On my routeConfig : This was done so that my custom landing page can be loaded first, on this page is a button saying "Enter platform", which the client will click on and go to Azure AD signin(MS Login page)
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapRoute("Default", "{controller}/{action}/{id}", new
{
controller = "Account",
action = "Login",
id = UrlParameter.Optional
}).RouteHandler = new DashRouteHandler();
}
}
Account Controller
[Authorize]
public void SignIn()
{
clsHomeScreen clsHomeScreen = new clsHomeScreen();
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
Response.Redirect("/");
}
[AllowAnonymous]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult Login(string returnUrl)
{
// We do not want to use any existing identity information
EnsureLoggedOut();
// Store the originating URL so we can attach it to a form field
var viewModel = new AccountLoginModel { ReturnUrl = returnUrl };
return View(viewModel);
}
HomeController - This is where it SHOULD be redirected to after signing in, but its not:
[Authorize]
public async Task<ActionResult> Index()
{
HomeScreenLists HS = new HomeScreenLists();
IEnumerable<Challenges> ActiveChallenges;
IEnumerable<Challenges> PrivateChallenges;
string loggedInUserId = "";
string loggedInEmail = "";
var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
string email = userClaims?.FindFirst(System.IdentityModel.Claims.ClaimTypes.Name)?.Value;
string firstname = userClaims?.FindFirst(System.IdentityModel.Claims.ClaimTypes.GivenName)?.Value;
string lastname = userClaims?.FindFirst(System.IdentityModel.Claims.ClaimTypes.Surname)?.Value;
string userId = "";
//The Email will not contain an #(i.e. an email address) if not using Azure AD to sign in.
if (!email.Contains("#"))
{
loggedInUserId = User.Identity.GetUserId();
goto LoggedInUser_Found;
}
if (TempData["LoggedInEmail"] != null)
{
if (email != TempData["LoggedInEmail"].ToString())
{
userId = clsHomeScreen.GetUserId(TempData["LoggedInEmail"].ToString());
}
else
{
userId = clsHomeScreen.GetUserId(email);
}
}
if (email != null)
{
userId = clsHomeScreen.GetUserId(email);
}
if (userId == null || userId == "")
{
clsUsers clsUsers = new clsUsers();
if (TempData["LoggedInEmail"] != null)
{
loggedInEmail = TempData["LoggedInEmail"].ToString();
var userDetails = clsUsers.GetUsers().Where(x => x.Email == loggedInEmail).FirstOrDefault();
loggedInUserId = userDetails.Id;
}
else
{
if(userId == null)
{
await RegisterAAD();
userId = clsHomeScreen.GetUserId(email);
loggedInUserId = userId;
}
else
{
loggedInUserId = User.Identity.GetUserId();
}
}
}
else
{
loggedInUserId = userId;
}
LoggedInUser_Found:
int iBU = (int)db.Users.FirstOrDefault(x => x.Id == loggedInUserId).fkiBusinessUnitId;
if (iBU == 0)
{
HS.HasBU = false;
TempData["HasBU"] = "No";
TempData["UserId"] = loggedInUserId;
}
else
{
HS.HasBU = true;
TempData["HasBU"] = "Yes";
TempData["UserId"] = loggedInUserId;
}
bool isAdmin = false;
if (User.IsInRole("Administrator"))
{
isAdmin = true;
}
ActiveChallenges = clsChallenges.GetActiveChallenges();
PrivateChallenges = clsChallenges.GetPrivateChallenges(loggedInUserId, isAdmin);
HS.HomeScreenList = clsHomeScreen.GetHomeScreenAdverts();
HS.ActiveChallengesList = ActiveChallenges;
HS.PrivateChallengesList = PrivateChallenges;
HS.UserId = loggedInUserId;
return View(HS);
}
So if I remove the [Authorize] attribute on the Index ActionResult, then it does a continuous redirect loop.
What ive tried:
I have tried using the KentorCookiSaver, which didnt work.
Recreating the app service
Changed the redirectUrl in Azure AD App Registration
Someone even spoke about rewriting the cookies, which I tried, but dont know if I followed the steps correctly, the link is Here
Ive tried so many things that I cant even remember what ive tried. Could anyone possibly help with what I am doing wrong, please.
Thanks a million!
So with some help from someone who knows these things, my problem was solved.
Ultimately what it came down to was:
I needed to add the RedirectUri into my Web.config and into my Startup.Auth
Web.Config
<add key="ida:RedirectUri" value="https://sitename.azurewebsites.net/Home/Index"/>
Startup.Auth
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
RedirectUri = redirectUri,
PostLogoutRedirectUri = postLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = (context) =>
{
context.HandleResponse();
context.OwinContext.Response.Redirect("/Home/Index");
return Task.FromResult(0);
}
}
});
My Signin process kept routing back to my Account/Login page when failing, when it should have routed to my Home/Index, as I was using my Account/Login as my landing page and authentication only happening there after, the problem that happened here was because I did an "EnsureLogOut" on the Account/Login, thus why it kept logging me out first before wanting to authenticate. So instead of the Redirect = "/" I changed as follows:
public void SignIn()
`{`
`clsHomeScreen clsHomeScreen = new clsHomeScreen();`
`if (!Request.IsAuthenticated)`
`{`
`HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/Home/Index" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);`
`}`
`Response.Redirect("/Home/Index");`
`}`
Perhaps this is something that might not help others, but maybe it helps them in the right direction.

Asp.Net Mvc "Remember Me" not working on server

I am developing web application with asp.net mvc.
It's seems to work in local, but in a shared hosting, It last for about 10 minutes then logout.
Here is the code:
AccountController.cs
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
var context = Request.GetOwinContext();
var authenticationManager = context.Authentication;
authenticationManager.SignIn(new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddDays(90), IsPersistent = true }, identity);
return RedirectToAction("Index", "Dashboard");
Startup.cs
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
CookieName = "social",
CookieSecure = CookieSecureOption.Never
});
}
Solving my problem by adding machine key, hope helps someone

WSO2 Identity Server with OpenId Connect

I am trying to use WSO2 Identity Server (5.1.0) with Asp.Net MVC, as a proof of concept i created a sample asp.net MVC project in visual studio 2015.
Following the WSO2 Guide, i have configured the identity server as required.
https://docs.wso2.com/display/IS510/OpenID+Connect+with+the+WSO2+Identity+Server+and+WSO2+OAuth2+Playground
On the sample application, i have added reference to Microsoft.Owin.Security.OpenIdConnect and added code to ConfigureAuth in Startup.Auth.cs file.
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
// Enables the application to remember the second login verification factor such as phone or email.
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
// This is similar to the RememberMe option when you log in.
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = "SENmQQ9fOWcrqXjK1u3lXINhXtEa",
ClientSecret = "bFBJQqj4GT2Wfv8735fTTuHh3Isa",
Authority = "https://localhost:9443",
RedirectUri = "https://wso2openid.local.co.uk/Account/ExternalLoginCallback",
SignInAsAuthenticationType = "ClientCredCookie",
ResponseType = "id_token token",
Scope = "openid",
Configuration = new OpenIdConnectConfiguration
{
AuthorizationEndpoint = "https://localhost:9443/oauth2/authorize",
TokenEndpoint = "https://localhost:9443/oauth2/token"
},
Notifications = new OpenIdConnectAuthenticationNotifications()
{
RedirectToIdentityProvider = n =>
{
return Task.FromResult(0);
},
SecurityTokenReceived = n =>
{
return Task.FromResult(0);
},
AuthorizationCodeReceived = n =>
{
return Task.FromResult(0);
},
SecurityTokenValidated = n =>
{
var token = n.ProtocolMessage.AccessToken;
// persist access token in cookie
if (!string.IsNullOrEmpty(token))
{
n.AuthenticationTicket.Identity.AddClaim(
new Claim("access_token", token));
}
return Task.FromResult(0);
},
AuthenticationFailed = notification =>
{
if (string.Equals(notification.ProtocolMessage.Error, "access_denied", StringComparison.Ordinal))
{
notification.HandleResponse();
notification.Response.Redirect("/");
}
return Task.FromResult<object>(null);
}
}
});
}
When i run the application, on login it redirects to WSO2 Identity Server login and manage to login but when it redirect to Account\ExternalLoginCallback, the logininfo is always null.
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
Any advise as to why this is not working will be appreciated.?
NB: I tried to put a break point on SecurityTokenValidated but it did not hit that break point. The only breakpoint which i got hit was RedirectToIdentityProvider.
It's work well for me:
Step1 : Config WSO2 with this:
https://docs.wso2.com/display/IS570/Logging+in+to+a+.NET+application+using+the+Identity+Server
Step2:
public async Task<RedirectResult> LoginOAuth()
{
var url = "https://localhost:9443/oauth2/authorize?response_type=code&client_id=5a8urZQAc0r4R7iUS9ar1wOoq9Ma&scope=openid&redirect_uri=http://localhost:49545/Home/GetCode";
var client = new HttpClient();
var response = await client.GetAsync(url);
string urlDistance = response.RequestMessage.RequestUri.ToString();
client.Dispose();
return Redirect(urlDistance);
}
public async Task<RedirectToRouteResult> GetCode()
{
//باشد GetCode همشون حتما باید
var client = new HttpClient();
string code = Request.QueryString["code"];
string sessionState = Request.QueryString["session_state"];
string client_id = Request.QueryString["client_id"];
client.Dispose();
//از طریق ارسال کد میخواد توکن رو بگیره
//****************
var values = new Dictionary<string, string>
{
{ "code", code },
{ "sessionState", sessionState },
{ "client_id", "5a8urZQAc0r4R7iUS9ar1wOoq9Ma" },
{ "client_secret", "b0yefcCc4ftVYJm7ffQi2IZZ0eMa" },
{ "grant_type", "authorization_code" },
{ "redirect_uri", "http://localhost:49545/Home/GetCode" }//??????????????
};
var content = new FormUrlEncodedContent(values);
client = new HttpClient();
var response2 = await client.PostAsync("https://localhost:9443/oauth2/token", content);
string responseString = await response2.Content.ReadAsStringAsync();
JObject jsonResult = JObject.Parse(responseString);
string access_token = jsonResult["access_token"].ToString();
string refresh_token = jsonResult["refresh_token"].ToString();
string scope = jsonResult["scope"].ToString();
string id_token = jsonResult["id_token"].ToString();
string token_type = jsonResult["token_type"].ToString();
string expires_in = jsonResult["expires_in"].ToString();
//**************
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://localhost:9443/oauth2/userinfo?schema=openid");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token);
string result = await httpClient.GetStringAsync("/oauth2/userinfo?schema=openid");
return RedirectToAction("Contact");
}

authenticate both mvc controller and api controller from one login entry

I use Web API2 and MVC5 in the same project with Asp.net Identity 2 for authentication and authorization, for Web APIs I use AngularJs as front end framework,
Now I need to make one login entry for both controllers, MVC controllers and Apicontrollers
this code for my configuration function
public void Configure(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
app.CreatePerOwinContext(TemplateEntities.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
ExpireTimeSpan = TimeSpan.FromMinutes(5),
LoginPath = new PathString("/Home/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
// Enables the application to remember the second login verification factor such as phone or email.
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
// This is similar to the RememberMe option when you log in.
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
}
}
and this my provider code
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
private readonly string _publicClientId;
public ApplicationOAuthProvider(string publicClientId)
{
if (publicClientId == null)
{
throw new ArgumentNullException("publicClientId");
}
_publicClientId = publicClientId;
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var signInManager = context.OwinContext.Get<ApplicationSignInManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
//userManager.lo
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
var result = await signInManager.PasswordSignInAsync(context.UserName, context.Password, true, shouldLockout: false);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}
return Task.FromResult<object>(null);
}
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// Resource owner password credentials does not provide a client ID.
if (context.ClientId == null)
{
context.Validated();
}
return Task.FromResult<object>(null);
}
public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context.ClientId == _publicClientId)
{
Uri expectedRootUri = new Uri(context.Request.Uri, "/");
if (expectedRootUri.AbsoluteUri == context.RedirectUri)
{
context.Validated();
}
}
return Task.FromResult<object>(null);
}
public static AuthenticationProperties CreateProperties(string userName)
{
IDictionary<string, string> data = new Dictionary<string, string>
{
{ "userName", userName }
};
return new AuthenticationProperties(data);
}
}
I used this line to authorize MVC Controllers
var result = await signInManager.PasswordSignInAsync(context.UserName, context.Password, true, shouldLockout: false);
and this to set token cookie for APIs
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
in my GrantResourceOwnerCredentials function in previous provider code
Now the problem is APIs run perfectly with authenticated user
but when decorating MVC Controller action with [authorize] attribute it doesn't run in spite of this line var result = await signInManager.PasswordSignInAsync(context.UserName, context.Password, true, shouldLockout: false); runs successfully

Resources