简体   繁体   中英

Authentication fails for get request using Asp.net Identity

I have a Api Controller which returns a image for get request. I want to authorize this request. So I added the Authorize attribute to action. I am using Asp.net Identity framework for authorization. When I run my application I logged in to application using username/password sending to /Token via ajax. Then I get the access_token and store it. Problem is when I reference an Image tag with src attrib (which that src points to the above said api controller), I don't have a way to send access token with that. How will i implement this?

    public partial class Startup
{
    static Startup()
    {
        PublicClientId = "self"; 
        UserManagerFactory = () => new UserManager<User>(new UserStore<User>(new ImagePerfektDbContext())); 
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            AllowInsecureHttp = true
        };
    }

    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public static Func<UserManager<User>> UserManagerFactory { get; set; }

    public static string PublicClientId { get; private set; } 
    public void ConfigureAuth(IAppBuilder app)
    { 
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login")
        });
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 
        app.UseOAuthBearerTokens(OAuthOptions);

I see what you mean. It's never a good idea to append the access token in the src attribute URL as a route parameter either.

What I would do...assuming you are storing the access token in the authentication ticket, I would mark the action method with "Anonymous" action filter and remove the "Authorize" action filter. Then, inside the action method code, I would attempt to retrieve the access token from authentication ticket (or wherever you are storing it), validate it and finally return the image, or not, based on the success of the validation.

I hope it makes sense

Leo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM