using System; using System.Collections.Generic; using System.Threading.Tasks; using FHT.Agency.Infrastructure.MsSqlConfigurations; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.Infrastructure; using Microsoft.Owin.Security.OAuth; using Owin; using System.Web.Http; using FHT.Agency.RepositoryInterfaces; using System.Linq; using System.Security.Claims; using FHT.Utilities; namespace FHT.Agency.Web { public partial class Startup { private static bool IsAjaxRequest(IOwinRequest request) { IReadableStringCollection query = request.Query; if ((query != null) && (query["X-Requested-With"] == "XMLHttpRequest")) { return true; } IHeaderDictionary headers = request.Headers; return ((headers != null) && (headers["X-Requested-With"] == "XMLHttpRequest")); } // 有关配置身份验证的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { app.CreatePerOwinContext(FhtAgentDbContext.Create); app.CreatePerOwinContext(FhtAgentUserManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active, AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), LogoutPath = new PathString("/Account/Logout"), CookieName = "FhtAgentAuthCookie", Provider = new CookieAuthenticationProvider { OnApplyRedirect = ctx => { if (!IsAjaxRequest(ctx.Request)) { ctx.Response.Redirect(ctx.RedirectUri); } } } }); const string publicClientId = "self"; var oAuthOptions = new OAuthAuthorizationServerOptions { //AuthenticationMode = AuthenticationMode.Passive, TokenEndpointPath = new PathString("/Token"), Provider = new FhtOAuthProvider(publicClientId), //see https://stackoverflow.com/questions/3487991/why-does-oauth-v2-have-both-access-and-refresh-tokens AccessTokenExpireTimeSpan = ApplicationConfig.AccessTokenExpireTimeSpan, AllowInsecureHttp = true, //really good post: https://stackoverflow.com/questions/10703532/whats-the-point-of-refresh-token?noredirect=1&lq=1 RefreshTokenProvider = new ApplicationRefreshTokenProvider() }; //UseOAuthBearerTokens internally calls UseOAuthAuthorizationServer and UseOAuthBearerAuthentication app.UseOAuthBearerTokens(oAuthOptions); } } public class FhtOAuthProvider : OAuthAuthorizationServerProvider { private readonly string _publicClientId; public FhtOAuthProvider(string publicClientId) { if (publicClientId == null) { throw new ArgumentNullException(nameof(publicClientId)); } _publicClientId = publicClientId; } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { string userName = context.UserName; string password = context.Password; FhtAgentUserManager userManager = context.OwinContext.GetUserManager(); Agency.Infrastructure.MsSqlConfigurations.DbModels.UserIdentity user = await userManager.FindAsync(userName, password); if (user == null) { context.SetError("invalid_grant", "用户名或者密码错误,请重新输入"); return; } // var companyMemberQuery = DependencyResolver.Current.GetService(); ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType); ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); //http://www.advancesharp.com/blog/1216/oauth-web-api-token-based-authentication-with-custom-database //https://developerhandbook.com/c-sharp/create-restful-api-authentication-using-web-api-jwt/ var _userRepository = (IUserRepository)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUserRepository)); var _roleClaimRepository = (IRoleClaimRepository)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IRoleClaimRepository)); Domains.Users.Abstract.User loginUser = _userRepository.Get(user.Id); Domains.RoleClaim roleClaim = _roleClaimRepository.Get(loginUser.Role); oAuthIdentity.AddClaim(new Claim("fhtuserroletype", loginUser.Role.ToInt().ToString()));//角色添加到 Identity 中 oAuthIdentity.AddClaims(roleClaim.Claims.Select(c => new Claim("fhtuserclaimtype", ((int)c).ToString()))); var ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); } public override Task TokenEndpoint(OAuthTokenEndpointContext context) { foreach (KeyValuePair property in context.Properties.Dictionary) { context.AdditionalResponseParameters.Add(property.Key, property.Value); } return Task.FromResult(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(null); } public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context) { if (context.ClientId == _publicClientId) { var expectedRootUri = new Uri(context.Request.Uri, "/"); if (expectedRootUri.AbsoluteUri == context.RedirectUri) { context.Validated(); } } return Task.FromResult(null); } public static AuthenticationProperties CreateProperties(string userName) { IDictionary data = new Dictionary { { "userName", userName } }; return new AuthenticationProperties(data); } } public class ApplicationRefreshTokenProvider : AuthenticationTokenProvider { public async Task CreateAsync(AuthenticationTokenCreateContext context) { IFormCollection form = await context.Request.ReadFormAsync(); string grantType = form.Get("grant_type"); Create(context); } public Task ReceiveAsync(AuthenticationTokenReceiveContext context) { Receive(context); return Task.FromResult(0); } public override void Create(AuthenticationTokenCreateContext context) { // Expiration time in seconds bool isProd = ApplicationEnvironment.CurrentEnvironment == ApplicationEnv.Production; context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(ApplicationConfig.RefreshTokenExpireAt); context.SetToken(context.SerializeTicket()); } public override void Receive(AuthenticationTokenReceiveContext context) { context.DeserializeTicket(context.Token); } } }