2017-03-02 1 views
1

おそらく私は間違った検索語を使用していますが、Aurelia-AuthenticationをServiceStackで使いやすくする方法についての情報はありません。私はウェブサイトで使用されている超複雑な認証方式にはとても慣れていないので、意味がわからないものを試していると、おそらく混乱していると思われます。私がやろうとしているのは、ユーザーがWindowsの資格情報を使用してログインできるようにすることですが、私のWebアプリケーションには展開用にIISが必要です(自己ホスティング)。だから、私はユーザー名/パスワードを送信し、認証されたセッション情報を格納するためにAureliaが利用可能なものをservicestackに返す必要があります。今、私はJWTを使う方向に傾いています。ここでAurelia-Self-Serviceedサービスを使用した認証

は、私はクライアント側(オーレリア)の上に持っているものです。

main.ts

import { Aurelia } from 'aurelia-framework'; 
import 'src/helpers/exceptionHelpers' 
import config from "./auth-config"; 

export function configure(aurelia: Aurelia) { 
    aurelia.use 
     .standardConfiguration() 
     .feature('src/resources') 
     .developmentLogging() 
     .plugin('aurelia-dialog') 
     .plugin('aurelia-api', config => { 
      // Register an authentication hosts 
      config.registerEndpoint('auth', 'http://localhost:7987/auth/'); 
     }) 
     .plugin('aurelia-authentication', (baseConfig) => { 
      baseConfig.configure(config); 
     }); 

    aurelia.start().then(x => x.setRoot('src/app')); 
} 

のauth-config.ts

var config = { 
    endpoint: 'auth',    // use 'auth' endpoint for the auth server 
    configureEndpoints: ['auth'], // add Authorization header to 'auth' endpoint 

    // The API specifies that new users register at the POST /users enpoint 
    signupUrl: null, 
    // The API endpoint used in profile requests (inc. `find/get` and `update`) 
    profileUrl: null, 
    // Logins happen at the POST /sessions/create endpoint 
    loginUrl: '', 
    // The API serves its tokens with a key of id_token which differs from 
    // aurelia-auth's standard 
    accessTokenName: 'BearerToken', 
    // Once logged in, we want to redirect the user to the welcome view 
    loginRedirect: '#/pending', 
    // The SPA url to which the user is redirected after a successful logout 
    logoutRedirect: '#/login', 
    // The SPA route used when an unauthenticated user tries to access an SPA page that requires authentication 
    loginRoute : '#/help' 
}; 

export default config; 

login.ts

import { AuthService } from 'aurelia-authentication'; 
import { inject, computedFrom } from 'aurelia-framework'; 

@inject(AuthService) 
export class Login { 
    heading: string; 
    auth: AuthService; 
    userName: string; 
    password: string; 

    constructor(authService) { 
     this.auth = authService; 
     this.heading = 'Login'; 
    } 

    login() { 
     var credentials = { 
      username: this.userName, 
      password: this.password, 
      grant_type: "password" 
     }; 
     return this.auth.login(credentials, 
           { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } 
     ).then(response => { 
       console.log("success logged " + response); 
      }) 
      .catch(err => { 
       console.log("login failure"); 
      }); 
    }; 
} 

AppHost(se rviceStack):

public override void Configure(Container container) 
    { 
     var privateKey = RsaUtils.CreatePrivateKeyParams(RsaKeyLengths.Bit2048); 
     var publicKey = privateKey.ToPublicRsaParameters(); 
     var privateKeyXml = privateKey.ToPrivateKeyXml(); 
     var publicKeyXml = privateKey.ToPublicKeyXml(); 

     SetConfig(new HostConfig 
     { 
#if DEBUG 
      DebugMode = true, 
      WebHostPhysicalPath = Path.GetFullPath(Path.Combine("~".MapServerPath(), "..", "..")), 
#endif 
     }); 
     container.RegisterAs<LDAPAuthProvider, IAuthProvider>(); 
     container.Register<ICacheClient>(new MemoryCacheClient { FlushOnDispose = false }); 
     container.RegisterAs<MemoryCacheClient, ICacheClient>(); 
     Plugins.Add(new AuthFeature(() => new AuthUserSession(), 
      new[] { 
       container.Resolve<IAuthProvider>(), 
       new JwtAuthProvider { 
         HashAlgorithm = "RS256", 
         PrivateKeyXml = privateKeyXml, 
         RequireSecureConnection = false, 
        } 
      }) 
     { 
      HtmlRedirect = "~/#/pending", 
      IncludeRegistrationService = false, 
      IncludeAssignRoleServices = false, 
      MaxLoginAttempts = Settings.Default.MaxLoginAttempts 
     }); 
    } 

私はアクセスを制限したいServiceInterfaceにAuthenticate属性を持っています。

最後にLDAPプロバイダ:これまで

public class LDAPAuthProvider : CredentialsAuthProvider 
{ 
    private readonly IHoldingsManagerSettings _settings; 

    public LDAPAuthProvider(IHoldingsManagerSettings settings) 
    { 
     _settings = settings; 
    } 
    public override bool TryAuthenticate(IServiceBase authService, string userName, string password) 
    { 
     //Check to see if the username/password combo is valid, an exception will be thrown if the username or password is wrong 
     try 
     { 
      var entry = new DirectoryEntry($"LDAP://{_settings.Domain}", userName, password); 
      var nativeObject = entry.NativeObject; 
      using (var identity = new WindowsIdentity(userName)) 
      { 
       var principal = new WindowsPrincipal(identity); 
       return principal.IsInRole(_settings.AdminGroupName); 
      } 
     } 
     catch (Exception) 
     { 
      //This means the username/password combo failed 
      return false; 
     } 
    } 

    public override IHttpResult OnAuthenticated(IServiceBase authService, 
               IAuthSession session, 
               IAuthTokens tokens, 
               Dictionary<string, string> authInfo) 
    { 
     //Fill IAuthSession with data you want to retrieve in the app eg: 
     session.DisplayName = "Testy McTesterson"; 
     //... 

     //Call base method to Save Session and fire Auth/Session callbacks: 
     return base.OnAuthenticated(authService, session, tokens, authInfo); 

     //Alternatively avoid built-in behavior and explicitly save session with 
     //authService.SaveSession(session, SessionExpiry); 
     //return null; 
    } 
} 

、私は限りServiceStackは、LDAPプロバイダでの要求を受けて取得するために管理してログインしようとすると、認証が成功しますが、リクエストが来るとき戻るaurelia-authenticationは、ServiceStackがセッション情報に返すものの形式が気に入らない。

私はここで何が起こっているのか、私の理解には間違いありません。もし誰かが正しい方法で進めてくれると私を指摘できたら、本当に感謝しています。

編集1

は 'BearerToken' から 'accessTokenName' を変更し、少なくともペイロードのセットを取得しているようです。しかし、依然としてクライアント側で失敗した認証を取得しています。 Aurelia-Authenticationにセッションをクッキーに格納する方法を理解する必要もあります。

編集2

多くのデバッグした後、それはすべてが正常に動作していることが表示されます、問題は、ログインが成功した後、私は認証されなければならないの呼び出しを行うページにリダイレクトしてしまうことがあります。しかし、私は問題servicestack JsonServiceClientを使用して認証JWTトークンを渡すを持っています、ここを参照してください: ServiceStack Javascript JsonServiceClient missing properties

答えて

1

は、このスレッドの範囲を超えての理由(上記LDAPproviderが本番に展開するときに、あなたが期待するように動作しませんが判明します)。

System.DirectoryServicesへの参照を含める場合。予想通り

public override bool TryAuthenticate(IServiceBase authService, string userName, string password) 
{ 
    //Check to see if the username/password combo is valid, an exception will be thrown if the username or password is wrong 
    try 
    { 
     var entry = new DirectoryEntry($"LDAP://{_settings.Domain}", userName, password); 
     var nativeObject = entry.NativeObject; 

     var ctx = new PrincipalContext(ContextType.Domain, _settings.Domain); 
     var user = UserPrincipal.FindByIdentity(ctx, userName); 
     if (user == null) 
     { 
      return false; 
     } 

     var group = GroupPrincipal.FindByIdentity(ctx, _settings.AdminGroupName); 
     if (group == null) 
     { 
      return false; 
     } 

     return user.IsMemberOf(group); 
    } 
    catch (Exception) 
    { 
     //This means the username/password combo failed 
     return false; 
    } 
} 

すべてが動作するはずです:AccountManagement

とは、以下の方法を変更します。

関連する問題