MVC Authorization Certification

Source: Internet
Author: User

In the security considerations, MVC can complete the authorization authentication, the way of authorizing authentication is as follows:

1, configure config file, set the login page:

<authentication mode="Forms">      <forms loginurl="~/ Authentication/login "timeout="2880" />      <!--<forms cookieless="useuri " loginurl="~/authentication/login "></forms>-->    </authentication>

2. Action Add authorization Authentication attribute authorize:

[Authorize] PublicActionResult Index () {Employeebusinesslayer Empbal=NewEmployeebusinesslayer (); List<Employee> employees=empbal.getemployees (); List<EmployeeViewModel> Empviewmodels =NewList<employeeviewmodel>(); foreach(Employee emtpinchemployees) {Employeeviewmodel vmemp=NewEmployeeviewmodel (); Vmemp.employeename= Emtp. FirstName +" "+Emtp.                LastName; Vmemp.salary= Emtp. Salary.tostring ("C"); if(EMTP. Salary >15000) {Vmemp.salarycolor="Yellow"; }                Else{Vmemp.salarycolor="Green";            } empviewmodels.add (Vmemp); } Employeelistviewmodel Currlistmodel=NewEmployeelistviewmodel (); Currlistmodel. UserName=User.Identity.Name; Currlistmodel. Employees=Empviewmodels; returnView (Currlistmodel); }

Note: Display current user information, User.Identity.Name get

3, set up authorization authentication.

Formsauthentication.setauthcookie (Udemail. UserName, false);//indicates identity authentication

FormsAuthentication.SignOut ();//Sign Out of identity authentication

The login page code is as follows:

@using mymvc3demo.models; @model userdetails@{Layout=NULL;}<! DOCTYPE html>".. /.. /scripts/jquery-1.8.0.min.js"Type="Text/javascript"></script> <script src=".. /.. /scripts/jquery.validate.js"Type="Text/javascript"></script> <script src=".. /.. /scripts/jquery.validate.unobtrusive.js"Type="Text/javascript"></script>@Html. Validationmessage ("Credentialerror",New{style ="color:red;"}) @using (Html.BeginForm ("Dologin","Authentication", FormMethod.Post)) {@Html. labelfor (c=c.username) @Html. Textboxfor (x=x.username) @Html. Validationmessagefor (x=x.username)<br/>@Html. Labelfor (c=C.password) @Html. Passwordfor (c=C.password)<br/> <input type="Submit"Name="btnsubmit"Value="Login"/>        }    </div></body>
Note 1: @Html. Textboxfor (x=>x.username) converted to Html code <IDnametype   Value/>

2: @using (Html.BeginForm ("Dologin", "Authentication", FormMethod.Post)) {}

Convert to HTML code <form action= "/authentication/dologin" method= "POST" > </form>

The control code is as follows:
         PublicActionResult Login () {returnView (); }         PublicActionResult Logout () {formsauthentication.signout (); returnRedirecttoaction ("Login"); } [HttpPost] Publicactionresult Dologin (userdetails udemail) {if(modelstate.isvalid) {Employeebusinesslayer BLL=NewEmployeebusinesslayer (); if(BLL. Isvaliduser (Udemail)) {Formsauthentication.setauthcookie (udemail. UserName,false); returnRedirecttoaction ("Index","Employee"); }                Else{modelstate.addmodelerror ("Credentialerror","Invalid Username or Password"); returnView ("Login"); }            }            Else {                returnView ("Login"); }        }

Modelstate.isvalid is the calibration of the model type;

Modelstate.addmodelerror (), custom error type, convenient for foreground display;

@Html. Validationmessage ("Credentialerror", new {style = "color:red;"  })

Add:

displaying error messages with the client

1. Select "Manage Nuget packages", click Online to find "jquery unobtrusive", install "Microsoft jquery unobtrusive valiadtion"

2, Quote JS

    • Jquery-someversion.js
    • JQuery.valiadte.js
    • Jquery.validate.unobtrusive

3, the main reason to use unobtrusive to display error messages in the HTMLHelp class can be

@Html. Textboxfor (X=>x.username)
@Html. Validationmessagefor (X=>x.username)
Converted Into
<input data-val="true" data-val-length="UserName length should be between 2 and 7" data-val-length-max="7 "Data-val-length-min=" 2 "id=" UserName "name=" UserName "type=value=" "/>   
class="Field-validation-error" data-valmsg-for="UserName" data-valmsg-replace="true" > </ Span>
and data-val-length is the unbtrusive built-in data property, so you can use the front-end intercept error message

MVC Authorization Certification

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.