Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

c# - .net 5 how to setup authorization using custom provider

in my .net 5 website i have to read user login from header and the call external webservice to check if is authorized and get permission list.

I'using custom attribute to manage this scenario in this way:

public class MyAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter{
    public string[] Roles { get; set; }
    public void OnAuthentication(AuthenticationContext filterContext)
      {
        string MyHeaderToken = “SM_USER”;

        string userSSO = null;
        if (HttpContext.Current.Request.Headers[MyHeaderToken] != null)
        {
             userSSO = HttpContext.Current.Request.Headers[MyHeaderToken];
                Trace.WriteLine(string.Format(“got MyToken: {0}”, userSSO));
        }
        if (string.IsNullOrWhiteSpace(userSSO))
        {
                Trace.WriteLine(“access denied, no token found”);
        }
        else
        {
        // Create GenericPrincipal
        GenericIdentity webIdentity = new GenericIdentity(userSSO, “My”);
        string[] methods= GetMethods(userSSO);
        GenericPrincipal principal = new GenericPrincipal(webIdentity, methods);
        filterContext.HttpContext.User = principal; 
        }
    }
    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        //check authorizations
    }
}

but external webservice returns list of controller/action authorized for users, so i have to test all actions executions to simply check if names is contained in the list.

is there a way to do this without have to write attribute on every actions or every controllers in this way:

[MyAuthentication(Roles = “Admin”)]
pubic class AdminController: Controller
{
}

i know i can use

services.AddMvc(o =>
{
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    o.Filters.Add(new AuthorizeFilter(policy));
});

but no idea of how to use this with my custom authorization

i'am also not sure if string[] methods= GetMethods(userSSO) is cached by .net core filterContext.HttpContext.User avoiding multiple calls to external webservice.

Thanks

question from:https://stackoverflow.com/questions/65858115/net-5-how-to-setup-authorization-using-custom-provider

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...