簡體   English   中英

如何在ASP.NET單頁應用程序(SPA)中從移動設備登錄並獲取令牌

[英]How to login and get token from mobile device in ASP.NET Single Page App (SPA)

當我創建默認的SPA模板項目時,VS2013將創建MeController。 如果從站點登錄,請致電Get我有一個用戶信息。 如何登錄並從移動設備獲取令牌? 我嘗試

POST "/Token?userName=someuser%40gmail.com&password=SomeAlpha%2B12345-Password&grant_type=password"

回應為

{
"readyState": 4,
"responseText": "{\"error\":\"invalid_client\"}",
"responseJSON": {
    "error": "invalid_client"
},
"status": 400,
"statusText": "Bad Request"
}

StartupAuth.cs:

public partial class Startup
{
    // Enable the application to use OAuthAuthorization. You can then secure your Web APIs
    static Startup()
    {
        PublicClientId = "web";

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            AuthorizeEndpointPath = new PathString("/Account/Authorize"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            AllowInsecureHttp = true
        };
    }

    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public static string PublicClientId { get; private set; }

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(20),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);
    }

我自己找到了答案:

我在ApplicationOAuthProvider類中重寫了ValidateClientAuthentication:

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider 
{
    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        var clientIdParam = context.Parameters.Get("client_id");
        if (context.ClientId == null && clientIdParam == "mobile"))
        {
            context.Validated();
        }

        return Task.FromResult<object>(null);
    }

網址:

POST "/Token" 

要求正文:

userName=someuser%40gmail.com&password=SomePassword&grant_type=password&clientId=mobile"

響應主體:

 {"access_token":"6EtSNgXOqI8uN8TXXXXXXXXG2Hd46B2j3A6eOApAm12j","token_type":"bearer","expires_in":1209599,"userName":"someuser@gmail.com",".issued":"Wed, 27 Jan 2016 13:30:25 GMT",".expires":"Wed, 10 Feb 2016 13:30:25 GMT"}

這是一個很棒的教程,用於在WebAPI和任何類型的客戶端之間啟用基於令牌的身份驗證,在這種情況下,客戶端是AngularJS SPA應用程序。

http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM