How to authenticate WPF Client request to ASP .NET WebAPI 2

后端 未结 1 384
抹茶落季
抹茶落季 2021-02-04 14:19

I just created an ASP .NET MVC 5 Web API project and added the Entity Framework model and other things to get it working with ASP. NET Identity.

相关标签:
1条回答
  • 2021-02-04 15:01

    You can send over the current logged on user like so:

        var handler = new HttpClientHandler();
        handler.UseDefaultCredentials = true;
        _httpClient = new HttpClient(handler);
    

    then you can create your own authorization filter

    public class MyAPIAuthorizationFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            //perform check here, perhaps against AD group, or check a roles based db?
            if(success)
            {
                base.OnActionExecuting(actionContext);
            }
            else
            {
                var msg = string.Format("User {0} attempted to use {1} but is not a member of the AD group.", id, actionContext.Request.Method);
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent(msg),
                    ReasonPhrase = msg
                });
            }
        }
    }
    

    then use [MyAPIAuthorizationFilter] on each action in your controller that you want to secure.

    0 讨论(0)
提交回复
热议问题