Playframework web和移动AOuth2均带有轮廓

Playframework web和移动AOuth2均带有轮廓,playframework,silhouette,Playframework,Silhouette,在使用play framework+剪影成功登录google web之后,我希望能够通过ajax请求进行访问。 表示在2个环境中使用2个控制器 Environment[User, SessionAuthenticator] Environment[User, JWTAuthenticator] 如何将web身份验证(SessionAuthenticator)与使用JWTAuthenticator的其他部分“链接”起来 ajax客户端能否使用会话cookie中的数据来构造JWT头(如何) 使

在使用play framework+剪影成功登录google web之后,我希望能够通过ajax请求进行访问。 表示在2个环境中使用2个控制器

 Environment[User, SessionAuthenticator]
 Environment[User, JWTAuthenticator]
  • 如何将web身份验证(SessionAuthenticator)与使用JWTAuthenticator的其他部分“链接”起来
  • ajax客户端能否使用会话cookie中的数据来构造JWT头(如何)
  • 使用用户定义表实现aouth2。
    公共部分类启动
    {
    公共无效配置(IAppBuilder应用程序)
    {
    ConfigureAuth(app);
    app.mapsigner();
    HttpConfiguration config=新的HttpConfiguration();
    WebApiConfig.Register(配置);
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    app.UseWebApi(配置);
    }
    }
    调用启动类
    配置OAuth(应用程序);
    公共void配置OAuth(IAppBuilder应用程序)
    {
    OAuthAuthorizationServerOptions OAuthServerOptions=新的OAuthAuthorizationServerOptions()
    {
    AllowInsecureHttp=true,
    TokenEndpointPath=新路径字符串(“/token”),
    AccessTokenExpireTimeSpan=TimeSpan.FromDays(1),
    Provider=新的SimpleAuthorizationServerProvider(),
    RefreshTokenProvider=新的SimpleRefreshTokenProvider()
    };
    //令牌生成
    使用OAuthAuthorizationServer(OAuthServerOptions);
    使用OAuthBeareAuthentication(新的OAuthBeareAuthenticationOptions());
    }
    提供者-----
    公共类SimpleAuthorizationServerProvider:OAuthAuthorizationServerProvider
    {
    公共重写异步任务ValidateClientAuthentication(OAuthValidateClientAuthenticationContext)
    {
    context.Validated();
    }
    公共重写异步任务GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentials上下文)
    {
    context.OwinContext.Response.Headers.Add(“访问控制允许来源”,新[]{“*”});
    使用(AuthRepository\u repo=new AuthRepository())
    {
    var user=wait _repo.FindUser(context.UserName,context.Password);
    if(user==null)
    {
    SetError(“无效的授权”,“用户名或密码不正确”);
    返回;
    }
    //ClaimsIdentity oAuthIdentity=wait _repo.CreateIdentityAsync(用户,
    //context.Options.AuthenticationType);
    //ClaimsIdentity cookiesIdentity=wait _repo.CreateIdentityAsync(用户,
    //CookieAuthenticationDefaults.AuthenticationType);
    //AuthenticationProperties=CreateProperties(user.UserName);
    //AuthenticationTicket=新的AuthenticationTicket(OAuthidentitity,属性);
    //上下文。已验证(票证);
    //context.Request.context.Authentication.sign(cookiesIdentity);
    }
    var identity=newclaimsidentity(context.Options.AuthenticationType);
    identity.AddClaim(新声明(“sub”,context.UserName));
    identity.AddClaim(新声明(“角色”、“用户”));
    上下文验证(身份);
    }
    公共重写异步任务GrantRefreshToken(OAuthGrantRefreshTokenContext)
    {
    var originalClient=context.Ticket.Properties.Dictionary[“as:client_id”];
    var currentClient=context.OwinContext.Get(“as:client_id”);
    //强制刷新令牌的客户端绑定
    if(originalClient!=当前客户端)
    {
    context.Rejected();
    返回;
    }
    //更改刷新令牌请求的身份验证票证的机会
    var newId=newclaimsidentity(context.Ticket.Identity);
    newId.AddClaim(新索赔(“新索赔”、“刷新令牌”));
    var newTicket=newauthenticationticket(newId,context.Ticket.Properties);
    上下文验证(newTicket);
    }
    }
    公共类SimpleRefreshTokenProvider:IAAuthenticationTokenProvider
    {
    私有静态ConcurrentDictionary_refreshTokens=新ConcurrentDictionary();
    公共异步任务CreateSync(AuthenticationTokenCreateContext上下文)
    {
    var guid=guid.NewGuid().ToString();
    //可能只是第一次创建一个句柄,然后重复使用
    _refreshTokens.TryAdd(guid,context.Ticket);
    //只考虑存储句柄的哈希值
    SetToken(guid);
    }
    公共异步任务ReceiveAsync(AuthenticationTokenReceiveContext上下文)
    {
    认证票证;
    if(_refreshtokes.TryRemove(context.Token,out ticket))
    {
    上下文。设置票证(票证);
    }
    }
    公共void创建(AuthenticationTokenCreateContext上下文)
    {
    var guid=guid.NewGuid().ToString();
    //可能只是第一次创建一个句柄,然后重复使用
    _refreshTokens.TryAdd(guid,context.Ticket);
    //只考虑存储句柄的哈希值
    SetToken(guid);
    }
    public void Receive(AuthenticationTokenReceiveContext上下文)
    {
    认证票证;
    if(_refreshtokes.TryRemove(context.Token,out ticket))
    {
    上下文。设置票证(票证);
    }
    }
    }
    回购-------------
    公共类UserManagerService:UserManager,IUserManagerService
    {
    公共用户管理服务(IUserStore用户存储)
    :base(userStore)
    {
    this.UserValidator=newuservalidator(this){AllowOnlyAlphanumericUserNames=false};
    }
    公共新店
    {
    获取{return base.Store;}
    }
    }
    公共类AuthRepository:IDisposable
    {
    私有AuthContext ctx;
    私人用户管理器(UserManager);;
    公共AuthRepository()
    {
    _ctx=新的AuthContext();
    _userManager=newusermanager(newuserstore(_ctx));
    }
    //公共异步任务注册器(UserModel UserModel)
    //{
    //IdentityUser用户=新IdentityUser
    //    {
    //UserName=userModel.UserName
    //    };
    //var result=await\u userManager
    
    Implement aouth2 with User define tables.
     public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.MapSignalR();
    
            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
        }
    }
    call startup class 
    ConfigureOAuth(app);
      public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider(),
                 RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };
    
            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    
        }
    Provider -----
      public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }
    
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
    
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
    
            using (AuthRepository _repo = new AuthRepository())
            {
                var user = await _repo.FindUser(context.UserName, context.Password);
    
                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
    
    
    
            //ClaimsIdentity oAuthIdentity = await _repo.CreateIdentityAsync(user,
            //      context.Options.AuthenticationType);
            //ClaimsIdentity cookiesIdentity = await _repo.CreateIdentityAsync(user,
            //    CookieAuthenticationDefaults.AuthenticationType);
            //AuthenticationProperties properties = CreateProperties(user.UserName);
            //AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            //context.Validated(ticket);
            //context.Request.Context.Authentication.SignIn(cookiesIdentity);
     }
               var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));
    
            context.Validated(identity);
    
        }
    
        public override async Task GrantRefreshToken( OAuthGrantRefreshTokenContext context)
    
        {
            var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
            var currentClient = context.OwinContext.Get<string>("as:client_id");
    
            // enforce client binding of refresh token
            if (originalClient != currentClient)
            {
                context.Rejected();
                return;
            }
    
            // chance to change authentication ticket for refresh token requests
            var newId = new ClaimsIdentity(context.Ticket.Identity);
            newId.AddClaim(new Claim("newClaim", "refreshToken"));
    
            var newTicket = new AuthenticationTicket(newId, context.Ticket.Properties);
            context.Validated(newTicket);
        }
    }
    
    public class SimpleRefreshTokenProvider : IAuthenticationTokenProvider
    {
        private static ConcurrentDictionary<string, AuthenticationTicket> _refreshTokens = new ConcurrentDictionary<string, AuthenticationTicket>();
    
    
        public   async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var guid = Guid.NewGuid().ToString();
    
            // maybe only create a handle the first time, then re-use
            _refreshTokens.TryAdd(guid, context.Ticket);
    
            // consider storing only the hash of the handle
            context.SetToken(guid);
        }
    
        public   async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            AuthenticationTicket ticket;
            if (_refreshTokens.TryRemove(context.Token, out ticket))
            {
                 context.SetTicket(ticket);
            }
        }
    
        public void Create(AuthenticationTokenCreateContext context)
        {
            var guid = Guid.NewGuid().ToString();
    
            // maybe only create a handle the first time, then re-use
            _refreshTokens.TryAdd(guid, context.Ticket);
    
            // consider storing only the hash of the handle
            context.SetToken(guid);
        }
    
        public void Receive(AuthenticationTokenReceiveContext context)
        {
            AuthenticationTicket ticket;
            if (_refreshTokens.TryRemove(context.Token, out ticket))
            {
                context.SetTicket(ticket);
            }
        }
    }
     Repo-------------
      public class UserManagerService : UserManager<User>, IUserManagerService<User>
    {
    
        public UserManagerService(IUserStore<User> userStore)
            : base(userStore)
        {
            this.UserValidator = new UserValidator<User>(this) { AllowOnlyAlphanumericUserNames = false };
        }
    
        public new IUserStore<User> Store
        {
            get { return base.Store; }
        }
    
    
    }
    
    
      public class AuthRepository : IDisposable
      {
       private AuthContext _ctx;
    
       private UserManager<User> _userManager;
    
       public AuthRepository() 
       {
           _ctx = new AuthContext();
           _userManager =  new UserManager<User>(new UserStore<User>(_ctx));
       }
       //public async Task<IdentityResult> RegisterUser(UserModel userModel)
       //{
       //    IdentityUser user = new IdentityUser
       //    {
       //        UserName = userModel.UserName
       //    };
    
       //    var result = await _userManager.CreateAsync(user, userModel.Password);
    
       //    return result;
       //}
    
       public async Task<User> FindUser(string userName, string password)
       {
           User user = await _userManager.FindAsync(userName, password);
    
           return user;
       }
    
       public void Dispose()
       {
           _ctx.Dispose();
           _userManager.Dispose();
    
       }
       }
    
    
      public class AuthContext : DbContext
     {
       public AuthContext()
           : base("ObjectContext")
       {
       }
       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {
    
           modelBuilder.Entity<IdentityRole>().HasKey<string>(i => i.Id).ToTable("Roles");
           modelBuilder.Entity<IdentityUser>().HasKey<string>(i => i.Id).ToTable("Users");
           modelBuilder.Entity<User>().HasKey<string>(i => i.Id).ToTable("Users");
           modelBuilder.Entity<IdentityUserClaim>().HasKey<int>(i => i.Id).ToTable("UserClaims");
           modelBuilder.Entity<IdentityUserLogin>().HasKey(q => new { q.LoginProvider, q.UserId, q.ProviderKey }).ToTable("UserLogins");
           modelBuilder.Entity<IdentityUserRole>().HasKey(q => new { q.RoleId, q.UserId }).ToTable("UserRoles");
    
           base.OnModelCreating(modelBuilder);
    
       }
    }