Diskuze: ASP.NET MVC, Web API a HttpClient

C# .NET .NET (C# a Visual Basic) ASP.NET MVC, Web API a HttpClient American English version English version

Avatar
Majkel
Člen
Avatar
Majkel:

Ahoj, za pomoci HttpClienta dělám post na

http://localhost:63443/api/Hardware/VerifyMotherboard

ale v response dostanu pokaždé

RequestUri: {http://localhost:63443/Account/Login?ReturnUrl=%2Fapi%2FHardware%2FVerifyMotherboard}

ApiController nemá nastavený žádný autorizační atribut a vypadá takto:

public class HardwareController : ApiController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IMapper _mapper;
        private readonly ILogger _log;

        /// <summary>
        /// Konstruktor
        /// </summary>
        /// <param name="unitOfWork"></param>
        public HardwareController(IUnitOfWork unitOfWork, IMapper mapper, ILogger log)
        {
            _unitOfWork = unitOfWork;
            _mapper = mapper;
            _log = log;
        }

        [HttpPost]
        public HttpResponseMessage VerifyMotherboard([FromBody] MotherboardDTO model)
        {
            if (ModelState.IsValid)
            {
                MotherboardDTO motherboard = _mapper.Map<Motherboard, MotherboardDTO>(_unitOfWork.Motherboards.GetBySerialNumber(model.SerialNumber));
                if (motherboard != null)
                    return Request.CreateResponse(HttpStatusCode.OK, "");
            }

            return Request.CreateResponse(HttpStatusCode.BadRequest, "");
        }

kde dělám chybu?

Editováno 6. listopadu 18:40
 
Odpovědět 6. listopadu 18:39
Avatar
Marian Benčat
Redaktor
Avatar
Marian Benčat:

Koukni se do nastaveni treba do App_start / FiltersConfig.. nekde tam bude globalne nastaveny AuthorizeAttri­bute.. Neboli "whitelisting".

 
Nahoru Odpovědět 7. listopadu 5:56
Avatar
Majkel
Člen
Avatar
Majkel:

Ahoj, prošel jsem to nastavení a bohužel jsem nikde nenašel nic, co by autorizaci vynucovalo globálně.

FilterConfig:

public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }

IdentityConfig

public class EmailService : IIdentityMessageService
    {
        public Task SendAsync(IdentityMessage message)
        {
            // Plug in your email service here to send an email.
            return Task.FromResult(0);
        }
    }

    public class SmsService : IIdentityMessageService
    {
        public Task SendAsync(IdentityMessage message)
        {
            // Plug in your SMS service here to send a text message.
            return Task.FromResult(0);
        }
    }

    // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
    public class ApplicationUserManager : UserManager<AppUser, int>
    {
        public ApplicationUserManager(IUserStore<AppUser, int> store)
            : base(store)
        {
        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore<AppUser, AppRole, int, AppUserLogin, AppUserRole, AppUserClaim>(context.Get<WatcherContext>()));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<AppUser, int>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 3,
                RequireNonLetterOrDigit = false,
                RequireDigit = false,
                RequireLowercase = false,
                RequireUppercase = false,
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<AppUser, int>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<AppUser, int>
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider<AppUser, int>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }
    }

    // Configure the application sign-in manager which is used in this application.
    public class ApplicationSignInManager : SignInManager<AppUser, int>
    {
        public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
            : base(userManager, authenticationManager)
        {
        }

        public override Task<ClaimsIdentity> CreateUserIdentityAsync(AppUser user)
        {
            return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
        }

        public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
        {
            return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
        }
    }

StartupAuth

public partial class Startup
   {
       // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
       public void ConfigureAuth(IAppBuilder app)
       {
           // Configure the db context, user manager and signin manager to use a single instance per request
           app.CreatePerOwinContext(() => new WatcherContext());
           app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
           app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

           // Enable the application to use a cookie to store information for the signed in user
           // and to use a cookie to temporarily store information about a user logging in with a third party login provider
           // Configure the sign in cookie
           app.UseCookieAuthentication(new CookieAuthenticationOptions
           {
               AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
               LoginPath = new PathString("/Account/Login"),
               Provider = new CookieAuthenticationProvider
               {
                   // Enables the application to validate the security stamp when the user logs in.
                   // This is a security feature which is used when you change a password or add an external login to your account.
                   OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, AppUser, int>(
                       validateInterval: TimeSpan.FromMinutes(30),
                       regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                       getUserIdCallback: (id) => (Int32.Parse(id.GetUserId())))
               }
           });
           app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

           // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
           app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

           // Enables the application to remember the second login verification factor such as phone or email.
           // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
           // This is similar to the RememberMe option when you log in.
           app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

           // Uncomment the following lines to enable logging in with third party login providers
           //app.UseMicrosoftAccountAuthentication(
           //    clientId: "",
           //    clientSecret: "");

           //app.UseTwitterAuthentication(
           //   consumerKey: "",
           //   consumerSecret: "");

           //app.UseFacebookAuthentication(
           //   appId: "",
           //   appSecret: "");

           //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
           //{
           //    ClientId = "",
           //    ClientSecret = ""
           //});
       }
   }

WebApiConfig

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { action = "get", id = RouteParameter.Optional }
            );
        }
    }
 
Nahoru Odpovědět 7. listopadu 17:00
Avatar
Marian Benčat
Redaktor
Avatar
Marian Benčat:

Hmm zajimave.. chova se to jako kdyby to odchytaval normalne Membership (koukni jeste do web configu). Chova se to jak MVC :-/

 
Nahoru Odpovědět 9. listopadu 17:43
Avatar
Majkel
Člen
Avatar
Majkel:

Ona je to MVC aplikace, jejíž součástí je Web API. Což jsem koukám zapomněl sdělit...

 
Nahoru Odpovědět 9. listopadu 19:22
Děláme co je v našich silách, aby byly zdejší diskuze co nejkvalitnější. Proto do nich také mohou přispívat pouze registrovaní členové. Pro zapojení do diskuze se přihlas. Pokud ještě nemáš účet, zaregistruj se, je to zdarma.

Zobrazeno 5 zpráv z 5.