MVC ASP.NET – 手动授权某人并通过表单身份验证保留授权

我想要ASP.NET中的表单身份验证的好处.我希望它能继续授权我这样,但是我的情况有一点不同;我想对一个简单的Web服务(特别是由客户端提供)进行身份验证.

我有我的代码来查看Web位置并查看它们是否应该被授权,但是如何在ASP.NET中设置cookie [?]或授权标志,他们知道当前用户已获得授权.

基本上…

if (HttpContext.Current.User.Identity.IsAuthenticated)
// we're all good

//Other wise...
bool success = CheckClientsWebService(string username,string password);

if (success)
// Somehow tell .NET that they're authorized

*注意:这是一个相当简单的服务,不处理组或角色.只需检查用户是否可以查看该站点.

解决方法

在表单中,身份验证不能证明您是谁在表单身份验证cookie中.考虑到这一点,您无法在自定义登录表单中创建票证而无需创建自定义提供程序?我绝对认为你可以.进行快速测试并创建表单身份验证票证,并查看开箱即用的成员资格提供程序是否认为用户已通过身份验证.

我很好奇 – 所以这里有一些代码..

模型

public class SignInViewModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

调节器

public class SignInController : Controller
{

    public ActionResult Index()
    {
        var model = new SignInViewModel {};
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(SignInViewModel model)
    {
        if (model.Username == "Fred" && model.Password == "Mertz")
        {
            FormsAuthentication.SetAuthCookie(model.Username,false);
            return RedirectToAction("Secure");
        }
        return View(model);
    }

    [Authorize]
    public ActionResult Secure(SignInViewModel model)
    {
        return View();
    }

    [Authorize]
    public ActionResult Logout(SignInViewModel model)
    {
        FormsAuthentication.SignOut();
        return RedirectToAction("Index");
    }

Index.cshtml

@using (Html.BeginForm()) {
    <fieldset>
        <legend>SignInViewModel</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Username)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Username)
            @Html.ValidationMessageFor(model => model.Username)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

        <p>
            <input type="submit" value="Login" />
        </p>
    </fieldset>
}

Secure.cshtml

<h2>Secure</h2>
@Html.ActionLink("Logout","Logout")

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....