2013-08-17 44 views
12

Tôi đang cố gắng thiết lập các mẫu DotNetOpenAuth để có giải pháp SSO hoạt động với nhà cung cấp tùy chỉnh. Tôi đang sử dụng dự án mẫu OpenIdProviderMvc có vẻ hoạt động tốt.Dấu hiệu đơn lẻ Dotnetopenauth với nhà cung cấp thông tin nhận dạng tùy chỉnh

Sự cố của tôi đang thiết lập "người tiêu dùng", trong trường hợp này là dự án mẫu OpenIdRelyingPartyMvc, tôi không thể định cấu hình nó để sử dụng OpenIdProvider.

Tôi cố gắng để thiết lập một thiết bị đầu cuối trên web.config của người tiêu dùng như thế này:

<trustedProviders rejectAssertionsFromUntrustedProviders="true"> 
    <add endpoint="http://localhost:4864/OpenID/Provider" /> 
</trustedProviders> 

Nhưng tất cả tôi nhận được là "Không endpoint OpenID được tìm thấy." lỗi (thực ra, tôi không chắc chắn về những gì để đưa vào hộp OpenID ...)

Dự án này hầu như không có giấy tờ. Ai đó có thể chỉ cho tôi đi đúng hướng?

Ít nhất để có một nhà cung cấp và người tiêu dùng làm việc và nói chuyện với nhau?

+0

Đối với những gì nó có giá trị: tôi gặp phải không có vấn đề chạy các mẫu (https://github.com/DotNetOpenAuth/DotNetOpenAuth). Tôi đã không bỏ ghi chú phần nhà cung cấp đáng tin cậy, bắt đầu hai trường hợp trong VS cho máy chủ và máy khách và chỉ cần nhập http: // localhost: 4864 vào hộp OpenId. Theo mặc định, tôi đoán client mẫu sẽ chấp nhận bất kỳ nhà cung cấp openId nào. – jbl

Trả lời

7

Chúng ta hãy bắt đầu:

1- Mở Visual Studio 2010 vào File> New> Project> Web> ASP.NET MVC 3 Ứng dụng:

enter image description here

sau đó Chọn ứng dụng Internet hãy chắc chắn có Razor như Xem động cơ của bạn và nhấn OK:

enter image description here

2- Download Assets folder, nó chứa DotNetOpenAuth dll và các tập tin OpenID-Selector mà chúng ta sẽ sử dụng,

Hãy thoải mái nếu bạn muốn đi đến các dự án này và khám phá chúng trong biết thêm chi tiết.

Giải nén nó vào thư mục bạn muốn

a - Add the DotNetOpenAuth.dll to references in your site. 

    b- Delete all files/folders in Site Content folder. 

    c- Copy Assets Content files/folders to the site Content . 

    d- Copy the Assets Script files to the site Script. 

.

dự án của bạn sẽ trông như thế này:

enter image description here

3- Tới xem> Shared> _Layout.cshtml và thay thế với người đứng đầu mới này, chúng ta chỉ cần thêm các phong cách mới và kịch bản:

<head> 
    <title>@ViewBag.Title</title> 
    <link href="@Url.Content("~/Content/Site.css")" 
    rel="stylesheet" type="text/css" /> 
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" 
    type="text/javascript"></script> 
    <link href="@Url.Content("~/Content/openid-shadow.css")" 
    rel="stylesheet" type="text/css" /> 
    <link href="@Url.Content("~/Content/openid.css")" 
    rel="stylesheet" type="text/css" /> 
    <script src="@Url.Content("~/Scripts/openid-en.js")" 
    type="text/javascript"></script> 
    <script src="@Url.Content("~/Scripts/openid-jquery.js")" 
    type="text/javascript"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      openid.init('openid_identifier'); 
     }); 
    </script> 
</head> 

4- Chuyển đến Mô hình> Mô hình tài khoản.cs, điều hướng đến public class LogOnModel

và Thêm thuộc tính OpenID rằng chúng tôi sẽ sử dụng nó để giữ OpenID trở về từ OpenID-Selector

lớp học của bạn sẽ trông như thế này:

public class LogOnModel 
{ 
    [Display(Name = "OpenID")] 
    public string OpenID { get; set; } 

    [Required] 
    [Display(Name = "User name")] 
    public string UserName { get; set; } 

    [Required] 
    [DataType(DataType.Password)] 
    [Display(Name = "Password")] 
    public string Password { get; set; } 

    [Display(Name = "Remember me?")] 
    public bool RememberMe { get; set; } 
} 

điều hướng đến cộng đồng lớp RegisterModel và Thêm OpenID thuộc tính

public class RegisterModel 
{ 

    [Display(Name = "OpenID")] 
    public string OpenID { get; set; } 

    [Required] 
    [Display(Name = "User name")] 
    public string UserName { get; set; } 

    [Required] 
    [DataType(DataType.EmailAddress)] 
    [Display(Name = "Email address")] 
    public string Email { get; set; } 

    [Required] 
    [ValidatePasswordLength] 
    [DataType(DataType.Password)] 
    [Display(Name = "Password")] 
    public string Password { get; set; } 

    [DataType(DataType.Password)] 
    [Display(Name = "Confirm password")] 
    [Compare("Password", ErrorMessage = 
    "The password and confirmation password do not match.")] 
    public string ConfirmPassword { get; set; } 
} 

Sau đó đi đến phần Dịch vụ trong AccountModels.cs

và Sửa đổi CreateUser và Thêm GetUser để có được những người dùng bằng OpenID, giao diện của bạn

sẽ trông như thế này:

public interface IMembershipService 
{ 
    int MinPasswordLength { get; } 
    bool ValidateUser(string userName, string password); 
    MembershipCreateStatus CreateUser(string userName, string password, 
             string email, string OpenID); 
    bool ChangePassword(string userName, string oldPassword, string newPassword); 
    MembershipUser GetUser(string OpenID); 
} 

Thêm những sử dụng để AccountModels.cs

using System.Security.Cryptography; 
using System.Text; 

Sau đó, Thêm chức năng này vào AccountModels.cs, chức năng này sẽ được sử dụng để chuyển đổi OpenID thành GUID

Lưu ý : cảm thấy tự do để sử dụng băm tốt hơn cho hệ thống của bạn, MD5 đã có một số vấn đề va chạm.

public Guid StringToGUID(string value) 
{ 
    // Create a new instance of the MD5CryptoServiceProvider object. 
    MD5 md5Hasher = MD5.Create(); 
    // Convert the input string to a byte array and compute the hash. 
    byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(value)); 
    return new Guid(data); 
} 

Cũng thay đổi chức năng CreateUser trông như thế này:

public MembershipCreateStatus CreateUser(string userName, string password, 
             string email , string OpenID) 
{ 
    if (String.IsNullOrEmpty(userName)) throw 
    new ArgumentException("Value cannot be null or empty.", "userName"); 
    if (String.IsNullOrEmpty(password)) throw 
    new ArgumentException("Value cannot be null or empty.", "password"); 
    if (String.IsNullOrEmpty(email)) throw 
    new ArgumentException("Value cannot be null or empty.", "email"); 

    MembershipCreateStatus status; 
    _provider.CreateUser(userName, password, email, null, null, true, 
          StringToGUID(OpenID), out status); 
    return status; 
} 

Ở đây chúng ta đang sử dụng ProviderUserKey thành viên để lưu trữ các OpenID và thủ thuật ở đây là chúng ta chuyển đổi chuỗi OpenID để GUID được sử dụng bằng các phương thức CreateUser và GetUser.

Bây giờ chúng ta thêm chức năng này để AccountModels.cs rằng sẽ nhận người dùng bằng OpenID:

public MembershipUser GetUser(string OpenID) 
{ 
    return _provider.GetUser(StringToGUID(OpenID), true); 
} 

5- đi để xem> Tài khoản> LogOn.cshtml

thay thế tất cả các đánh dấu với điều này một, chúng tôi đang tích hợp OpenID-Selector để đăng nhập xem:

@model OpenIDMVC3.Models.LogOnModel 
@{ 
    ViewBag.Title = "Log On"; 
} 
<h2> 
    Log On</h2> 
<p> 
    Please enter your username and password. @Html.ActionLink("Register", "Register") 
    if you don't have an account. 
</p> 
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> 
</script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" 
    type="text/javascript"></script> 
<form action= 
"[email protected](Request.QueryString["ReturnUrl"])" 
method="post" id="openid_form"> 
<input type="hidden" name="action" value="verify" /> 
<div> 
    <fieldset> 
     <legend>Login using OpenID</legend> 
     <div class="openid_choice"> 
      <p> 
       Please click your account provider:</p> 
      <div id="openid_btns"> 
      </div> 
     </div> 
     <div id="openid_input_area"> 
      @Html.TextBox("openid_identifier") 
      <input type="submit" value="Log On" /> 
     </div> 
     <noscript> 
      <p> 
       OpenID is service that allows you to log-on to many different websites 
       using a single indentity. Find out <a href="http://openid.net/what/"> 
       more about OpenID</a>and <a href="http://openid.net/get/"> 
       how to get an OpenID enabled account</a>.</p> 
     </noscript> 
     <div> 
      @if (Model != null) 
      { 
       if (String.IsNullOrEmpty(Model.UserName)) 
       { 
       <div class="editor-label"> 
        @Html.LabelFor(model => model.OpenID) 
       </div> 
       <div class="editor-field"> 
        @Html.DisplayFor(model => model.OpenID) 
       </div> 
       <p class="button"> 
        @Html.ActionLink("New User ,Register", "Register", 
             new { OpenID = Model.OpenID }) 
       </p> 
       } 
       else 
       { 
        //user exist 
       <p class="buttonGreen"> 
        <a href="@Url.Action("Index", "Home")">Welcome , @Model.UserName, 
        Continue..." </a> 
       </p> 

       } 
      } 
     </div> 
    </fieldset> 
</div> 
</form> 

@Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors 
                and try again.") 
@using (Html.BeginForm()) 
{ 
    <div> 
     <fieldset> 
      <legend>Or Login Normally</legend> 
      <div class="editor-label"> 
       @Html.LabelFor(m => m.UserName) 
      </div> 
      <div class="editor-field"> 
       @Html.TextBoxFor(m => m.UserName) 
       @Html.ValidationMessageFor(m => m.UserName) 
      </div> 
      <div class="editor-label"> 
       @Html.LabelFor(m => m.Password) 
      </div> 
      <div class="editor-field"> 
       @Html.PasswordFor(m => m.Password) 
       @Html.ValidationMessageFor(m => m.Password) 
      </div> 
      <div class="editor-label"> 
       @Html.CheckBoxFor(m => m.RememberMe) 
       @Html.LabelFor(m => m.RememberMe) 
      </div> 
      <p> 
       <input type="submit" value="Log On" /> 
      </p> 
     </fieldset> 
    </div> 
} 

6- Bây giờ chúng ta hãy chạy dự án, sau đó nhấp vào [Log On] liên kết, bạn sẽ nhận được như trang này:

ws

7- Tới điều khiển> AccountController.cs và Thêm những cách sử dụng:

using DotNetOpenAuth.Messaging; 
using DotNetOpenAuth.OpenId; 
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; 
using DotNetOpenAuth.OpenId.RelyingParty; 
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; 

Sau đó thêm thuộc tính này để AccountController.cs:

private static OpenIdRelyingParty openid = new OpenIdRelyingParty(); 

Sau đó, Thêm Chức năng này vào AccountController.cs:

[ValidateInput(false)] 
public ActionResult Authenticate(string returnUrl) 
{ 
    var response = openid.GetResponse(); 
    if (response == null) 
    { 
     //Let us submit the request to OpenID provider 
     Identifier id; 
     if (Identifier.TryParse(Request.Form["openid_identifier"], out id)) 
     { 
      try 
      { 
       var request = openid.CreateRequest(
             Request.Form["openid_identifier"]); 
       return request.RedirectingResponse.AsActionResult(); 
      } 
      catch (ProtocolException ex) 
      { 
       ViewBag.Message = ex.Message; 
       return View("LogOn"); 
      } 
     } 

     ViewBag.Message = "Invalid identifier"; 
     return View("LogOn"); 
    } 

    //Let us check the response 
    switch (response.Status) 
    { 

     case AuthenticationStatus.Authenticated: 
      LogOnModel lm = new LogOnModel(); 
      lm.OpenID = response.ClaimedIdentifier; 
      // check if user exist 
      MembershipUser user = MembershipService.GetUser(lm.OpenID); 
      if (user != null) 
      { 
       lm.UserName = user.UserName; 
       FormsService.SignIn(user.UserName, false); 
      } 

      return View("LogOn", lm); 

     case AuthenticationStatus.Canceled: 
      ViewBag.Message = "Canceled at provider"; 
      return View("LogOn"); 
     case AuthenticationStatus.Failed: 
      ViewBag.Message = response.Exception.Message; 
      return View("LogOn"); 
    } 

    return new EmptyResult(); 
} 

8 - Bây giờ chạy dự án nhấp chuột [Log On] liên kết và nhấp vào một nhà cung cấp như Google

nó có thể yêu cầu bạn đăng nhập hoặc yêu cầu bạn cho phép truy cập thông tin của bạn

bạn sẽ nhận được một trang như thế này:

enter image description here

như bạn có thể thấy nó sẽ hiển thị OpenID của bạn và một nút chỉ ra rằng đây là người dùng mới chưa đăng ký,

trước khi nhấn nút [Người dùng mới, Đăng ký], chúng tôi cần sửa đổi chế độ xem Đăng ký và bộ điều khiển để truy cập thông tin OpenID.

9 Tới điều khiển> AccountController.cs thay thế [ActionResult Đăng ký()] của thành viên này:

public ActionResult Register(string OpenID) 
{ 
    ViewBag.PasswordLength = MembershipService.MinPasswordLength; 
    ViewBag.OpenID = OpenID; 
    return View(); 
} 

Và Sửa đổi [ActionResult Register (model RegisterModel)] để sử dụng OpenID khi

tạo người dùng:

[HttpPost] 
public ActionResult Register(RegisterModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     // Attempt to register the user 
     MembershipCreateStatus createStatus = 
     MembershipService.CreateUser(model.UserName, model.Password, 
             model.Email,model.OpenID); 

     if (createStatus == MembershipCreateStatus.Success) 
     { 
      FormsService.SignIn(model.UserName, false); 
      return RedirectToAction("Index", "Home"); 
     } 
     else 
     { 
      ModelState.AddModelError("", 
      AccountValidation.ErrorCodeToString(createStatus)); 
     } 
    } 

    // If we got this far, something failed, redisplay form 
    ViewBag.PasswordLength = MembershipService.MinPasswordLength; 
    return View(model); 
} 

10- tới xem> Tài khoản> Register.cshtml, thay thế đánh dấu bằng cách này:

@model OpenIDMVC3.Models.RegisterModel 
@{ 
    ViewBag.Title = "Register"; 
} 

<h2>Create a New Account</h2> 
<p> 
    Use the form below to create a new account. 
</p> 
<p> 
    Passwords are required to be a minimum of @ViewBag.PasswordLength 
    characters in length. 
</p> 

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" 
    type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" 
    type="text/javascript"></script> 

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true, "Account creation was unsuccessful. 
              Please correct the errors and try again.") 
    <div> 
     <fieldset> 
      <legend>Account Information</legend> 
      @if (ViewData["OpenID"] != null) 
      { 
      <div class="editor-label"> 
       @Html.Label("OpenID") 
      </div> 
      <div class="editor-label"> 
       @Html.Label((string)ViewBag.OpenID) 
      </div> 
      } 
      <div class="editor-label"> 
       @Html.LabelFor(m => m.UserName) 
      </div> 
      <div class="editor-field"> 
       @Html.TextBoxFor(m => m.UserName) 
       @Html.ValidationMessageFor(m => m.UserName) 
      </div> 

      <div class="editor-label"> 
       @Html.LabelFor(m => m.Email) 
      </div> 
      <div class="editor-field"> 
       @Html.TextBoxFor(m => m.Email) 
       @Html.ValidationMessageFor(m => m.Email) 
      </div> 

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

      <div class="editor-label"> 
       @Html.LabelFor(m => m.ConfirmPassword) 
      </div> 
      <div class="editor-field"> 
       @Html.PasswordFor(m => m.ConfirmPassword) 
       @Html.ValidationMessageFor(m => m.ConfirmPassword) 
      </div> 

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

11 Đến bước 8 và chúng ta hãy nhấn [Người dùng mới, Đăng ký] nút, bạn sẽ có được điều này:

enter image description here

12- đăng ký bất kỳ tài khoản bạn muốn, bạn sẽ nhận được như trang này :

enter image description here

13- Bấm [Log Off] và đăng nhập lại bằng cách sử dụng cùng một OpenID, bạn sẽ nhận được như trang này:

enter image description here

Như bạn có thể thấy nút chào mừng màu xanh lá cây phát hiện người dùng này đã được đăng ký.

14- Nhấp vào nút màu xanh lá cây, bạn sẽ nhận được một trang như thế này:

enter image description here

Xin chúc mừng! , bây giờ bạn đã tích hợp OpenID cho dự án của bạn.

Reference

+0

Hướng dẫn rất đầy đủ ... Liên kết tham chiếu dường như không trỏ đến những gì bạn nghĩ. –

+1

Cảm ơn nhưng, làm cách nào để liên kết điều này với nhà cung cấp tùy chỉnh? tức là nhà cung cấp xác thực của riêng tôi? – tggm