WEB API-在控制器或操作级别进行授权(不进行身份验证) [英] WEB API - Authorize at controller or action level (no authentication)

查看:313
本文介绍了WEB API-在控制器或操作级别进行授权(不进行身份验证)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个没有身份验证的现有API.它是一个公共Web API,多个客户端通过发出简单的请求即可使用.

I have an existing API that has No Authentication. It`s a public Web API which several clients use by making simple requests.

现在,需要授权访问某种方法.

Now, there is the need to authorize access to a certain method.

是否有任何方法可以使其余的控制器和相应方法对已经使用此Web API的客户端保持打开"状态?

Is there any way to do this, keeping the rest of the controllers and respective methods "open" for the clients that already use this Web API?

如何确定请求是否具有访问此受保护"方法的权限?

How can i identify if the request has permissions to access this "protected" method?

推荐答案

您需要做的是使用要接受的一个或多个角色名称的重载(可选)向要保护的方法中添加一个[Authorize]属性.主叫用户必须在其中.

What you'll need to do is add an [Authorize] attribute to the methods you want to protect optionally using the overload that accepts one or more role names that the calling user must be in.

然后,您将必须实现的一种方法,可以确保将调用方的身份验证数据转换为Principal对象.设置Principal通常不是您自己要做的,而是让框架为您完成.

Then what you'll have to implement is a way to ensure that authentication data of the caller is transformed into a Principal object. Setting the Principal is generally something you don't do yourself, but instead have the framework do for you.

如果确实要提供自己的接口,则可以使用实现System.Web.Http.Filters.IAuthenticationFilter接口的身份验证筛选器.

If you do want to provide your own interface, you can using an authentication filter implementing the System.Web.Http.Filters.IAuthenticationFilter interface.

那么你会得到的是

[MyAuthentication]
[Authorize]
public SomeClass MyProtectedMethod() {
    return new SomeClass();
}

,然后实现MyAuthentication属性.下面是一个示例,重要的是您使用传入请求的上下文并最终使用新的Principal设置context.Principal属性

And then implement the MyAuthentication attribute. Below is an example, the important thing is that you use the context of the incoming request and end up setting the context.Principal property with a new Principal

public class MyAuthentication : ActionFilterAttribute, System.Web.Http.Filters.IAuthenticationFilter {

    public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        // 1. Look for credentials in the request.
        HttpRequestMessage request = context.Request;
        AuthenticationHeaderValue authorization = request.Headers.Authorization;

        // 2. If there are no credentials, do nothing.
        if (authorization == null)
        {
            return;
        }

        // 3. If there are credentials but the filter does not recognize the 
        //    authentication scheme, do nothing.
        if (authorization.Scheme != "Basic")
        {
            return;
        }

        // 4. If there are credentials that the filter understands, try to validate them.
        // 5. If the credentials are bad, set the error result.
        if (String.IsNullOrEmpty(authorization.Parameter))
        {
            context.ErrorResult = new AuthenticationFailureResult("Missing credentials", request);
            return;
        }

        Tuple<string, string> userNameAndPasword = ExtractUserNameAndPassword(authorization.Parameter);
        if (userNameAndPasword == null)
        {
            context.ErrorResult = new AuthenticationFailureResult("Invalid credentials", request);
        }

        string userName = userNameAndPasword.Item1;
        string password = userNameAndPasword.Item2;

        IPrincipal principal = await AuthenticateAsync(userName, password, cancellationToken);
        if (principal == null)
        {
            context.ErrorResult = new AuthenticationFailureResult("Invalid username or password", request);
        }

        // 6. If the credentials are valid, set principal.
        else
        {
            context.Principal = principal;
        }

    }


    ... other interface methods here
}

我希望这可以帮助您走上正确的道路.有关更多信息,请查看此帖子: http://www.asp.net/web-api/overview/security /authentication-filters

I hope this helps you get on the right track. For more information check this post: http://www.asp.net/web-api/overview/security/authentication-filters

这篇关于WEB API-在控制器或操作级别进行授权(不进行身份验证)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆