How to call web API under specific user permission?

陌路散爱 提交于 2019-12-04 05:49:13

问题


I have a function that allows the end user to execute a Workflow (containing many APIs) or schedule it to run as a background job.

Example: User1 creates Workflow1, which contains 3 APIs (Api1, Api2, Api3), and configures it to run at 9AM every day.

I use HttpClient to call each API like this:

var client = new HttpClient { BaseAddress = new Uri("http://localhost/") };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsJsonAsync("/api/services/myApp/workflow/Api1?input=something", "").Result;

How do I add the credentials of User1 to the request while the user is not logged in to the application (because it will run automatically as a scheduled job)?

Update 1

I decided to use reflection to call an API by string name.

In the case of executing an API directly, how do I run it under a specific permission?

Update 2

I have put my code inside a using block, but all APIs were fired successfully:

using (_session.Use(1, 3)) // 3 is the Id of User1, who has no permissions
{
    // Execute operator
    switch (input.Operator.Type)
    {
        case "api":
            executeApiResult = await ExecuteApi(input);
            break;
        case "procedure":
            executeApiResult = await ExecuteProcedure(input);
            break;
        default:
            return new ExecuteOperatorOutput
            {
                Result = new ExecuteOperatorResult { Status = false, Message = $"Wrong operator type: {input.Operator.Type}" },
                WorkflowStatus = false
            };
    }
}

回答1:


In the case of executing an API directly, how do I run it under a specific permission?

You can override current session values and call your method inside the using block.

I have put my code inside a using block, but all APIs were fired successfully

Declare your API methods as public virtual as there are some restrictions for AbpAuthorize.




回答2:


You have two options.

1- You can make those Application Services anonymously accessible. And if you want it to be secure, send an encrypted security token.

2- You didn't mention if your project is MVC or Angular. I assume you have Angular version. You need a bearer token to make authenticated requests. First you have to authenticate user and get a token. Then add this bearer token to every request.

You have to research for using bearer tokens in asp.net core...



来源:https://stackoverflow.com/questions/47031071/how-to-call-web-api-under-specific-user-permission

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!