2016-10-10 4 views
1

電子メールのリンクをクリックすると自動的にログインします。 example.com/action?_ul=blah-guid。 '_ul'を検出して自動的にユーザーにログインします。 urlはさまざまなもののうちの1つになる可能性があるので、クエリ文字列paramが存在するかどうかを検出し、この特殊キーを使用して自動的にログインします。URLクエリ文字列トークンを使用した自動ログイン

これまで、以前のIDプロバイダGlobal.asax.csApplication_BeginRequestを使用してこれを行っています。

protected void Application_BeginRequest(object sender, EventArgs e) 
{ 
    if (Request["_ul"] != null) 
    { 
     var userService = new UserService(); 
     userService.QuickLogin(Request["_ul"]); 
    } 
} 

しかし、このプロジェクトでは、我々はAsp.Netアイデンティティを使用していて、それがOwinStartup、このポイントの後に起こっているとエラーを投げているようだ:

No owin.Environment item was found in the context.

これは、初期化の中で起こりますサービス:

public UserService() 
    { 
     signInManager = HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>(); 
    } 

私はActionFilterを使用しようとしましたが、これは認証後に発生します。

私はAsp.Net IDでこれを行う方法がわかりませんが、通常のフォーム認証を保持したいと思いますが、特定のクエリ文字列値があるかどうかを検出し、現在ログインしている場合はログアウトしてからログ特別なキーを使用しています。

この追加のログインチェックを行う正しい方法は何ですか?

答えて

1

AuthorizeAttributeを実装する必要があります。あなたはトークンでユーザーを認証したいコントローラ/アクションにこの属性を適用する必要があり

using System; 
using System.Collections.Generic; 
using System.Security.Claims; 
using System.Web; 
using System.Web.Mvc; 


public class TokenAuthenticationAttribute : AuthorizeAttribute 
{ 
    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     var providedToken = filterContext.Controller.ValueProvider.GetValue("_ul").AttemptedValue; 

     // Here check if your provided token is correct one and indeed authenticates user 

     var user = // get your ApplicationUser based on your token 

     var userManager = HttpContext.Current.GetOwinContext().Get<ApplicationUserManager>(); 

     // this might be different in your code. Basically you need to crate ClaimsIdentity from ApplicationUser object 
     var identity = user.CreateIdentity(userManager, DefaultAuthenticationTypes.ApplicationCookie); 

     var claimsPrincipal = new ClaimsPrincipal(identity); 

     var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; 

     // signs out the current user 
     authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); 

     // you need this for the current request, otherwise user will be authenticated only for the next request. 
     HttpContext.Current.User = claimsPrincipal; 

     // sets the cookie for the next request 
     authenticationManager.SignIn(new AuthenticationProperties(), identity); 
    } 
} 

:私は何をしようとすると非常によく似た何かをやりました。

これにbashを付けます。私はそれが最初の試みからうまくいくとは絶対に確信していません - これは、私が持っているものの適応版です。

関連する問題