簡體   English   中英

Webapi具有針對不同用戶的多個oauth令牌

[英]Webapi with multiple oauth tokens for different users

我正在使用oauth作為授權提供程序在asp.net中創建自己的webapi。 api wil基本上可以作為我稱之為不同模塊的提供者。 一個可以是圖庫,另一個可以是具有不同類型用戶的用戶登錄模塊。

我有oauth部分工作正常。 Api用戶可以通過使用登錄憑據調用/ Token端點來注冊然后請求令牌。

但是我現在想在api中創建另一個單獨的用戶模塊,只有注冊的apiusers才能訪問。 我希望這個模塊有另一個注冊和登錄功能,並有自己的端點登錄(/ UserModuleToken或類似的東西)。 來自用戶模塊的用戶是與Api用戶不同的用戶。 因此apiusers是想要在我的api中調用特定模塊的實際開發人員,而用戶模塊中的用戶是在實現該模塊的站點上注冊的用戶。

我的所有apicontrollers都將擁有api用戶的[Authorize]屬性,我想要特定的屬性,例如用戶模塊中的某些功能,用[UserModuleAuthorize]屬性進行修飾。

您可以在下面看到我的api用戶實體模型:

public class ApiUserEntity : BaseEntity
{
    public string Username { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
    public string Salt { get; set; }
    public ApiUserLevel Level { get; set; }
}

可以驗證api用戶的userservice函數:

public UserLoginResult LoginUser(ApiUserEntityLoginForm userForm)
{
    // retrieve user from database
    var user = _userRepository.GetUser(userForm.UserName);

    if(user == null)
        return _modelStateWrapper.AddError(UserLoginResult.UserNotFound, "User does not exist");

    var passwordHash = PasswordHash.HashPassword(user.Salt, userForm.Password);

    // check if password matches with database.
    if (passwordHash != user.Password)
        return _modelStateWrapper.AddError(UserLoginResult.IncorrectPassword, "Incorrect password");

    return UserLoginResult.Success;
}

在我的webapi中調用/ Token端點將調用令牌提供程序的以下函數:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{

    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

    // create a userloginform object : 
    var loginForm = new ApiUserEntityLoginForm {UserName = context.UserName, Password = context.Password};

    // pass it into the login validation function of the userservice:
    var loginResult = _userService.LoginUser(loginForm);

    // if login result was not sucesful, return an error.
    if (loginResult != UserLoginResult.Success)
    {
        var jsonSerialiser = new JavaScriptSerializer();
        var json = jsonSerialiser.Serialize(_userService.Errors());

        context.SetError("invalid_grant", json);
        return;
    }

    // result was succesful, grant the token.
    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
    identity.AddClaim(new Claim("sub", context.UserName));
    identity.AddClaim(new Claim("role", "user"));

    context.Validated(identity);

}

我配置我的oauth提供程序並使用以下函數定義/ Token端點:

public static void ConfigureOAuth(IAppBuilder app, IUnityContainer container)
{

    var simpleAuthorizationServerProvider = container.Resolve<SimpleAuthorizationServerProvider>();

    var OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = simpleAuthorizationServerProvider
    };

    // Token Generation
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

}

現在我的問題是,是否有可能擁有多個令牌端點,因此我可以為apiusers提供令牌,然后為使用自定義用戶模塊的用戶提供另一個令牌,並根據這2個用戶保護某些功能。

經過大量的互聯網搜索,我找不到任何相關信息。 所以我開始相信這不是好的做法或不可能。 如果有人能夠指出我正確的方向,這將是偉大的!

我相信您需要根據角色配置用戶授權,您嘗試做的只是使您的解決方案復雜化。 您可以執行以下操作:內部方法GrantResourceOwnerCredentials您需要從DB存儲(即“Admin”)獲取經過身份驗證的用戶的正確角色,然后將其添加為類型為“Role”的聲明,如下面的代碼所示:

identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
identity.AddClaim(new Claim(ClaimTypes.Role, "Supervisor"));

現在在您的控制器上,您只需要具有角色“Admin”的用戶訪問; 您需要使用[Authorize(Roles="Admin")]或多個角色[Authorize(Roles="Admin,User")]進行歸因

這是實現目標的最直接方式。

來自http://bitoftech.net的這段代碼,對嗎? 很高興看到我的代碼示例使用:)如果您需要進一步說明,請告訴我。

暫無
暫無

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

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