且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WEB API-在控制器或操作级别进行授权(不进行身份验证)

更新时间:2023-12-03 20:18:58

您需要做的是使用要接受的一个或多个角色名称的重载(可选)向要保护的方法中添加一个[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