本文整理汇总了C#中Microsoft.Owin.Security.AuthenticationProperties类的典型用法代码示例。如果您正苦于以下问题:C# AuthenticationProperties类的具体用法?C# AuthenticationProperties怎么用?C# AuthenticationProperties使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
AuthenticationProperties类属于Microsoft.Owin.Security命名空间,在下文中一共展示了AuthenticationProperties类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
//var client = new UserClient();
//var result = client.Login(request, out status, out message);
//using (AuthRepository _repo = new AuthRepository())
//{
// IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
// if (user == null)
// {
// context.SetError("invalid_grant", "The user name or password is incorrect.");
// return;
// }
//}
//create identity
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
//var identity = new ClaimsIdentity("Embedded");
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim("role", "user"));
// create metadata to pass on to refresh token provider
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{ "as:client_id", context.ClientId }
});
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
}
示例2: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var allowedOrigin = "*";
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
if (!user.EmailConfirmed)
{
context.SetError("invalid_grant", "User did not confirm email.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{"audience", context.ClientId ?? string.Empty }
});
var ticket = new AuthenticationTicket(oAuthIdentity, props);
context.Validated(ticket);
}
示例3: GoogleOAuth2Configuration
public void GoogleOAuth2Configuration(IAppBuilder app)
{
app.UseAuthSignInCookie();
var option = new GoogleOAuth2AuthenticationOptions()
{
ClientId = "581497791735.apps.googleusercontent.com",
ClientSecret = "-N8rQkJ_MKbhpaxyjdVYbFpO",
};
app.UseGoogleAuthentication(option);
app.Run(async context =>
{
if (context.Authentication.User == null || !context.Authentication.User.Identity.IsAuthenticated)
{
var authenticationProperties = new AuthenticationProperties();
authenticationProperties.Dictionary.Add("access_type", "custom_accessType");
authenticationProperties.Dictionary.Add("approval_prompt", "custom_approval_prompt");
authenticationProperties.Dictionary.Add("login_hint", "custom_login_hint");
context.Authentication.Challenge(authenticationProperties, "Google");
await context.Response.WriteAsync("Unauthorized");
}
});
}
示例4: GrantResourceOwnerCredentials
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
// Dummy check here, you need to do your DB checks against membership system http://bit.ly/SPAAuthCode
if (context.UserName != context.Password)
{
context.SetError("invalid_grant", "The user name or password is incorrect");
//return;
return Task.FromResult<object>(null);
}
var identity = new ClaimsIdentity("JWT");
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "Manager"));
identity.AddClaim(new Claim(ClaimTypes.Role, "Supervisor"));
var props =
new AuthenticationProperties(
new Dictionary<string, string>
{
{
"audience",
context.ClientId ?? string.Empty
}
});
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
return Task.FromResult<object>(null);
}
示例5: AddNonceToMessage
protected override void AddNonceToMessage(OpenIdConnectMessage message)
{
if (message == null)
{
throw new ArgumentNullException("message");
}
var properties = new AuthenticationProperties();
var nonce = Options.ProtocolValidator.GenerateNonce();
properties.Dictionary.Add(
NonceProperty, nonce);
message.Nonce = nonce;
//computing the hash of nonce and appending it to the cookie name
string nonceKey = GetNonceKey(nonce);
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Secure = Request.IsSecure,
};
var nonceId = Convert.ToBase64String(Encoding.UTF8.GetBytes((Options.StateDataFormat.Protect(properties))));
Response.Cookies.Append(
nonceKey,
nonceId,
cookieOptions);
}
示例6: Login
public ActionResult Login(LoginModel model, string returnUrl)
{
if (model.UserName == model.Password) //valdiate credentials there
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, model.UserName),
new Claim(ClaimTypes.Email, "[email protected]"),
new Claim(ClaimTypes.Role, "Administrator"),
new Claim("Custom", "Custom Claim Value")
};
var id = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType);
var authenticationManager = this.Request.GetOwinContext().Authentication;
var authProperties = new AuthenticationProperties() { IsPersistent = true };
authenticationManager.SignIn(authProperties, id);
if (Url.IsLocalUrl(returnUrl))
{
Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
return View();
}
示例7: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (var userPasswordStore = _userPasswordStoreFactory())
{
var user = await userPasswordStore.FindByNameAsync(context.UserName);
if (user == null)
{
context.SetError("invalid_grant", "No user by that user name exists.");
return;
}
var passwordHash = await userPasswordStore.GetPasswordHashAsync(user);
if (_passwordHasher.VerifyHashedPassword(passwordHash, context.Password) == PasswordVerificationResult.Failed)
{
context.SetError("invalid_grant", "The password is incorrect.");
return;
}
ClaimsIdentity oauthIdentity = user.CreateIdentity(OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = user.CreateIdentity(CookieAuthenticationDefaults.AuthenticationType);
var properties = new AuthenticationProperties(new Dictionary<string, string> { { "userName", user.UserName } });
var ticket = new AuthenticationTicket(oauthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
}
示例8: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
IFormCollection formCollection = await context.Request.ReadFormAsync();
CaptchaData captcha = new CaptchaData()
{
CaptchaChallenge = context.UserName,
CaptchaResponse = context.Password,
UserHostAddress = context.Request.LocalIpAddress,
ClientId = context.ClientId
};
CaptchaOutput captchaOutput = await this.ValidateCaptcha(captcha);
if (captchaOutput == null || !captchaOutput.Status)
{
context.SetError("invalid_captcha", "Mã bảo vệ chưa đúng, bạn vui lòng nhập lại!");
}
else
{
ApplicationUserManager userManager = OwinContextExtensions.GetUserManager<ApplicationUserManager>(context.OwinContext);
ApplicationUser user = await userManager.FindAsync("e7c44459-837c-45f2-b125-2b639d84ea45", "[email protected]");
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync((UserManager<ApplicationUser>)userManager, "Bearer");
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync((UserManager<ApplicationUser>)userManager, "Cookies");
AuthenticationProperties properties = new AuthenticationProperties();
properties.Dictionary.Add(new KeyValuePair<string, string>("client_id", captchaOutput.ClientId));
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
}
示例9: ValidateTicket
public async Task<AuthenticationTicket> ValidateTicket(IOwinRequest request, IOwinContext context, HttpClient httpClient,
string ticket, AuthenticationProperties properties, string service)
{
// Now, we need to get the ticket validated
string validateUrl = _options.CasServerUrlBase + "/validate" +
"?service=" + service +
"&ticket=" + Uri.EscapeDataString(ticket);
HttpResponseMessage response = await httpClient.GetAsync(validateUrl, request.CallCancelled);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
String validatedUserName = null;
var responseParts = responseBody.Split('\n');
if (responseParts.Length >= 2 && responseParts[0] == "yes")
validatedUserName = responseParts[1];
if (!String.IsNullOrEmpty(validatedUserName))
{
var identity = new ClaimsIdentity(_options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, validatedUserName, "http://www.w3.org/2001/XMLSchema#string", _options.AuthenticationType));
identity.AddClaim(new Claim(ClaimTypes.Name, validatedUserName, "http://www.w3.org/2001/XMLSchema#string", _options.AuthenticationType));
var authenticatedContext = new CasAuthenticatedContext(context, identity, properties);
await _options.Provider.Authenticated(authenticatedContext);
return new AuthenticationTicket(authenticatedContext.Identity, authenticatedContext.Properties);
}
return new AuthenticationTicket(null, properties);
}
示例10: Login
public ActionResult Login(string userName, string password)
{
var user = Authenticate(userName, password);
if (user != null)
{
var claims = new[] { new Claim(ClaimTypes.Name, userName) };
var identity = new ClaimsIdentity(
claims,
DefaultAuthenticationTypes.ApplicationCookie,
ClaimTypes.Name,
ClaimTypes.Role);
foreach (var role in user.Roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, role));
}
// Tell OWIN the identity provider, optional
// identity.AddClaim(new Claim(IdentityProvider, "Simplest Auth"));
var properties = new AuthenticationProperties
{
IsPersistent = false,
};
Authentication.SignIn(properties, identity);
return RedirectToAction("index", "home");
}
return View("index", "Could not log you in");
}
示例11: CreateTicket
public AuthenticationTicket CreateTicket(IdentityUser user, string clientId = null)
{
var tokenExpiration = TimeSpan.FromDays(1);
var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
identity.AddClaim(new Claim("UserId", user.Id));
identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
identity.AddClaim(new Claim("role", "user"));
foreach (var claim in user.Claims)
{
identity.AddClaim(new Claim(claim.ClaimType, claim.ClaimValue));
}
var props = new AuthenticationProperties()
{
IssuedUtc = DateTime.UtcNow,
ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
};
props.Dictionary.Add("as:client_id", clientId ?? string.Empty);
props.Dictionary.Add("userName", user.UserName);
props.Dictionary.Add("userId", user.Id);
var ticket = new AuthenticationTicket(identity, props);
return ticket;
}
示例12: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
var user = await _userService.Authenticate(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"as:client_id", context.ClientId ?? string.Empty
},
{
"userName", context.UserName
}
});
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
}
示例13: GrantResourceOwnerCredentials
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
user = Mapper.Map<UserModel>(await userService.FindAsync(context.UserName, context.Password));
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
else
{
ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
// Proporties
IDictionary<string, string> prop = new Dictionary<string, string>()
{
{ "username", user.UserName },
{ "id", user.Id}
};
// Add dictionary to auth proporties
AuthenticationProperties proporties = new AuthenticationProperties(prop);
AuthenticationTicket ticket = new AuthenticationTicket(identity, proporties);
context.Validated(ticket);
}
}
示例14: ClaimsIdentity
public override async Task GrantResourceOwnerCredentials
(OAuthGrantResourceOwnerCredentialsContext context)
{
// validate user credentials (demo!)
// user credentials should be stored securely (salted, iterated, hashed…)
if (!((context.UserName == "[email protected]" && context.Password == "test123")||
(context.UserName == "[email protected]" && context.Password == "test123")))
{
context.Rejected();
return;
}
// create identity
var id = new ClaimsIdentity("Embedded");
id.AddClaim(new Claim("sub", context.UserName));
id.AddClaim(new Claim("role", "user"));
id.AddClaim(new Claim("privileges", "Admin,AccountViewer,AccountSubmit"));
// create metadata to pass on to refresh token provider
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{"client_key", context.ClientId}
});
var ticket = new AuthenticationTicket(id, props);
context.Validated(ticket);
}
示例15: GrantResourceOwnerCredentials
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var allowedOrigin = context.OwinContext.Get<string>(OAuthDefaults.OwinKeyAllowedOrigin) ?? "*";
context.OwinContext.Response.Headers.Add(OAuthDefaults.HeaderKeyAllowedOrigin, new[] { allowedOrigin });
if (ValidateUserNameAndPassword != null && !ValidateUserNameAndPassword(context.UserName, context.Password))
{
context.SetError("invalid_grant", "The user name or password is incorrect");
return Task.FromResult<object>(null);
}
var identity = new ClaimsIdentity(OAuthDefaults.TokenFormat);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(OAuthDefaults.ClaimKeySub, context.UserName));
identity.AddClaim(new Claim(OAuthDefaults.ClaimKeySite, context.Request.Uri.Host.Split('.')[0]));
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
OAuthDefaults.HeaderKeyClientId, context.ClientId ?? string.Empty
},
{
OAuthDefaults.HeaderKeyUserName, context.UserName
}
});
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
return Task.FromResult<object>(null);
}