San Tommaso eh...
Ci provo:
Partendo dal presupposto che se hai intenzione di utilizzare html e javascript per il client, ti conviene andare sulle web api e comunicare in json. Detto ci�, ti dovrai basare su un servizio che funge da servizio di autenticazione, con ad esempio un metodo "login", dentro esso dovrai impostare un cookie per l'autenticazione form in caso di credenziali corrette, a questo punto sei autenticato e puoi decidere cosa passa e cosa no.
Inoltre puoi anche utilizzare i ruoli con un piccolo trucchetto, con questi potrai autorizzare o meno le richieste varie. Un esempio passo-passo:
1) Crea un nuovo progetto ASP.NET vuoto (spunta WebAPI)
2) nel file "WebApiConfig.cs" (dentro App_Start) modifica in questo modo:
codice:
public static void Register(HttpConfiguration config)
{
// Servizi e configurazione dell'API Web
// Route dell'API Web
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
3)aggiungi un nuovo elemento e scegli controller, il codice d'esempio da usare potrebbe essere questo:
codice:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using System.Web.Security;
namespace Kahm_Auth
{
public class AuthController : ApiController
{
public Utente Login([FromBody]Authentication Auth)
{
Utente utente = null;
if (Auth.User == "kahm" && Auth.Password == "sondaggio")
utente = new Utente() { Nome = "kahm", Cognome = "Sondaggio", Eta = "42" };
else
throw new Exception("Errore autenticazione");
var ticket = new FormsAuthenticationTicket(
version: 1,
name: utente.Nome,
issueDate: DateTime.Now,
expiration: DateTime.Now.AddYears(1),
isPersistent: false,
userData: "Admin|User|AltroRuolo");
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Current.Response.Cookies.Add(cookie);
return utente;
}
public bool Logout()
{
FormsAuthentication.SignOut();
return true;
}
[HttpGet]
[Authorize(Roles = "Admin")]
public HttpResponseMessage RequestAdmin()
{
var encoding = new System.Text.UTF8Encoding();
//var htm = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/Admin.asp"), encoding);
var response = new HttpResponseMessage();
response.Content = new StringContent("Ciao Admin", encoding);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
[HttpGet]
[Authorize(Roles = "Dev")]
public HttpResponseMessage RequestDev()
{
var encoding = new System.Text.UTF8Encoding();
//var htm =System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/Dev.asp"), encoding);
var response = new HttpResponseMessage();
response.Content = new StringContent("Ciao Dev", encoding);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
}
public class Utente
{
public string Nome { get; set; }
public string Cognome { get; set; }
public string Eta { get; set; }
}
public class Authentication
{
public string Password { get; set; }
public string User { get; set; }
}
}
in questo file ci saranno le chiamate per il login, logout, e due chiamate che restituiscono un risultato solo se l'utente che li chiama � autenticato e possiede il ruolo relativo appropriato. Come puoi notare nel login carico nel ticket (userData: "Admin|User|AltroRuolo") una stringa che poi andr� a "splittare" per caricare i ruoli (puoi passarla come ti pare, non necessariamente in questa forma), per fare ci� dovrai scrivere nel global.asax questo :
codice:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Http;
using System.Web.Routing;
using System.Web.Security;
namespace Kahm_Auth
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
public override void Init()
{
base.PostAuthenticateRequest += OnAuthenticateRequest;
}
protected void Application_PostAuthorizeRequest()
{
System.Web.HttpContext.Current.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Required);
}
private void OnAuthenticateRequest(object sender, EventArgs eventArgs)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
var decodedTicket = FormsAuthentication.Decrypt(cookie.Value);
var roles = decodedTicket.UserData.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
var principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
HttpContext.Current.User = principal;
}
}
}
}
qui una volta autenticato potrai "splittare" i ruoli caricati in precedenza e potrai caricarli definitivamente nell'user.
4) aggiungi l'autenticazione form nel web.config, nella sezione "<system.web>":
codice:
<authentication mode="Forms">
<forms loginUrl="index.html" name=".ASPXFORMSAUTH" />
</authentication>
5) aggiungi una pagina html e nominala index.html, dopo puoi usare questo per fare il login :
codice:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta charset="utf-8" />
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<input type="text" id="user" />
<input type="password" id="password" />
<button onclick="login()">Invia</button>
<a href="/api/Auth/RequestAdmin">Admin</a>
<a href="/api/Auth/RequestDev">Dev</a>
<button onclick="logout()">Esci</button>
<script>
function login() {
var User = $('#user').val()//.value();
var Password = $('#password').val();
var requestData = { User: $.trim(User), Password: $.trim(Password) };
$.ajax({
url: '/api/Auth/Login',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert(xhr.statusText);
},
success: function (res) {
alert("ciao " + res.Nome);
}
});
}
function logout() {
$.ajax({
url: '/api/Auth/Logout',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (res) {
}
});
}
</script>
</body>
</html>
In soldoni con questa paginetta non faccio altro che chiamare il servizio passando le credenziali, se sono corrette allora potr� accedere al link "Admin", ma non a quello "Dev", in quanto nonostante sia autenticato, nel login non ho impostato appositamente il ruolo "Dev" per mostrarti come sia possibile anche usare i ruoli.