webapi与基本授权

时间:2017-04-22 17:07:39

标签: asp.net-mvc web-services

我用.NET创建了一个WebApi。 我想确保一些方法。 我想只有aspnetuser表中的用户才能执行这个方法

我创建了



public class BasicAuthHttpModule : IHttpModule




并在web.config中我将其配置为



<system.webServer>
    <modules>
        <add name="BasicAuthHttpModule" type="WebHostBasicAuth.Modules.BasicAuthHttpModule"/>
    </modules>    
</system.webServer>
&#13;
&#13;
&#13;

我的BasicAuthHttpModule.cs: 我用aspnetusers tabla

检查电子邮件和密码

&#13;
&#13;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;

using Microsoft.Owin;
using ServicioProx360.Models;
using ServicioProx360;


namespace WebHostBasicAuth.Modules
	{
	public class BasicAuthHttpModule: IHttpModule
		{
		private const string Realm = "WebAPI Authentication";

		public void Init(HttpApplication context)
			{
			// Se registran los manejadores de los eventos
			context.AuthenticateRequest += OnApplicationAuthenticateRequest;
			context.EndRequest += OnApplicationEndRequest;
			}

		private static void SetPrincipal(IPrincipal principal)
			{
			Thread.CurrentPrincipal = principal;
			if (HttpContext.Current != null)
				{
				HttpContext.Current.User = principal;
				}
			}

		private static bool AuthenticateUser(string credentials)
			{
			var encoding = Encoding.GetEncoding("iso-8859-1");
			credentials = encoding.GetString(Convert.FromBase64String(credentials));

			var credentialsArray = credentials.Split(':');
			var username = credentialsArray[0];
			var password = credentialsArray[1];

			var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

			ApplicationUser usuario = manager.Find(username, password);
			/* Aquí se validan las credenciales o el token enviado en el encabezado de la solicitud */
//			if (!(username == "test" && password == "test"))
			if (usuario==null)
				{
				return false;
				}
			
			var identity = new GenericIdentity(usuario.UserName);
			
			SetPrincipal(new GenericPrincipal(identity, new string[] { "CIUDADADNO" }));

			return true;
			}

		private static void OnApplicationAuthenticateRequest(object sender, EventArgs e)
			{
			var request = HttpContext.Current.Request;
			var authHeader = request.Headers["Authorization"];
			if (authHeader != null)
				{
				var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);

				// Se valida si el esquema de autenticación es básico (Basic Authentication)
				if (authHeaderVal.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) && authHeaderVal.Parameter != null)
					{
					AuthenticateUser(authHeaderVal.Parameter);
					}
				}
			}

		// Si la solicitud no fue aprobada, se agrega el encabezado WWW-Authenticate a la respuesta

		private static void OnApplicationEndRequest(object sender, EventArgs e)
			{
			var response = HttpContext.Current.Response;
			if (response.StatusCode == 401)
				{
				response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", Realm));
				}
			}
		public void Dispose()
			{
			}
		}
	}
&#13;
&#13;
&#13;

但它没有成功。如果方法是[授权],它会询问我的电子邮件和密码,我会输入正确的数据,但它会再次再次询问。

你能帮帮我吗?

非常感谢

1 个答案:

答案 0 :(得分:0)